我曾尝试在 Java 中使用此代码,其中我使用 JFrame 作为它自己的 ActionListener。现在,理论上是可能的,因为在 Java 中,一个类既可以实现多个接口,又可以扩展另一个类。
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
/*
* This is an example of the strangeness of the syntax of Java. In this example, I am using the JFrame itself as the listener for its component, namely a JButton which, on clicking, ends the program.
* Warning : This is just an example, and I would never recommend this syntax, for I do not know the full consequences yet.
*/
@SuppressWarnings("serial") public class ListenerTest extends JFrame implements ActionListener{
private final JPanel contentPane;
private final JLabel message;
private final JButton button;
/**
* Launch the application.
*/
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
@Override public void run(){
try{
ListenerTest frame = new ListenerTest();
frame.setVisible(true);
} catch(Exception e){
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ListenerTest(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 200, 150);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
message = new JLabel("Hello World");
message.setFont(new Font("Times New Roman", Font.PLAIN, 16));
message.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(message, BorderLayout.CENTER);
button = new JButton("Click Me!");
button.addActionListener(this);
contentPane.add(button, BorderLayout.SOUTH);
}
@Override public void actionPerformed(ActionEvent arg0){
JOptionPane.showMessageDialog(null, "Well, I listened for myself!");
System.exit(0);
}
}
我的问题是:使用组件作为自己的监听器有什么问题吗?