Swing FocusAdapter類

FocusAdapter類是一個抽象(適配器)類,用於接收鍵盤焦點事件。此類的所有方法都是空的,此類是用於創建偵聽器對象的便捷類。

類聲明

以下是java.awt.event.FocusAdapter類的聲明 -

public abstract class FocusAdapter
   extends Object
      implements FocusListener

類構造函數

編號 構造函數 描述
1 FocusAdapter() 無參數構造函數

類方法

編號 類方法 描述
1 void focusGained(FocusEvent e) 當組件獲得鍵盤焦點時調用。

方法繼承

該類繼承以下類中的方法 -

  • java.lang.Object

FocusAdapter示例

使用編輯器創建以下Java程式:FocusAdapterExample.java

package com.zaixian.swing.listener;

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

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

    public FocusAdapterExample() {
        prepareGUI();
    }

    public static void main(String[] args) {
        FocusAdapterExample swingAdapterDemo = new FocusAdapterExample();
        swingAdapterDemo.showFocusAdapterDemo();
    }

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

        okButton.addFocusListener(new FocusAdapter() {
            public void focusGained(FocusEvent e) {
                statusLabel.setText(
                        statusLabel.getText() + e.getComponent().getClass().getSimpleName() + " gained focus. ");
            }
        });
        cancelButton.addFocusListener(new FocusAdapter() {
            public void focusLost(FocusEvent e) {
                statusLabel
                        .setText(statusLabel.getText() + e.getComponent().getClass().getSimpleName() + " lost focus. ");
            }
        });
        controlPanel.add(okButton);
        controlPanel.add(cancelButton);
        mainFrame.setVisible(true);
    }
}

執行上面示例代碼,得到以下結果:

FocusAdapter示例


上一篇: Swing事件適配器 下一篇: Swing Layout佈局