要為按鈕添加ActionListener,可以通過以下步驟來實(shí)現(xiàn):
JButton button = new JButton("Click Me");
class MyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// 處理按鈕點(diǎn)擊事件的邏輯
System.out.println("Button clicked!");
}
}
MyActionListener myListener = new MyActionListener();
button.addActionListener(myListener);
現(xiàn)在,當(dāng)用戶點(diǎn)擊按鈕時,MyActionListener類的actionPerformed方法將被調(diào)用,從而處理按鈕點(diǎn)擊事件的邏輯。