简体   繁体   English

在大量的jTextField中选择所有焦点

[英]select all on focus in lots of jTextField

I have lots of jTextFields in my application (About 34 jTextFields) and I want all of them select all of their text when get focus and select none of text on focus lost. 我的应用程序中有很多jTextFields(大约34个jTextFields),我希望所有这些文本在获得焦点时选择所有文本,并且在焦点丢失时不选择任何文本。
Is there any way to do this with one listener or should I write a "FocusGained" and a "FocusLost" for each of these 34 jTextFields? 有没有办法用一个监听器做这个或者我应该为这34个jTextField中的每一个写一个“FocusGained”和一个“FocusLost”?

Thanks 谢谢

Create a class for this task: 为此任务创建一个类:

static class FocusTextField extends JTextField {
    {
        addFocusListener(new FocusListener() {

            @Override
            public void focusGained(FocusEvent e) {
                FocusTextField.this.select(0, getText().length());
            }

            @Override
            public void focusLost(FocusEvent e) {
                FocusTextField.this.select(0, 0);
            }
        });
    }
}

Example usage (code below): 用法示例(下面的代码):

截图

public static void main(String[] args) throws Exception {

    JFrame frame = new JFrame("Test");
    frame.setLayout(new GridLayout(5, 1));

    frame.add(new FocusTextField());
    frame.add(new FocusTextField());
    frame.add(new FocusTextField());
    frame.add(new FocusTextField());
    frame.add(new FocusTextField());

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

Create on class and extend the JTextField now implement whatever you want in this class. 在类上创建并扩展JTextField现在可以在此类中实现您想要的任何内容。 And where you can create object of JTextField like this 在这里你可以像这样创建JTextField的对象

JTextField txt1 = new JTextField();
frm.add(txt1);

instead of do this way 而不是这样做

JTextField txt1 = new CustomText();
frm.add(txt1);

so you have to set the common class for the Text field 所以你必须为Text字段设置公共类

Is there any way to do this with one listener 有没有办法用一个监听器做到这一点

You can use the KeyboardFocusManager. 您可以使用KeyboardFocusManager。 See the example from Global Event Listeners . 请参阅全局事件监听器中的示例。

I would say the easy way to do it is add an action on click that simply selects all 我想说这样做的简单方法是在点击上添加一个只选择全部的操作

private void jTextField1MouseClicked(java.awt.event.MouseEvent evt) {                                         
    jTextField1.selectAll();
}                      

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

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