【问题标题】:How can I access a variable from an actionListener insider another actionListener?如何从另一个 actionListener 内部的 actionListener 访问变量?
【发布时间】:2015-03-29 04:50:37
【问题描述】:
private int var = 0;

test(){
    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String selection = (String) items.getSelectedItem();

            for (int i = 0; i < itms.length; i++) {
                if (selection == itms[i]) {
                    var = 10 + i;

                    System.out.println(var); // prints the desired value
                }
            }
        }
    };

    System.out.println(var); // prints 0 but why not desired value???
}

此 actionListener 用于组合框。我想在组合框中获取所选项目的值并将其提供给另一个 actionListener,该 actionListener 将根据选择的 JButton 将新值附加到原始 actionListener 的 var 中。如何从这个 actionListener 中获取 var 的值,并在另一个同样在同一个构造函数中的 actionListener 中使用它?这甚至可能吗?有更好的方法吗?

【问题讨论】:

  • 据我所见,第二个打印语句在创建侦听器后立即被调用。至于侦听器中的代码,直到事件实际发生时才会执行。 0 会先打印吗?
  • 当您的 var 是 int 时,将另一个值附加到 var 是什么意思? int 只包含一个值。您不能向其附加其他值。
  • @VinceEmigh yes 0 首先打印,直到我在组合框中进行选择。
  • @ajb 我会将它们转换为字符串,然后附加它们以生成更长的“整数”值。

标签: java scope jbutton actionlistener jcombobox


【解决方案1】:

您的actionPerformed() 方法将在其事件发生时执行,但actionPerformed() 之外的打印语句并非如此。

所以这个说法

System.out.println(var); // prints 0 but why not desired value???

在您创建test 类的对象时执行(根据Java 命名约定,最好将其命名为Test 类),因为打印语句是在构造函数中编写的。相反,只要事件发生,actionPerformed 方法中的 print 语句就会被执行并打印出正确的值,即您的“期望值”。

【讨论】:

    猜你喜欢
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    相关资源
    最近更新 更多