首页 > 解决方案 > 匿名类,还是观察者模型中的一个 ActionEvent?

问题描述

考虑一个带有两个按钮的 JFrame:

设置1:

一个 actionPerformed 方法被传递给孩子,它的处理方式是基于传递事件的对象的 ID。

import javx.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;

public class View extends JFrame implements ActionListener{
    private JButton btn1;
    private JButton btn2;
    private JLabel lbl;

    public View(){
        btn1 = new JButton("hi");
        btn2 = new JButton("bye");
        setLayout(new GridBagLayout());
        GridBagConstraings gc = new GridBagConstraints();

        gc.gridx = 0;
        gc.gridy = 0;
        gc.weightx = 1;
        gc.weighty = 1;
        add(btn1,gc);

        gc.gridx = 1;
        gc.gridy = 0;
        gc.weightx = 1;
        gc.weighty = 1;
        add(btn2,gc);

        btn1.addActionListener(this);
        btn2.addActionListener(this);
    }
    @Override
    public void actionPerformed(ActionEvent e){
        JButton src = (JButton)e.getSource();
        if(src == btn1){
            //do this
        }else{
            //do that
        }
    }
}

设置 2:

每个单独的模块都被传递一个匿名类的实例,该类包含它自己独特的实现actionPerformed()

import javx.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;

public class View extends JFrame{
    private JButton btn1;
    private JButton btn2;
    private JLabel lbl;

    public View(){
        btn1 = new JButton("hi");
        btn2 = new JButton("bye");
        setLayout(new GridBagLayout());
        GridBagConstraings gc = new GridBagConstraints();

        gc.gridx = 0;
        gc.gridy = 0;
        gc.weightx = 1;
        gc.weighty = 1;
        add(btn1,gc);

        gc.gridx = 1;
        gc.gridy = 0;
        gc.weightx = 1;
        gc.weighty = 1;
        add(btn2,gc);

        btn1.addActionListener(new ActionListener(){
            //do this
        });
        btn2.addActionListener(new ActionListener(){
            //do that
        });
    }
}

我应该选择一种方法而不是另一种方法的原因是什么?

标签: javaswingevent-handlingobserver-patternanonymous-class

解决方案


推荐阅读