Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class AutoClearingTextField extends JTextField {
- final FocusListener AUTO_CLEARING_LISTENER = new FocusListener(){
- @Override
- public void focusLost(FocusEvent e) {
- //onFocusLost(e);
- }
- @Override
- public void focusGained(FocusEvent e) {
- selectAll();
- }
- };
- public AutoClearingTextField(String string) {
- super(string);
- addListener();
- }
- private void addListener() {
- addFocusListener(AUTO_CLEARING_LISTENER);
- }
- }
- public class SelectAllListener implements FocusListener {
- private static INSTANCE = new SelectAllListener();
- public void focusLost(FocusEvent e) { }
- public void focusGained(FocusEvent e) {
- if (e.getSource() instanceof JTextComponent) {
- ((JTextComponent)e.getSource()).selectAll();
- }
- };
- public static void addSelectAllListener(JTextComponent tc) {
- tc.addFocusListener(INSTANCE);
- }
- public static void removeSelectAllListener(JTextComponent tc) {
- tc.removeFocusListener(INSTANCE);
- }
- }
- public static void addSelectAllListener(JSpinner spin) {
- if (spin.getEditor() instanceof JTextComponent) {
- addSelectAllListener((JTextComponent)spin.getEditor());
- }
- }
- public static void addSelectAllListener(JComboBox combo) {
- JComponent editor = combo.getEditor().getEditorComponent();
- if (editor instanceof JTextComponent) {
- addSelectAllListener((JTextComponent)editor);
- }
- }
- void addTextFocusSelect(JComponent component){
- if(component instanceof JTextComponent){
- component.addFocusListener(new FocusAdapter() {
- @Override
- public void focusGained(FocusEvent event) {
- super.focusGained(event);
- JTextComponent component = (JTextComponent)event.getComponent();
- // a trick I found on JavaRanch.com
- // Without this, some components don't honor selectAll
- component.setText(component.getText());
- component.selectAll();
- }
- });
- }
- else
- {
- for(Component child: component.getComponents()){
- if(child instanceof JComponent){
- addTextFocusSelect((JComponent) child);
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment