# 在我发布的问题中,我无法理解第 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();
}
});
}
}