JTextArea怎么能让用户 输入文字,并设置输入文字的位置呢,最好显示“请在此处输入文字”当用户点击时,这句提示话语消失,并让用户输入
时间: 2024-03-07 07:50:46 浏览: 35
要实现这个功能,可以使用JTextArea和FocusListener。
首先,创建一个JTextArea并设置它的初始文本为“请在此处输入文字”:
```
JTextArea textArea = new JTextArea("请在此处输入文字");
```
然后,添加一个FocusListener来监听焦点事件,当用户点击JTextArea时,将其文本设置为空字符串:
```
textArea.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
if (textArea.getText().equals("请在此处输入文字")) {
textArea.setText("");
}
}
public void focusLost(FocusEvent e) {
if (textArea.getText().equals("")) {
textArea.setText("请在此处输入文字");
}
}
});
```
最后,将JTextArea添加到你的GUI中,并设置它的位置和大小:
```
frame.add(textArea);
textArea.setBounds(x, y, width, height);
```
这样,当用户点击JTextArea时,提示文本会消失,并且用户可以输入自己的文本,当用户离开JTextArea时,如果JTextArea没有文本,则提示文本会重新显示。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)