如何在 Java 中为 JButton 添加操作监听器


以下是为按钮添加操作监听器的示例

示例

package my;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingDemo {
   private JFrame frame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   public SwingDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingDemo swingControlDemo = new SwingDemo();
      swingControlDemo.showButtonDemo();
   }
   private void prepareGUI(){
      frame = new JFrame("Java Swing");
      frame.setSize(500,500);
      frame.setLayout(new GridLayout(3, 1));
      frame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }
      });
      headerLabel = new JLabel("", JLabel.CENTER);
      statusLabel = new JLabel("",JLabel.CENTER);
      statusLabel.setSize(350,100);
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());
      frame.add(headerLabel);
      frame.add(controlPanel);
      frame.add(statusLabel);
      frame.setVisible(true);
   }
   private void showButtonDemo(){
      headerLabel.setText("Button Demo");
      JButton okButton = new JButton("OK");
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("Ok Button is clicked here");
         }
      });
      controlPanel.add(okButton);
      frame.setVisible(true);
   }
}

输出

现在,在单击上述“确定”按钮后,会出现以下内容

更新于: 2019-07-30

8K+ 阅读

开启你的职业

通过完成课程获取证书

开始吧
广告