Swing FocusListener介面

2019-10-16 22:11:26

FocusListener介面用於接收鍵盤焦點事件,處理焦點事件的類需要實現此介面。

類宣告

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

public interface FocusListener
extends EventListener

介面方法

編號 方法 描述說明
1 void focusGained(FocusEvent e) 當元件獲得鍵盤焦點時呼叫。
2 void focusLost(FocusEvent e) 當元件失去鍵盤焦點時呼叫。

方法繼承

該類從以下介面繼承方法 -

  • java.awt.event.EventListener

FocusListener範例

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

package com.yiibai.swing.listener;

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

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

    public FocusListenerDemo() {
        prepareGUI();
    }

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

    private void prepareGUI() {
        mainFrame = new JFrame("Java SWING FocusListener範例(yiiai.com)");
        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 showFocusListenerDemo() {
        headerLabel.setText("Listener in action: FocusListener");
        JButton okButton = new JButton("確定");
        JButton cancelButton = new JButton("取消");

        okButton.addFocusListener(new CustomFocusListener());
        cancelButton.addFocusListener(new CustomFocusListener());

        controlPanel.add(okButton);
        controlPanel.add(cancelButton);
        mainFrame.setVisible(true);
    }

    class CustomFocusListener implements FocusListener {
        public void focusGained(FocusEvent e) {
            statusLabel
                    .setText(statusLabel.getText() + e.getComponent().getClass().getSimpleName() + " gained focus. ");
        }

        public void focusLost(FocusEvent e) {
            statusLabel.setText(statusLabel.getText() + e.getComponent().getClass().getSimpleName() + " lost focus. ");
        }
    }
}

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

FocusListener