JTree 给出 ArrayIndexOutOfBoundsException?

mar*_*nus 3 java swing multithreading synchronization jtree

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

这是触发此问题的精简代码。每当我运行它并双击根节点以展开/折叠它(在添加节点时),我都会得到一个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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

我现在这样做:

  1. 添加 100 项以内SwingUtilities.invokeLater();
  2. 100 个项目后,我运行此命令以便 GUI 可以更新:

    // just wait so that all events in the queue can be processed
    SwingUtilities.invokeAndWait(new Runnable() {
        public void run() { }; 
    });
    
    Run Code Online (Sandbox Code Playgroud)

这样我就拥有了一个响应非常灵敏的 GUI,而且它工作得非常完美。谢谢!

Pau*_*lin 5

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);
           }
        });

}
Run Code Online (Sandbox Code Playgroud)

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