1 | // Copyright 2004-2007 Jean-Francois Poilpret |
2 | // |
3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
4 | // you may not use this file except in compliance with the License. |
5 | // You may obtain a copy of the License at |
6 | // |
7 | // http://www.apache.org/licenses/LICENSE-2.0 |
8 | // |
9 | // Unless required by applicable law or agreed to in writing, software |
10 | // distributed under the License is distributed on an "AS IS" BASIS, |
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | // See the License for the specific language governing permissions and |
13 | // limitations under the License. |
14 | |
15 | package net.sourceforge.hivegui.component; |
16 | |
17 | import java.awt.EventQueue; |
18 | import java.awt.event.FocusEvent; |
19 | import java.awt.event.FocusListener; |
20 | |
21 | import javax.swing.JSpinner; |
22 | import javax.swing.text.JTextComponent; |
23 | |
24 | public class SelectAllFocusListener implements FocusListener |
25 | { |
26 | static private final FocusListener SELECT_ALL_FOCUS_LISTENER = |
27 | new SelectAllFocusListener(); |
28 | |
29 | // NB: must be called after the spinner has been added to the layout (why????) |
30 | static public void setAutoSelect(JSpinner spinner) |
31 | { |
32 | setAutoSelect(((JSpinner.DefaultEditor) spinner.getEditor()).getTextField()); |
33 | } |
34 | |
35 | static public void setAutoSelect(JTextComponent field) |
36 | { |
37 | field.addFocusListener(SELECT_ALL_FOCUS_LISTENER); |
38 | } |
39 | |
40 | public void focusGained(FocusEvent e) |
41 | { |
42 | if ( (!e.isTemporary()) |
43 | && (e.getComponent() instanceof JTextComponent)) |
44 | { |
45 | final JTextComponent field = (JTextComponent) e.getComponent(); |
46 | EventQueue.invokeLater(new Runnable() |
47 | { |
48 | public void run() |
49 | { |
50 | field.selectAll(); |
51 | } |
52 | }); |
53 | } |
54 | } |
55 | |
56 | public void focusLost(FocusEvent e) |
57 | { |
58 | if ( (!e.isTemporary()) |
59 | && (e.getComponent() instanceof JTextComponent)) |
60 | { |
61 | final JTextComponent field = (JTextComponent) e.getComponent(); |
62 | EventQueue.invokeLater(new Runnable() |
63 | { |
64 | public void run() |
65 | { |
66 | field.setCaretPosition(field.getText().length()); |
67 | } |
68 | }); |
69 | } |
70 | } |
71 | } |