📄 e971. asynchronously reading the contents of a visible jtextcomponent.txt
字号:
When a text component is visible on the screen, you cannot simply call getText() on the document model to retrieve the text. The reason is that the user may be modifying the text at the same time. There are two ways to safely access the contents of the text component. One is by using SwingUtilities.invokeLater() and the other is by using Document.render(). This example demonstrates the latter.
// Create and display the component
JTextComponent textComp = new JTextArea();
Document doc = textComp.getDocument();
JFrame frame = new JFrame();
frame.getContentPane().add(textComp, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
// Read the contents
try {
process(read(doc));
} catch (InterruptedException e) {
} catch (Exception e) {
}
// This method returns the contents of a Document using a renderer.
public static String read(Document doc) throws InterruptedException, Exception {
Renderer r = new Renderer(doc);
doc.render(r);
synchronized (r) {
while (!r.done) {
r.wait();
if (r.err != null) {
throw new Exception(r.err);
}
}
}
return r.result;
}
static class Renderer implements Runnable {
Document doc;
String result;
Throwable err;
boolean done;
Renderer(Document doc) {
this.doc = doc;
}
public synchronized void run() {
try {
result = doc.getText(0, doc.getLength());
} catch (Throwable e) {
err = e;
e.printStackTrace();
}
done = true;
// When done, notify the creator of this object
notify();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -