gpt4 book ai didi

java - JTree 给出 ArrayIndexOutOfBoundsException?

转载 作者:行者123 更新时间:2023-12-03 12:58:02 25 4
gpt4 key购买 nike

我尝试将节点动态添加到 Java Swing JTree ,并且用户应该能够在不断添加节点的同时浏览和折叠层次结构。当我添加 Thread.sleep(10)在我的循环中,它工作正常;但这是一个肮脏的黑客......

这是触发此问题的精简代码。每当我运行它并双击根节点以展开/折叠它时(添加节点时),我得到一个 ArrayIndexOutOfBoundsException .当我添加 Thread.sleep(10)这不会发生。我想这是一个线程问题,但我不知道如何同步它?任何提示将不胜感激!

public static void main(String[] args) throws InterruptedException {
final JFrame frame = new JFrame();
frame.setSize(600, 800);
frame.setVisible(true);

MutableTreeNode root = new DefaultMutableTreeNode("root");
final DefaultTreeModel model = new DefaultTreeModel(root);
final JTree tree = new JTree(model);
frame.add(new JScrollPane(tree));

while (true) {
MutableTreeNode child = new DefaultMutableTreeNode("test");
model.insertNodeInto(child, root, root.getChildCount());
tree.expandRow(tree.getRowCount() - 1);

// uncommenting this to make it work
// Thread.sleep(10);
}
}

我想将它用于打字搜索应用程序,因此提供(几乎)即时结果对我来说至关重要。

编辑:感谢您的快速回答! SwingUtilities.invokeLater()解决了这个问题。

我现在这样做:
  • SwingUtilities.invokeLater(); 内添加 100 个项目
  • 在 100 个项目之后,我运行它以便 GUI 可以得到更新:
    // just wait so that all events in the queue can be processed
    SwingUtilities.invokeAndWait(new Runnable() {
    public void run() { };
    });

  • 这样我就有了一个非常灵敏的 GUI 并且它工作得很好。谢谢!

    最佳答案

    tree.expandRow 需要在事件线程中完成,所以改变循环如下:

    while (true) 
    {
    MutableTreeNode child = new DefaultMutableTreeNode("test");
    model.insertNodeInto(child, root, root.getChildCount());
    final int rowToExpand = tree.getRowCount() - 1; // ? does this work ?
    SwingUtilities.invokeLater(new Runnable()
    {
    public void run()
    {
    tree.expandRow(rowToExpand);
    }
    });

    }

    在此过程中,您可能需要确保树模型使用的任何列表都是同步的,因此在绘制线程遍历树时不要插入到集合中。

    关于java - JTree 给出 ArrayIndexOutOfBoundsException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/466599/

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