KeyAdapter
類是一個用於接收鍵盤事件的抽象(介面卡)類。此類的所有方法都是空的。此類是用於建立偵聽器物件的便捷類。
以下是java.awt.event.KeyAdapter
類的宣告 -
public abstract class KeyAdapter
extends Object
implements KeyListener
編號 | 建構函式 | 描述說明 |
---|---|---|
1 | KeyAdapter() |
無引數建構函式 |
編號 | 類方法 | 描述說明 |
---|---|---|
1 | void keyPressed(KeyEvent e) |
按下某個鍵時呼叫。 |
2 | void keyReleased(KeyEvent e) |
當一個鍵被釋放時呼叫。 |
3 | void keyTyped(KeyEvent e) |
鍵入鍵時呼叫。 |
該類繼承以下類中的方法 -
java.lang.Object
使用編輯器建立以下Java程式:KeyAdapterDemo.java
package com.yiibai.swing.listener;
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.*;
public class KeyAdapterDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public KeyAdapterDemo() {
prepareGUI();
}
public static void main(String[] args) {
KeyAdapterDemo swingAdapterDemo = new KeyAdapterDemo();
swingAdapterDemo.showKeyAdapterDemo();
}
private void prepareGUI() {
mainFrame = new JFrame("Java SWING KeyAdapter範例(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 showKeyAdapterDemo() {
headerLabel.setText("Listener in action: KeyAdapter");
final JTextField textField = new JTextField(10);
textField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
statusLabel.setText("Entered text: " + textField.getText());
}
}
});
JButton okButton = new JButton("確定");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Entered text: " + textField.getText());
}
});
controlPanel.add(textField);
controlPanel.add(okButton);
mainFrame.setVisible(true);
}
}
執行上面範例程式碼,得到以下結果: