我曾尝试在 Java 中使用此代码,其中我使用了 JFrame 作为它自己的 ActionListener。现在,这在理论上是可行的,因为在 Java 中,一个类既可以实现多个接口(interface),也可以扩展另一个类。
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);
}
}
我的问题是:使用组件作为它自己的监听器有什么问题吗?
最佳答案
它是否有效……是的。
话虽这么说。我可以举出数百个不良编码实践的例子,这就是其中之一。
- 几乎从不需要扩展 Swing 中的
Jxxx
类(自定义绘画除外)。在您的示例中,您可以使用JFrame
而不是扩展它 - 拥有一个实现
ActionListener
接口(interface)的类向您的API/代码的用户建议它可以用作ActionListener
。但是,您的类未设计为ActionListener
。它是一个的事实是一个可以更好地隐藏的实现细节。所以使用ActionListener
(匿名类,内部类,...)而不是直接实现它(或者更好的是,使用Action
)
而且不是,直接实现ActionListener
接口(interface)与我看到GUI加载时间很长
作为旁注。最好使用 JFrame#pack()
然后调用 setBounds
。
关于java - 一个组件本身可以用作监听器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13543159/