溫馨提示×

java怎么實現點擊按鈕清空文本框

小億
165
2023-11-16 12:04:23
欄目: 編程語言

在Java中,可以通過使用按鈕的事件監聽器來實現點擊按鈕清空文本框的功能。下面是一個實現的示例代碼:

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

public class ClearTextFieldExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Clear Text Field Example");

        JTextField textField = new JTextField();
        textField.setBounds(50, 50, 200, 30);

        JButton button = new JButton("Clear");
        button.setBounds(100, 100, 100, 30);

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                textField.setText(""); // 清空文本框
            }
        });

        frame.add(textField);
        frame.add(button);

        frame.setSize(300, 200);
        frame.setLayout(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

在這個示例代碼中,創建了一個JFrame窗口,其中包含一個文本框JTextField和一個按鈕JButton。按鈕使用addActionListener方法添加了一個事件監聽器,當按鈕被點擊時,事件監聽器中的actionPerformed方法會被調用,從而實現清空文本框的功能。在actionPerformed方法中,通過textField.setText("")將文本框的內容設置為空字符串,即實現了清空文本框的效果。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女