简体   繁体   English

Java-如何对多个JTextField使用单个FocusListener?

[英]Java - How do I use a single FocusListener for multiple JTextFields?

Some background: I'm a fairly experienced C++ programmer, but I'm currently teaching myself Java. 背景知识:我是一位相当有经验的C ++程序员,但是我目前正在自学Java。

I have an application with several JTextFields, and I want the content of a field to be highlighted when I click on it. 我有一个带有多个JTextField的应用程序,并且我希望在单击该字段时突出显示该字段的内容。 I know I can write a simple inline FocusAdapter for each one, but I'd like to write a single nested class that is used for each JTestField's addFocusListener. 我知道我可以为每个脚本编写一个简单的内联FocusAdapter,但是我想编写一个用于每个JTestField的addFocusListener的嵌套类。 I figured out the following code works: 我发现以下代码有效:

    private class textFieldFocusListener extends FocusAdapter {
    @Override
    public void focusGained(FocusEvent arg0) {
        ((JTextComponent) arg0.getComponent()).selectAll();
        }   
    }

...but that JTextComponent cast troubles me a little bit. ...但是JTextComponent演员让我有些麻烦。 In C++ casts are frowned upon, and I'm not familiar with the Best Practices of Java. 在C ++中,强制转换不受欢迎,并且我对Java的最佳实践不熟悉。

So, is this solution with the cast to JTextComponent "good" Java coding, or is there a better/cleaner solution? 那么,这种将JTextComponent强制转换为“好的” Java编码的解决方案,还是有一个更好/更干净的解决方案?

JTextComponent cast troubles me a little bit JTextComponent演员让我有些麻烦

This is fine to do, as long as you take care to only add the FocusListener to JTextComponents such as JTextFields. 只要您注意仅将FocusListener添加到JTextComponents(例如JTextFields),就可以做到这一点。 If you want to be extra careful, you could always do an instanceof check, 如果您要格外小心,可以随时执行checkof实例,

Component comp = e.getComponent();
if (!(e instanceof JTextComponent)) {
   return;
}

but likely it's not necessary. 但可能没有必要。

Perhaps better: create a method that adds the FocusListener and that only accepts JTextComponent as its parameter. 也许更好:创建一个添加FocusListener且仅接受JTextComponent作为其参数的方法。

test if arg0 is a JTextComponent 测试arg0是否为JTextComponent

private class textFieldFocusListener extends FocusAdapter {
    @Override
    public void focusGained(FocusEvent arg0) {
        if (arg0 instanceOf JTextComponent) {
           ((JTextComponent) arg0.getComponent()).selectAll();
          }
        }   
    }

只需创建一个所有听众都调用它的函数即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM