【问题标题】:How to empty JTextField if gained focus如果获得焦点,如何清空 JTextField
【发布时间】:2014-12-13 04:55:24
【问题描述】:

我是 Java GUI 的新手,我有 2 个JTextFieldtxtMessage1txtMessage2。我想存档这个:如果一个文本文件有焦点,另一个将被清空,这可能吗?如何存档?

我试过了:

if (txtMessage1.isFocusOwner())
    txtMessage2.setText("");
if (txtMessage2.isFocusOwner())
    txtMessage1.setText("");

但它不起作用,不扔任何东西......

【问题讨论】:

标签: java swing focus jtextfield


【解决方案1】:

您必须为每个JTextField 定义一个FocusListener,或者为两者定义一个。

参见本页底部的示例:

【讨论】:

    【解决方案2】:

    你需要一个FocusListener,就像这样:

    FocusAdapter fl = new FocusAdapter()
    {
        public void focusGained (FocusEvent evt)
        {
            if (evt.getSource() == txtField1)
                txtField2.setText("");
            else if (evt.getSource() == txtField2)
                txtField1.setText("");
        }
    }
    txtField1.addFocusListener(fl);
    txtField2.addFocusListener(fl);
    

    【讨论】:

    • 如何在我当前类的方法中创建代码,而不是在这样的单独类中?
    • @RonaldinhoState 我编辑了这个问题,你现在有一个匿名内部类型。您可以在方法/构造函数中使用此代码
    • 你的意思是 addFocusListener 不是 setFocusListener 对吗?
    • @RonaldinhoState 是的,我的意思是,对不起
    猜你喜欢
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 2017-03-12
    • 2013-06-13
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多