Computer >> Máy Tính >  >> Lập trình >> Java

Tầm quan trọng của giao diện FocusListener trong Java là gì?

FocusListener

  • Các sự kiện tiêu điểm được tạo bất cứ khi nào một thành phần đạt được hoặc mất tiêu điểm bàn phím .
  • Các đối tượng đại diện cho các sự kiện tiêu điểm được tạo từ FocusEvent Cả lớp.
  • Giao diện trình nghe tương ứng cho FocusEvent lớp là FocusListener giao diện. Mỗi người nghe cho FocusEvent có thể triển khai FocusListener giao diện.
  • FocusListener giao diện chứa hai phương thức focusGained (): Được AWT gọi ngay sau khi thành phần đã lắng nghe nhận được tiêu điểm và focusLost (): Được AWT gọi ngay sau khi thành phần được lắng nghe mất tiêu điểm.

Cú pháp

public interface FocusListener extends EventListener {
   public void focusGained(FocusEvent fe);
   public void focusLost(FocusEvent fe);

Ví dụ

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FocusListenerTest extends JPanel implements FocusListener {
   private JTextField textField;
   public FocusListenerTest() {
      setLayout(new BorderLayout());
      textField = new JTextField();
      textField.addFocusListener(this);
      add(textField, BorderLayout.NORTH);
   }
   public void focusGained(FocusEvent fe) {
      System.out.println("Text field gained focus");
   }
   public void focusLost(FocusEvent fe) {
      System.out.println("Text field lost focus");
   }
   public static void main(String args[]) {
      JFrame frame = new JFrame();
      frame.add(new FocusListenerTest());
      frame.setTitle("FocusListener Test");
      frame.setSize(375, 250);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }
}

Đầu ra

Tầm quan trọng của giao diện FocusListener trong Java là gì?

Tầm quan trọng của giao diện FocusListener trong Java là gì?