如何在 Java 中為 JButton 設定動作命令
透過設定動作命令,這裡我們在單擊某個按鈕時在控制檯上顯示一條訊息。
首先設定按鈕
JButton btn = new JButton("Demo Button");
現在,將 Action Listener 設定為在單擊按鈕時觸發
ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent event) { String str = event.getActionCommand(); System.out.println("Clicked = " + str); } };
以下是為 JButton 設定動作命令的一個示例
示例
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JOptionPane; public class SwingDemo { public static void main(final String args[]) { JButton btn = new JButton("Demo Button"); ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent event) { String str = event.getActionCommand(); System.out.println("Clicked = " + str); } }; btn.setActionCommand("FirstButton"); btn.addActionListener(actionListener); JOptionPane.showMessageDialog(null, btn); } }
輸出
當單擊上面的“Demo Button”時,以下文字將在 EclipseIDE 輸出視窗中顯示
廣告