简体   繁体   中英

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. 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. How can I do this? Thanks.

From your question:

pass to the class Orders the number of the button which fires the event

You could just capture the loop iteration variable i so it can be used inside your anonymous event handler. 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". 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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