如何在焦点上选择JFormattedTextField中的所有文本? [英] How to select all text in a JFormattedTextField when it gets focus?

查看:122
本文介绍了如何在焦点上选择JFormattedTextField中的所有文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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). When I activate the JFormattedTextFields either by tabbing through the form or by clicking it with the mouse, I would like it to select all the text that it currently contains. That way, users could just start typing and overwrite the default values.

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

How can I do that? I did use a FocusListener/FocusAdapter that calls selectAll() on the JFormattedTextField, but it doesn't select anything, although the FocusAdapter's focusGained() method is called (see code sample below).

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的默认行为,至少在表格中进行选项时。

Any ideas? The funny thing is that selecting all of its text apparently is the default behavior for both JTextField and JSpinner, at least when tabbing through the form.

推荐答案

使用SwingUtilities.invokeLater保存您的通话,以便在处理完所有挂起的AWT事件后发生:

Wrap your call with SwingUtilities.invokeLater so it will happen after all pending AWT events have been processed :

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();
            }
        });
    }
});

这篇关于如何在焦点上选择JFormattedTextField中的所有文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆