FocusAdapter
類是一個抽象(介面卡)類,用於接收鍵盤焦點事件。此類的所有方法都是空的,此類是用於建立偵聽器物件的便捷類。
以下是java.awt.event.FocusAdapter
類的宣告 -
public abstract class FocusAdapter
extends Object
implements FocusListener
編號 | 建構函式 | 描述 |
---|---|---|
1 | FocusAdapter() |
無引數建構函式 |
編號 | 類方法 | 描述 |
---|---|---|
1 | void focusGained(FocusEvent e) |
當元件獲得鍵盤焦點時呼叫。 |
該類繼承以下類中的方法 -
java.lang.Object
使用編輯器建立以下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範例(tw511.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);
}
}
執行上面範例程式碼,得到以下結果: