Swing FocusListener接口

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.zaixian.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


上一篇: Swing事件监听器 下一篇: Swing事件适配器