# 在我发布的问题中,我无法理解第 1 行和第 2 行提到的代码,因为我对它们的了解是它们用于设置按钮的操作监听器,但让我最困惑的是,在第 1 行和第 2 行的语法中,{JB1.addActionListener(this)} 在这中“this”的作用是什么......所以请告诉基本的这背后。以及整个语法如何工作......详细。 #
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class frametest1_1 implements ActionListener
{
JLabel JL;
public frametest1_1()
{
//create a JFrame container
JFrame JF=new JFrame("A BUTTON");
//Frame Layout This is contained in Java .awt.*; "ON USING THIS OPTION OUR BUTTON AND OTHER COMPONENT ARE ADJUSTED IN THE FRAME AUTOMATICALLY"
JF.setLayout(new FlowLayout());
//set the size of the container
JF.setSize(200, 200);
//set visible
JF.setVisible(true);
//make button
JButton JB1=new JButton("FIRST");
JButton JB2=new JButton("SECOND");
//add button to the JFrame container
JF.add(JB1);
JF.add(JB2);
//Create and add Label to the JFrame container
JL=new JLabel("PRESS A BUTTON");
JF.add(JL);
//set action command :now this will help in determining that which button is presses, is it FIRST or SECOND
JB1.setActionCommand("one");
JB2.setActionCommand("two");
//The action responded is added to the actionlistener
JB1.addActionListener((ActionListener) this); // line 1
JB2.addActionListener((ActionListener) this); // line 2
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand().equals("one"))
JL.setText("First Button Pressed"); // to set text on the label
else
JL.setText("Second button Pressed"); // to set the text on the label
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new frametest1_1();
}
});
}
}
最佳答案
1.考虑监听者是对某些操作使用react的人
。
2.ActionListener
是一个接口(interface),它有一个回调方法,名为actionPerformed
,其中的代码将在 Controller 上执行特定操作时运行。
3.这一行JB1.addActionListener((ActionListener) this);
含义如下
JB1 - Button
ActionListener - Interface
addActionListener - Registering the Button with the Listener.
4. addActionListener
将绑定(bind)/注册 Button
与 Listener
(这里是 ActionListener)。
5.在MVC
架构中,Button是 Controller
,当对其执行特定操作时,将通知谁做某些事情是通过将其注册到监听器来完成的。
6. 此监听器将具有callback
方法,该方法将被实现监听器的类覆盖。
7.此外,在您的示例中,您也可以这样做......
JB1.addActionListener(this);
关于java - Swing: Action 监听器的作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11629499/