大家节日快乐,
这是我要了解的情况的用例。
public abstract class Animal extends JButton implements ActionListener {
private boolean actionFlag = false;
//some constructor
//some functions
@Override
public void actionPerformed(ActionEvent actionEvent) {
this.actionFlag = true;
System.out.println(this.actionFlag);
}
}
public class Tiger extends Animal {}
public class Bear extends Animal {}
例如,当创建Tiger
和Bear
对象并且它们是BTN的原因时,抽象方法扩展了JButton
类,按下这些按钮时将调用它们各自的ActionPerformed()
函数,因为我没有分别将actionPerformed
函数覆盖到这些类中的每一个中,它们将从其父类actionPerformed()
继承Animal
,我相信到目前为止,如果不能随意纠正我,我是正确的。
现在,由于所有这些观察结果都是正确的,例如,当我单击熊按钮时,我应该看到输出中的消息等于“ true”。
这就是问题,我的控制台上什么也没有出现,并且看来根本没有触发基类的actionListener
。(GUI上的按钮是setEnabled(true)
,因此交互不是问题)
可能的原因是什么?我在这里想念什么?
paintComponent()
函数也发生了同样的事情,但是我相信,如果我理解了actionListener
上的错误,那就很简单了]
仅给JButton扩展类提供一个ActionListener 不会将该侦听器添加到创建的按钮中。为此,必须在类的构造函数中使用addActionListener(this);
实际上添加侦听器。
public abstract class Animal extends JButton implements ActionListener {
private boolean actionFlag = false;
public Animal() {
addActionListener(this);
}
//some constructor
//some functions
@Override
public void actionPerformed(ActionEvent actionEvent) {
this.actionFlag = true;
System.out.println(this.actionFlag);
}
}
话虽如此,我永远不会有这样的Swing代码。相反,我会
关于:
,它会由Swing图形系统自动调用。
paintComponent()
发生相同的事情>>这里可能会发生一些变化,因为您不需要向组件中“添加” paintComponent,而是如果它是适当的方法替代
看起来您只想演示实现ActionListener
的类的多态行为。为此,您不需要扩展JButton
。您只需要实现ActionListener
。以下示例代码将演示您想要做什么: