问题描述
|
JFrame myframe = new JFrame(\"My Sample Frame\");
JButton mybutton = new JButton(\"Okay\");
有人可以向我解释这些部分。
mybutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
//Assuming that the content here will do something.
}
解决方法
您究竟对代码不了解什么?
该代码向按钮添加了一个动作监听器。单击该按钮时,将调用动作侦听器的“ 2”方法。
请注意,这里使用了一个匿名内部类。
, 您应该阅读有关编写事件监听器的教程。
, 这里使用匿名内部类。
您已经在技术上实现了ActionListener。当您调用addActionListener时:
mybutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
//Assuming that the content here will do something.
}
您创建了一个匿名类的实例,或者创建了一个没有名称的ActionListener的类。
同样,请访问此链接。
, 为了使按钮对事件(例如单击)做出反应,它必须具有ActionListener
。
在发布的代码中,您正在创建实现ActionListener
的匿名类
public void mySetupFunction(){
mybutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
//Do something when the button is clicked
});
}
与执行相同:
public void mySetupFunction(){
mybutton.addActionListener(new MyEventHandler());
}
与:
public class MyEventHandler implements ActionListener{
public void actionPerformed(ActionEvent evt){
//Do something when the button is clicked
}
}
, 如果可以安全地假设,那么您要么是事件处理的新手,要么是Java的新手,无论我采用哪种通用方法都可以适应这两种情况:)
专家回答:ActionListener
没有一个,它是真正的自我领导并阅读API
简单答案:对您在代码中提供的内容的糖衣说明。
mybutton
是对实例化对象JButton的引用
xxxxxx.addActionListener()
是对从类javax.swing.AbstractButton继承的Field的函数调用
JButton继承了AbstractButton字段,因此将我们带到下一个说明
new ActionListener(){}
ActionListener是一个接口,我们根本不需要提高。.我们需要知道的是,它侦听来自给定对象的源输入
public void actionPerformed(ActionEvent e)
再次,这是一个函数调用,这是我们的“对象金字塔”的提示
而不是非典型的-将包含对您希望对象基础执行的操作的响应..在这种情况下为mybutton。
您在此处执行的操作取决于您要actionPerformed()执行的操作。
问自己是否属于作业的问题是-这是做什么的?它是如何做到的?