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

后端 未结 5 2015
孤独总比滥情好
孤独总比滥情好 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:31

    The code of camickr can be slightly improved. When the focus passes from a JTextField to another kind of component (such a button), the last automatic selection does not get cleared. It can be fixed this way:

        KeyboardFocusManager.getCurrentKeyboardFocusManager()
            .addPropertyChangeListener("permanentFocusOwner", new PropertyChangeListener()
        {
            @Override
            public void propertyChange(final PropertyChangeEvent e)
            {
    
                if (e.getOldValue() instanceof JTextField)
                {
                        SwingUtilities.invokeLater(new Runnable()
                        {
                                @Override
                                public void run()
                                {
                                        JTextField oldTextField = (JTextField)e.getOldValue();
                                        oldTextField.setSelectionStart(0);
                                        oldTextField.setSelectionEnd(0);
                                }
                        });
    
                }
    
                if (e.getNewValue() instanceof JTextField)
                {
                        SwingUtilities.invokeLater(new Runnable()
                        {
                                @Override
                                public void run()
                                {
                                        JTextField textField = (JTextField)e.getNewValue();
                                        textField.selectAll();
                                }
                        });
    
                }
            }
        });
    

提交回复
热议问题