Swing - FocusAdapter 类
简介
FocusAdapter 类是一个抽象(适配器)类,用于接收键盘焦点事件。 这个类的所有方法都是空的。 此类是用于创建侦听器对象的便利类。
类声明
以下是 java.awt.event.FocusAdapter 类的声明 −
public abstract class FocusAdapter
extends Object
implements FocusListener
类构造函数
| 序号 | 构造函数 & 描述 |
|---|---|
| 1 |
FocusAdapter() |
类方法
| 序号 | 方法 & 描述 |
|---|---|
| 1 |
void focusGained(FocusEvent e) Invoked when a component gains the keyboard focus. |
继承的方法
这个类继承了以下类的方法 −
- java.lang.Object
FocusAdapter Example
在 D:/ > SWING > com > tutorialspoint > gui > 中使用您选择的任何编辑器创建以下 Java 程序
SwingAdapterDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingAdapterDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public SwingAdapterDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingAdapterDemo swingAdapterDemo = new SwingAdapterDemo();
swingAdapterDemo.showFocusAdapterDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java SWING Examples");
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("OK");
JButton cancelButton = new JButton("Cancel");
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);
}
}
使用命令提示符编译程序。 转到 D:/ > SWING 并键入以下命令。
D:\SWING>javac com\tutorialspoint\gui\SwingAdapterDemo.java
如果没有报错,说明编译成功。 使用以下命令运行程序。
D:\SWING>java com.tutorialspoint.gui.SwingAdapterDemo
验证以下输出。

