0

What can I do in order to recognize button 2 by do_something function? I want to changing button2 text after clicking on it, but I received an error: button2 cannot be resolved.

class myClass {
    public static int counter = 0;
    public static void do_something() {
    button2.setText(Integer.toString(counter));
  }

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setLayout(new GridLayout(3, 2));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JButton button = new JButton("button 1");
    frame.add(button);
    JButton button2 = new JButton("button 2");
    button2.addActionListener(e -> do_something());
    frame.add(button2);
    frame.pack();
    frame.setVisible(true);     
  }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    This is a scope issue. Please see this question and let us know if it resolves your problem: http://stackoverflow.com/questions/4560850/java-variable-scope – ControlAltDel Oct 13 '16 at 14:12

1 Answers1

0

You need to declare button and button2 outside the class (some how globally and increment the counter varaiable whenever you press the button2):

package javaapplication1;

import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;

class myClass extends JFrame{

    static JButton button = new JButton("button 1");
    static JButton button2 = new JButton("button 2");
    public static int counter = 0;

    public static void do_something() {
        counter++;
        button2.setText(Integer.toString(counter));
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setLayout(new GridLayout(3, 2));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(button);

        button2.addActionListener(e -> do_something());
        frame.add(button2);
        frame.pack();
        frame.setVisible(true);
    }
}
Young Emil
  • 2,220
  • 2
  • 26
  • 37