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.yiibai.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示例(yiibai.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);
}
}
执行上面示例代码,得到以下结果: