在 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)容。