我遇到了一个问题:首先我从文件中加载一些大文本。之后我想在我的JTextPane中显示它。要将文本插入JTextPane,我使用:
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
textPane.setText(someLargeString);
}
});
但是当我的文本插入JTextPane时,所有UI都被冻结。
是否有能力将大型String插入JTextPane但没有UI冻结?
由于
P.S。 加载数据的过程在另一个线程中。但是在加载数据后我需要把它放到JTextPane中。所以我正在调用设置文本。但我的UI冻结了。为什么呢?
答案 0 :(得分:4)
你不应该在Swing EDT上拨打setText
;
setText
是线程安全的,请参阅API。 setText
与基础AbstractDocument
有关,而不是与Swing有关。 setText
在修改文档之前获取锁定。
但是必须从Swing EDT调用getText
。
答案 1 :(得分:3)
可能有些提示也可以提供帮助 http://java-sl.com/JEditorPanePerformance.html
如果您只需要纯文本,trashgod的答案是正确的。如果您有包含样式的文本,则需要使用JEditorPane / JTextPane。
答案 2 :(得分:2)
您可以尝试使用SwingWorker。 这是Java trail。
答案 3 :(得分:2)
我的字符串大小接近300千字节
如果JTextArea
是可接受的替代方案,则可以接受> 300 KiB在~1秒内。
import javax.swing.*;
import java.awt.*;
/** @see http://stackoverflow.com/questions/6536178 */
public class JTextAreaPasteTest {
public static void main(String argv[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
display();
}
});
}
private static void display() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String testStr = "Paste text here.";
JTextArea wrapArea = new JTextArea(testStr, 20, 40);
wrapArea.setLineWrap(true);
wrapArea.setWrapStyleWord(true);
wrapArea.setCaretPosition(testStr.length());
frame.add(new JScrollPane(wrapArea));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
答案 4 :(得分:0)
你可以将数据加载到另一个线程中。