动作侦听器/动作执行命令

时间:2017-03-14 16:56:21

标签: java swing actionlistener

很抱歉,如果这个问题看起来像是一个愚蠢的问题,或者这个问题已经在这个论坛中完成了,但在阅读了很多帖子和文档之后,我仍然有疑问。

我希望在同一个动作(addActionListener)上订阅两个对象/类。 通知将通过订单完成?也许addActionListener的顺序相同? 或者相关的操作将有一个未预先确定的序列?

例如,我在一个swing表单中为Ok按钮创建了两个addActionListener。按下Ok之后,我想根据需要管理表单内的一些字段,然后通知控制器 有没有更好的方法来做到这一点?

我做了这个简单的测试,我附上了。

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class testbutton {
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ButtonController bController = new ButtonController();
                    Button frame = new Button(bController);
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

}


/**
 * Create the frame.
 */
class Button extends JFrame implements ActionListener { 
    public Button(ButtonController b) {

        // b is the ButtonController object

        JFrame frame = new JFrame();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 376, 201);
        JPanel contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JButton btnButton1 = new JButton("New button");

        // It is important the order of addActionListener?

        // subscibe ButtonController
        btnButton1.addActionListener(b);

        //I am listen (observe) myself (this)
        btnButton1.addActionListener(this); 

        contentPane.add(btnButton1, BorderLayout.CENTER);
    }

    // actionPerformed receive the notification e is the event  
    // related to notify. What's happened to the notifier.
    public void actionPerformed(ActionEvent e) {
        System.out.println("Inside myself");

    }

}

这就是控制器

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ButtonController implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        // Waiting notification.
        // The "Button Controller" need to be instantiated before 
        //the object who do the addActionListener.
        // This instance will be passed to addActionListener
        System.out.println("Inside controller");
    }

}

0 个答案:

没有答案