共計 882 個字符,預計需要花費 3 分鐘才能閱讀完成。
ActionListener 是一個接口,用于處理按鈕點擊事件。要使用 ActionListener,需要實現這個接口并實現它的抽象方法。
以下是一個使用 ActionListener 的示例:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ActionListenerExample implements ActionListener {public static void main(String[] args) {JFrame frame = new JFrame("ActionListener Example");
JButton button = new JButton("Click Me");
ActionListenerExample listener = new ActionListenerExample();
button.addActionListener(listener);
frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {System.out.println("Button Clicked!");
}
}
在上面的示例中,我們創建了一個 JFrame 窗口和一個 JButton 按鈕。我們實現了 ActionListener 接口,并將其實例賦給按鈕的 addActionListener 方法。當按鈕被點擊時,actionPerformed 方法會被調用,輸出 ”Button Clicked!”。
注意,我們可以在 actionPerformed 方法中編寫自己的邏輯,以便處理點擊事件。
丸趣 TV 網 – 提供最優質的資源集合!
正文完