Events
Code low-level events
Focus
How to work with focus events
- A focus event occurs when the focus moves to or from a component.
- To implement a focus listener, you must implement both of the methods of the FocusListener interface.
Methods of the FocusListener interface
Method | Description |
---|---|
void focusGained(FocusEvent e) | Invoked when a component that implements a focus listener gains the focus. |
void focusLost(FocusEvent e) | Invoked when a component that implements a focus listener loses the focus. |
Common methods of the FocusEvent class
Method | Description |
---|---|
getComponent() | Returns the component where the event occurred. |
isTemporary() | Returns true if the focus is a temporary change. |
getOppositeComponent() | Returns the other component involved in the focus change. Introduced with JDK 1.4. |
A method of the JTextComponent class
Method | Description |
---|---|
selectAll() | Selects all of the text in the text component. |
A class that implements the FocusListener interface
public class AutoSelect implements FocusListener { public void focusGained(FocusEvent e) { if (e.getComponent() instanceof JTextField) { JTextField t = (JTextField) e.getComponent(); t.selectAll(); } } public void focusLost(FocusEvent e) {} }
A text field that uses the focus listener
paymentTextField = new JTextField(10); paymentTextField.addFocusListener(new AutoSelect()); displayPanel.add(paymentTextField);