在Java中,為按鈕添加Action事件通常是通過使用ActionListener
接口來實現的
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
JFrame
,同時實現ActionListener
接口:public class ButtonActionExample extends JFrame implements ActionListener {
// 類的其他部分
}
private JButton button;
public ButtonActionExample() {
button = new JButton("點擊我");
button.addActionListener(this);
this.setLayout(new FlowLayout());
this.add(button);
this.setSize(300, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
actionPerformed
方法以處理按鈕點擊事件:@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
JOptionPane.showMessageDialog(this, "按鈕被點擊了!");
}
}
main
方法中創建類的實例:public static void main(String[] args) {
new ButtonActionExample();
}
將上述代碼片段組合在一起,完整的示例代碼如下:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonActionExample extends JFrame implements ActionListener {
private JButton button;
public ButtonActionExample() {
button = new JButton("點擊我");
button.addActionListener(this);
this.setLayout(new FlowLayout());
this.add(button);
this.setSize(300, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
JOptionPane.showMessageDialog(this, "按鈕被點擊了!");
}
}
public static void main(String[] args) {
new ButtonActionExample();
}
}
運行此代碼,你將看到一個包含按鈕的窗口。當你點擊按鈕時,將彈出一個對話框顯示“按鈕被點擊了!”。