共計 852 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 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("")
將文本框的內容設置為空字符串,即實現了清空文本框的效果。
丸趣 TV 網 – 提供最優質的資源集合!
正文完