溫馨提示×

java清除文本框內(nèi)容如何操作

小億
119
2023-12-23 23:13:11
欄目: 編程語言

在 Java中,要清除文本框的內(nèi)容,可以使用setText()方法將文本框的文本內(nèi)容設(shè)置為空字符串。下面是一個(gè)示例代碼:

import javax.swing.*;

public class ClearTextFieldExample {
    public static void main(String[] args) {
        JTextField textField = new JTextField();
        JButton clearButton = new JButton("清除");

        clearButton.addActionListener(e -> {
            textField.setText(""); // 清除文本框的內(nèi)容
        });

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new java.awt.FlowLayout());
        frame.add(textField);
        frame.add(clearButton);
        frame.pack();
        frame.setVisible(true);
    }
}

上述代碼創(chuàng)建了一個(gè)包含一個(gè)文本框和一個(gè)清除按鈕的簡單的圖形用戶界面。當(dāng)點(diǎn)擊清除按鈕時(shí),通過調(diào)用setText(“”)方法將文本框的內(nèi)容設(shè)置為空字符串,從而清除文本框的內(nèi)容。

0