怎么让一个文本框与另一个同步显示 java
时间: 2024-01-16 17:02:12 浏览: 43
你可以使用 Java Swing 中的 JTextArea 组件来显示文本框中的内容,并使用 DocumentListener 接口来监听文本框的内容变化,以实现同步显示。具体步骤如下:
1. 创建两个 JTextArea 组件,一个用于输入,一个用于显示。
2. 获取输入 JTextArea 的 Document 对象,并为其添加 DocumentListener 接口的实现类,以监听输入内容的变化。
3. 在 DocumentListener 的实现类中,获取输入 JTextArea 中的文本,然后将其设置到显示 JTextArea 中。
这样,当用户在输入 JTextArea 中输入内容时,显示 JTextArea 中的内容也会随之改变,实现了同步显示。
以下是一个简单的示例代码:
```java
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class SyncTextAreaDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("SyncTextAreaDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
JTextArea inputTextArea = new JTextArea();
JTextArea displayTextArea = new JTextArea();
displayTextArea.setEditable(false);
inputTextArea.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
displayTextArea.setText(inputTextArea.getText());
}
@Override
public void removeUpdate(DocumentEvent e) {
displayTextArea.setText(inputTextArea.getText());
}
@Override
public void changedUpdate(DocumentEvent e) {
displayTextArea.setText(inputTextArea.getText());
}
});
JScrollPane inputScrollPane = new JScrollPane(inputTextArea);
JScrollPane displayScrollPane = new JScrollPane(displayTextArea);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, inputScrollPane, displayScrollPane);
frame.getContentPane().add(splitPane);
frame.setVisible(true);
}
}
```
在这个示例中,我们创建了两个 JTextArea 组件,一个用于输入,一个用于显示,并将它们放到了一个 JSplitPane 中,以便用户可以拖动调整它们的大小。
然后,我们获取了输入 JTextArea 的 Document 对象,并为其添加了一个 DocumentListener 的实现类。在这个实现类中,我们通过 getText() 方法获取输入 JTextArea 中的文本,并将其设置到显示 JTextArea 中,以实现同步显示。需要注意的是,我们为三个方法都添加了相同的实现,这是因为这三个方法分别对应文本的插入、删除和修改操作,我们需要在这三个操作中都更新显示 JTextArea 的内容。
相关推荐
![](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)