【发布时间】:2017-02-22 17:10:57
【问题描述】:
我该怎么做才能通过do_something 函数识别button 2?我想在点击后更改button2 文本,但收到错误消息: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);
}
}
【问题讨论】:
-
这是一个范围问题。请查看此问题,如果它解决了您的问题,请告诉我们:stackoverflow.com/questions/4560850/java-variable-scope