Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Tầm quan trọng của giao diện FocusListener trong Java

FocusListener

  • Sự kiện focus được sinh ra khi một thành phần nhận hoặc mất focus bàn phím.
  • Đối tượng đại diện sự kiện focus được tạo từ lớp FocusEvent.
  • Giao diện listener tương ứng cho FocusEvent là FocusListener. Mỗi listener cho FocusEvent triển khai FocusListener.
  • Giao diện FocusListener chứa hai phương thức: focusGained(): Gọi bởi AWT ngay sau khi thành phần được lắng nghe nhận focus và focusLost(): Gọi bởi AWT ngay sau khi thành phần mất focus.

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);
    }
}

Kết quả

Tầm quan trọng của giao diện FocusListener trong Java

Tầm quan trọng của giao diện FocusListener trong Java