Java 中的按钮单击事件

Sheeraz Gul 2023年10月12日
Java 中的按钮单击事件

我们使用事件侦听器在 Java 中创建按钮单击事件。本教程演示如何在 Java 中创建按钮单击事件。

Java 中的按钮单击事件

在 Java 中创建按钮单击事件是一个循序渐进的过程。

  • 导入所有必需的包,尤其是 Java.awt.event
  • 创建一个将调用事件的 Main 类。
  • 创建另一个包含 JFrame 类的对象、用户定义的方法和构造函数的类。
  • 接下来是将按钮添加到 JFrame 并创建 JButton 类的对象。
  • 接下来是实现 actionListener 接口。
  • 最后,我们将 actionListener 注册到按钮。

让我们尝试实现一个在 Java 中单击时会改变颜色的示例。参见示例:

package delftstack;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class ActionEventDemo implements ActionListener {
  JFrame Demo_Frame = new JFrame();
  JButton Demo_Button = new JButton("Click Here");

  ActionEventDemo() {
    Prepare_GUI();
    Button_Properties();
  }

  public void Prepare_GUI() {
    Demo_Frame.setTitle("Demo Window");
    Demo_Frame.getContentPane().setLayout(null);
    Demo_Frame.setVisible(true);
    Demo_Frame.setBounds(400, 100, 400, 400);
    Demo_Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
  public void Button_Properties() {
    Demo_Button.setBounds(150, 200, 150, 80);
    Demo_Frame.add(Demo_Button);
    Demo_Button.addActionListener(this);
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    // Changing Background Color
    Demo_Frame.getContentPane().setBackground(Color.red);
  }
}

public class On_Click {
  public static void main(String[] args) {
    new ActionEventDemo();
  }
}

上面的代码将创建一个带有按钮的框架,它会在点击时改变颜色。见输出:

按钮点击事件

作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook