AWT FocusAdapter 类

简介

FocusAdapter 是一个用于接收键盘焦点事件的抽象(适配器)类。此类的所有方法均为空。此类是创建侦听器对象的便利类。

类声明

以下是 java.awt.event.FocusAdapter 类的声明:

public abstract class FocusAdapter
    extends Object
        implements FocusListener

类构造函数

S.N.构造函数 &描述
1

FocusAdapter()

类方法

S.N.方法和描述
1

void focusGained(FocusEvent e)

当组件获得键盘焦点时调用。

2

focusLost(FocusEvent e)

当组件失去键盘焦点时调用。

继承的方法

此类从以下类继承方法:

  • java.lang.Object

FocusAdapter 示例

使用您选择的任何编辑器在 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序

AwtAdapterDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtAdapterDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtAdapterDemo  awtAdapterDemo = new AwtAdapterDemo();        
      awtAdapterDemo.showFocusAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      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");      

      Button okButton = new Button("OK");
      Button cancelButton = new Button("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:/ > AWT 并键入以下命令。

D:\AWT>javac com	utorialspoint\gui\AwtAdapterDemo.java

如果没有错误,则表示编译成功。使用以下命令运行程序。

D:\AWT>java com.tutorialspoint.gui.AwtAdapterDemo

验证以下输出

AWT FocusAdapter

awt_event_adapters.html