我正在自学 Java 的 swing 组件,但遇到了一些概念上的障碍。我确信我的一些具体术语是错误的,但希望我能够很好地传达我的困难,以获得一两个答案。
我有以下代码,为简洁起见,进行了精简:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//
public class CreateButtonSel {
public static void main(String[] args) {
ButtonSel thisButtonSel = new ButtonSel();
final int WIDTH = 250;
final int HEIGHT = 250;
thisButtonSel.setSize(WIDTH,HEIGHT);
thisButtonSel.setVisible(true);
}
}
当我添加 implements ActionListener
(在下面注释掉)时,我收到一个错误,指出 ButtonSel 不是抽象的,并且不会覆盖抽象方法 actionPerformed(ActionEvent)
。根据我在 javadoc 和各个站点上阅读的内容,我发现该错误是由于尚未在方法中定义操作而导致的。类似的东西
public void actionPerformed(ActionEvent clickButton) {
do stuff;
{
但是,我不清楚该方法需要存放在哪里。我猜测它位于带有构造函数的 ButtonSel
类中 - 因为那是我定义按钮对象的地方。不过,我也可以将其视为 CreateButtonSel 类中的一个方法,并作为参数传递给 ButtonSel。然后,存在的问题是如何或是否将这些按钮操作特征传递给构造函数?或者,如果它们位于 CreateButtonSel
类中,它们是否会自动附加到构造函数创建的按钮对象?
有人可以解释一下程序流程应该如何工作以及什么时候调用哪个方法吗?
// public class ButtonSel extends JFrame implements ActionListener {
public class ButtonSel extends JFrame {
JButton approveButton = new JButton("Go");
JPanel buttonPanel = new JPanel();
//
public ButtonSel() {
super("ButtonTest");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
add(approveButton);
}
}
最佳答案
参见How to Write an ActionListener举个例子。您还可以在论坛中搜索其他工作示例。
关于java - 我需要一些指导来了解 ActionListener 和 actionPerformed(ActionEvent) 的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16111113/