如何在JFormattedTextField获得焦点时选择它中的所有文本?

2022-09-01 05:35:43

我有一个使用Swing的小型Java桌面应用程序。有一个数据输入对话框,其中包含一些不同类型的输入字段(JTextField,JComboBox,JSpinner,JFormattedTextField)。当我通过按 Tab 键浏览表单或用鼠标单击表单来激活 JFormattedTextFields 时,我希望它选择它当前包含的所有文本。这样,用户就可以开始键入并覆盖默认值。

我该怎么做?我确实使用了一个FocusListener/FocusAdapter,它在JFormattedTextField上调用selectAll(),但它没有选择任何东西,尽管FocusAdapter的focusGained()方法被调用(参见下面的代码示例)。

private javax.swing.JFormattedTextField pricePerLiter;
// ...
pricePerLiter.setFormatterFactory(
    new JFormattedTextField.AbstractFormatterFactory() {
    private NumberFormatter formatter = null;
    public JFormattedTextField.AbstractFormatter 
        getFormatter(JFormattedTextField jft) {
        if (formatter == null) {
            formatter = new NumberFormatter(new DecimalFormat("#0.000"));
            formatter.setValueClass(Double.class);
        }
        return formatter;
    }
});
// ...
pricePerLiter.addFocusListener(new java.awt.event.FocusAdapter() {
    public void focusGained(java.awt.event.FocusEvent evt) {
        pricePerLiter.selectAll();
    }
});

有什么想法吗?有趣的是,选择其所有文本显然是JTextField和JSpinner的默认行为,至少在表单中按 Tab 键搜索时是这样。


答案 1

使用 SwingUtilities.invokeLater 包装您的调用,以便在处理完所有挂起的 AWT 事件后,它就会发生:

pricePerLiter.addFocusListener(new java.awt.event.FocusAdapter() {
    public void focusGained(java.awt.event.FocusEvent evt) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                pricePerLiter.selectAll();
            }
        });
    }
});

答案 2

除上述内容外,如果您希望对所有文本字段执行此操作,则只需执行以下操作:

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

        }
    }
});

推荐