我刚刚用 Java 制作了我的第一个基于事件的 GUI, 但我不明白我哪里错了。 当没有应用事件处理时,代码工作正常..
这是代码。
package javaapplication1;
import javax.swing.*;
import java.awt.event.*;
class Elem implements ActionListener{
void perform(){
JFrame frame = new JFrame();
JButton button;
button = new JButton("Button");
frame.getContentPane().add(button) ;
frame.setSize(300,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent ev){
button.setText("Clicked");
}
}
public class JavaApplication1 {
public static void main(String[] args) {
Elem obj = new Elem();
obj.perform();
}
}
最佳答案
变量作用域有问题。将 JButton button;
定义移到 perform()
方法之外,以便 actionPerformed()
可以访问它。
JButton button;
void perform(){
JFrame frame = new JFrame();
button = new JButton("Button");
frame.getContentPane().add(button) ;
frame.setSize(300,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(this);
}
当您在方法内部定义对象时(例如 perform()
),它的范围仅限于该方法(在大括号内)。这意味着您的类中的其他方法无法访问该变量。
通过将对象定义移到方法之外,它现在具有类级别范围。这意味着该类中的任何方法都可以访问该变量。您仍在 perform()
中定义它的值,但现在可以通过其他方法访问它,包括 actionPerformed()
。
参见 here以获得更多解释。
关于java - 如何在 Java 中处理事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19927046/