Swing ActionListener介面

2019-10-16 22:11:12

處理ActionEvent的類應該實現此介面。該類的物件必須在元件中註冊。可以使用addActionListener()方法註冊該物件。當動作事件發生時,將呼叫該物件的actionPerformed方法。

介面宣告

以下是java.awt.event.ActionListener介面的宣告 -

public interface ActionListener
   extends EventListener

介面方法

編號 方法 描述
1 void actionPerformed(ActionEvent e) 發生操作時呼叫。

方法繼承

此介面從以下介面繼承方法 -

  • java.awt.EventListener

ActionListener範例

使用編輯器建立以下Java程式:ActionListenerExample.java

package com.yiibai.swing.listener;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ActionListenerExample {
    private JFrame mainFrame;
    private JLabel headerLabel;
    private JLabel statusLabel;
    private JPanel controlPanel;

    public ActionListenerExample() {
        prepareGUI();
    }

    public static void main(String[] args) {
        ActionListenerExample swingListenerDemo = new ActionListenerExample();
        swingListenerDemo.showActionListenerDemo();
    }

    private void prepareGUI() {
        // from https://www.tw511.com/swing/
        mainFrame = new JFrame("Java SWING ActionListener範例");
        mainFrame.setSize(400, 400);
        mainFrame.setLayout(new GridLayout(3, 1));

        headerLabel = new JLabel("", JLabel.CENTER);
        statusLabel = new JLabel("", JLabel.CENTER);
        statusLabel.setSize(350, 100);

        mainFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent) {
                System.exit(0);
            }
        });
        controlPanel = new JPanel();
        controlPanel.setLayout(new FlowLayout());

        mainFrame.add(headerLabel);
        mainFrame.add(controlPanel);
        mainFrame.add(statusLabel);
        mainFrame.setVisible(true);
    }

    private void showActionListenerDemo() {
        headerLabel.setText("Listener in action: ActionListener");

        JPanel panel = new JPanel();
        panel.setBackground(Color.ORANGE);
        JButton okButton = new JButton("確定");

        okButton.addActionListener(new CustomActionListener());
        panel.add(okButton);
        controlPanel.add(panel);
        mainFrame.setVisible(true);
    }

    class CustomActionListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            statusLabel.setText("點選了'確定'按鈕");
        }
    }
}

執行上面範例程式碼,得到以下結果:

ActionListener示例