【问题标题】:getting refrence for JTextFeild in actionListener在 actionListener 中获取 JTextField 的参考
【发布时间】:2019-12-10 20:05:03
【问题描述】:

我正在尝试在附加的 ActionListener 中使用 JTextFeild 中的 getText() 方法...问题是我没有指向它的引用...也就是说我正在添加那些 textFeilds在从 arraylist 获取字符串并显示新 textFeild 的循环中,我搜索了 Internet 试图找到一种使用 getText() 的方法,但它没有意义,因为我没有参考。关于它,我的问题是如何在此操作侦听器中获取 JTextFeild 中的文本,并且有什么方法可以获取对该操作执行的此 JTextFeild 的引用????

 JTextField t;
 for(MyClass m: MyArraylist) {
     t=new JTextField(m.toString());
     t.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                    System.out.println(getText());
                    }
                    });
      }

我试过 getText(); super.getText(); t.getTaxt();并且肯定它不会起作用,因为 t 总是在变化,我也试过 system.out.println(m.toString());并且不工作

【问题讨论】:

标签: java swing reference jtextfield gettext


【解决方案1】:

您应该获取事件的源并将其转换为TextField

t.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        TextField tf = (TextField) e.getSource();
        System.out.println(tf.getText());
    }
});

【讨论】:

  • 我测试过了。你是怎么测试的?动作监听器只会在您按下Enter 时运行。如果您希望监听器在每次按键时运行,您应该使用KeyEventListener
【解决方案2】:

你必须使用对象中的函数

t.getText()

here

【讨论】:

  • 它不会起作用,因为它总是在变化,而且我已经尝试了百万次才意识到这一点
猜你喜欢
  • 2012-06-06
  • 1970-01-01
  • 2016-10-29
  • 2013-02-16
  • 2016-08-23
  • 2013-12-28
  • 2017-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多