简体   繁体   English

如何将值从按钮传递到另一个类

[英]How to pass a value from a button to another class

Scenario: I have a series of jbuttons (created at runtime) and each of them has a number in his label. 场景:我有一系列的jbutton(在运行时创建),每个jbutton的标签中都有一个数字。 Buttons are created with this code: 使用以下代码创建按钮:

    for (int i = 1; i <= tablesNumber; i++) {
        JButton button = new JButton(Integer.toString(i));
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new Orders().setVisible(true);
            }
        });
        jPanel1.add(button);
    }

I need to pass to the class Orders the number of the button which fires the event, eg if the user clicks on button number 5 I need to pass the value 5 to Orders. 我需要将触发事件的按钮的编号传递给Orders类,例如,如果用户单击5号按钮,则需要将5值传递给Orders。 How can I do this? 我怎样才能做到这一点? Thanks. 谢谢。

From your question: 根据您的问题:

pass to the class Orders the number of the button which fires the event 传递给类Orders触发事件的按钮的编号

You could just capture the loop iteration variable i so it can be used inside your anonymous event handler. 您可以捕获循环迭代变量i以便可以在匿名事件处理程序中使用它。 For the sake of argument I have assumed you want to pass the number into the constructor, but you can use it however you like: 为了论证,我假设您想将数字传递给构造函数,但是您可以随意使用它:

for (int i = 1; i <= tablesNumber; i++) {
    final int t = i; // <-- NEW LINE HERE
    JButton button = new JButton(Integer.toString(i));
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            new Orders(t).setVisible(true); // <-- USE t here however you need to
        }
    });
    jPanel1.add(button);
}

Without final int t = i you may get the compiler error "Cannot refer to a non-final variable i inside an inner class defined in a different method". 没有final int t = i您可能会收到编译器错误“无法在用不同方法定义的内部类中引用非最终变量i”。 This is because a capture variable (ie a variable from an outer scope used inside an anonymous class' method must be final (or effectively final - this behaviour has changed slightly as of SE 8). 这是因为捕获变量(即,在匿名类的方法内部使用的来自外部作用域的变量必须是final变量(或有效地是final变量-从SE 8开始,此行为已稍有更改))。

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

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