How to select all text in a JFormattedTextField when it gets focus?

后端 未结 5 2016
孤独总比滥情好
孤独总比滥情好 2020-12-08 00:53

I have a small Java desktop app that uses Swing. There is a data entry dialog with some input fields of different types (JTextField, JComboBox, JSpinner, JFormattedTextField

5条回答
  •  感动是毒
    2020-12-08 01:14

    Thats because the JFormattedTextfield overrides processFocusEvent to format on focus gained/focus lost.

    One sure shot way is to extend JFormattedTextField and override the processFocusEvent method :

    new JFormattedTextField("...") {  
            protected void processFocusEvent(FocusEvent e) {  
                super.processFocusEvent(e);  
                if (e.isTemporary())  
                    return;  
                SwingUtilities.invokeLater(new Runnable() {  
                    @Override  
                    public void run() {  
                        selectAll();  
                    }   
                });  
            }  
        };
    

    Using a focusListener might not always work..since it would depend on the time at which it is called relative to the processFocusEvent.

提交回复
热议问题