AWT FocusAdapter 类



简介

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

类声明

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

public abstract class FocusAdapter
   extends Object
      implements FocusListener

类构造函数

序号构造函数和说明
1

FocusAdapter()

类方法

序号方法和说明
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\tutorialspoint\gui\AwtAdapterDemo.java

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

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

验证以下输出

AWT FocusAdapter
awt_event_adapters.htm
广告