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);     
  }
}
1

1 Answer 1

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.