组件本身可以用作监听器吗?

Jav*_*107 2 java user-interface swing jframe actionlistener

我尝试在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);
    }

}
Run Code Online (Sandbox Code Playgroud)

我的问题是:使用组件作为自己的监听器有什么问题吗?

Rob*_*bin 5

它有效......是的

话虽如此.我可以举几百个不良编码实践的例子,这就是其中之一.

  • 几乎从不需要Jxxx在Swing中扩展类(除了自定义绘制之外).在您的示例中,您可以使用a JFrame而不是扩展它
  • 有一个实现ActionListener接口的类建议您的API /代码的用户可以将其用作ActionListener.但是,您的课程并非设计为ActionListener.它是一个的事实是一个可以更好地隐藏的实现细节.所以使用ActionListener(匿名类,内部类,......)而不是直接实现它(甚至更好,使用Action)

不,ActionListener直接实现接口与没有任何关系,我看到GUI需要很长时间才能加载

并作为旁注.最好使用JFrame#pack()然后调用setBounds.