如何在 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 输出窗口中显示

更新于:30-Jul-2019

3000+ 次查看

开启你的 职业

完成课程获得认证

开始学习
广告
© . All rights reserved.