简体   繁体   English

一旦失去焦点,我想从文本字段中获取文本。 为此,我尝试使用“ this”运算符,但它不起作用

[英]I want to get the text from the textfields as soon as their focus is lost. for this i tried using the “this” operator but it doesn't work

i have a lot of textfields in my frame so it would be impossible to have a focus listener for each 1 of them. 我的框架中有很多文本字段,因此不可能为每个文本字段都拥有一个焦点侦听器。 so i want to use a single focus listener function and get the text whenever the focus is lost. 所以我想使用单个焦点侦听器功能,并在焦点丢失时获取文本。

        tf1=new JTextField();
        tf1.setBounds(200,300,150,50);
        tf1.setText("");
        tf1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                tfFocusLost(evt);
            }
        });
        add(tf1);

        tf2=new JTextField();
        tf2.setBounds(200,500,150,50);
        tf2.setText("");
        tf2.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                tfFocusLost(evt);
            }
        });
        add(tf2);

    private void tfFocusLost(java.awt.event.FocusEvent evt) {
        s=this.getText();   
        System.out.println(s);
    }

Why not just creating your own class which extends FocusAdapter instead of creating an anonymous class for each of your JTextField : 为什么不创建自己的类来扩展FocusAdapter而不是为每个JTextField创建一个匿名类呢?

public class MyFocusAdapter extends FocusAdapter {

    private final JTextField text;

    public MyFocusAdapter(JTextField text) {
        this.text = text;
    }

    public void focusLost(java.awt.event.FocusEvent evt) {
        System.out.println(text);
    }
}

Then you can use this class : 然后,您可以使用此类:

tf1.addFocusListener(new MyFocusAdapter(tf1));
tf2.addFocusListener(new MyFocusAdapter(tf2));

You will need to change the implementation for your tfFocusLost. 您将需要更改tfFocusLost的实现。

   private void tfFocusLost(java.awt.event.FocusEvent evt) {
        s=this.getText();   
        System.out.println(s);
    }

instead of above you can use something like this. 而不是上面,您可以使用类似这样的东西。

 private void tfFocusLost(java.awt.event.FocusEvent evt, JTextField textField ) {
        s=textField.getText();   
        System.out.println(s);
    }

And call it like tfFocusLost(evt,tf1); 并像tfFocusLost(evt,tf1);这样称呼它tfFocusLost(evt,tf1);

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

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