HOWTO · Java

Java 中的按鈕單擊事件

本教程演示如何在 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();
  }
}

上面的程式碼將建立一個帶有按鈕的框架,它會在點選時改變顏色。見輸出:

按鈕點選事件