gpt4 book ai didi

Java GUI 由于 insertString 方法而卡住?

转载 作者:行者123 更新时间:2023-11-30 01:39:27 24 4
gpt4 key购买 nike

您是否听说过由于重复调用 javax.swing.Document.insertString 方法而导致 GUI 卡住?

这是我的代码:

private int insertNotation(GameNode startNode, StyledDocument doc, int pos) {

String s = "";
int startPos = pos;
boolean isContinuous = false;

Style boldStyle, regularStyle, commentStyle, currentNodeStyle, nagStyle, grayStyle;
grayStyle = notationTextPane.getStyle("gray");
GameNode currentNode = history.getCurrentGameNode();
if ((currentNode.isLeaf() && startNode == currentNode.getParent()) || startNode == currentNode) {

try {
if (startNode.getComment().length() > 0) {
s = startNode.getComment() + " ";
commentStyle.addAttribute("gameNode", startNode);
doc.insertString(pos, s, commentStyle);
pos += s.length();
}
for (int n = 0; n < startNode.getChildCount(); n++) {
GameNode node = (GameNode) startNode.getChildAt(n);
boolean isCurrentNode = (node == currentNode);
if (node.isLeaf()) {
if (node.isWhiteMove()) {
s = node.getFullMoveNumber() + ". ";
boldStyle.addAttribute("gameNode", node);
doc.insertString(pos, s, boldStyle);
pos += s.length();
s = node.getMove();
Style style = isCurrentNode ? currentNodeStyle : regularStyle;
style.addAttribute("gameNode", node);
doc.insertString(pos, s, style);
pos += s.length();
isContinuous = true;
} else {
if (isContinuous) {
s = node.getMove();
Style style = isCurrentNode ? currentNodeStyle : regularStyle;
style.addAttribute("gameNode", node);
doc.insertString(pos, s, style);
pos += s.length();
} else {
isContinuous = true;
s = node.getFullMoveNumber() + "... ";
boldStyle.addAttribute("gameNode", node);
doc.insertString(pos, s, boldStyle);
pos += s.length();
s = node.getMove();
Style style = isCurrentNode ? currentNodeStyle : regularStyle;
style.addAttribute("gameNode", node);
doc.insertString(pos, s, style);
pos += s.length();
}
}
doc.insertString(pos++, " ", regularStyle);
}
} catch (BadLocationException e) {
e.printStackTrace();
}
return pos - startPos;
}

我对其进行了很多简化,但正如您所看到的,在我的“doc”StyledDocument 变量中,有很多对 insertString() 方法的调用。此 StyledDocument 对象添加到 JTabbedPane 中。

我已阅读here (在性能分析部分)javax.swing.Document.insertString 方法非常慢(这里每次调用超过 1 毫秒)。

重复调用它会卡住 GUI 吗?

最佳答案

每当您在主 GUI 线程中执行缓慢的操作时,您就会卡住 GUI。它根据处理事件进行重绘。想象一下,您的事件处理代码处于 while 循环中,将事件从队列中拉出 - 如果您不从函数返回,则无法处理下一个事件。

考虑在后台线程中进行长时间运行或缓慢的处理。

查看这篇文章:http://java.sun.com/products/jfc/tsc/articles/threads/threads2.html

关于Java GUI 由于 insertString 方法而卡住?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1341980/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com