我是个学生,我们刚开始学习图形。我用actionListener做了两次作业。在这两个任务中,我的构造函数都有以下代码:
JButton.setActionListener(this) ;所以我的问题是,如果我使用不同的类,而不是"this“关键字,会发生什么情况?
例如
JButton.setActionListener(someClass) ;发布于 2017-05-22 20:35:58
您可以添加一个ActionListener实例(甚至允许匿名类)。所以你可以做这样的事情:
new JButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//YOUR CODE
}
});或者您可以实现另一个类(让我们称它为Foo)并将它添加到
new JButton().addActionListener(new Foo());如果您喜欢函数式编程,也可以使用lambda表达式;)
发布于 2017-05-22 20:35:43
这意味着该类someClass必须与implements ActionListener及其实现的方法(如actionperformed()方法)一起使用。
比如:
public class SomeClass implements ActionListener {
public SomeClass() {
//Could do things here
}
public void actionPerformed(ActionEvent e) {
//DDo things when button is clicked.
System.out.println("The button has been clicked");
}
}https://stackoverflow.com/questions/44121663
复制相似问题