ActionListener trong Java AWT – VietTuts

ActionListener được gọi bất cứ khi nào bạn click button hoặc menu item. ActionListener thuộc về package java.awt.event, nó chỉ có một phương thức actionPerformed().

Phương thức actionPerformed()

Phương thức actionPerformed() được gọi tự động bất cứ khi nào bạn nhấp vào thành phần đã đăng ký.

public abstract void actionPerformed(ActionEvent e);

Nội dung chính

  • Ví dụ về Java ActionListener: click button

Ví dụ về Java ActionListener: click button

package vn.viettuts.awt;

import java.awt.Button;
import java.awt.Frame;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ActionListenerExample {
    public static void main(String[] args) {
        Frame frame = new Frame("Ví dụ ActionListener trong Java AWT");
        final TextField textField = new TextField();
        textField.setBounds(50, 50, 150, 20);
        Button button = new Button("Click Here");
        button.setBounds(50, 100, 60, 30);

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                textField.setText("Welcome to VietTuts.Vn");
            }
        });
        frame.add(button);
        frame.add(textField);
        frame.setSize(450, 200);
        frame.setLayout(null);
        frame.setVisible(true);
    }
}

Kết quả:

Ví dụ ActionListener trong Java AWT