JScrollPane不会向下滚动以正确显示从ActionListener调用的JTextPane

Luc*_*ien 2 java swing jtextpane jscrollpane actionlistener

我想刷新我的ColorPane定义如下:

public class ColorPane extends JTextPane{
    /* FYI, The function below allows me to add text with ANSI Coloring */
    public void appendANSI(String s) {
        // ...
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

在下一个while语句中,我line在一个控制台式窗口中编写.因此,作为控制台,我想在添加新行时自动刷新并向下滚动textPane.

我想通过按a启动以下循环mainButton.

public class mainButton implements ActionListener  {
    public void actionPerformed (ActionEvent e) {
        ColorPane textPane = new ColorPane();

        /* FYI, in is a BufferedReader */
        while ((line = in.readLine()) != null) {

            /* Add automatically in the console window */
            textPane.appendANSI(line+"\n");

            /* Last possible workaround I tried
               Which as the same effect than commenting these lines.. */
            JScrollBar vertical = scrollPane.getVerticalScrollBar();
            vertical.setValue(vertical.getMaximum());

            /* I also tried : */
            // textPane.setCaretPosition(textPane.getDocument().getLength());

            /* Or this : */
            // Rectangle rec = GenerationWindow.textPane.getVisibleRect();
            // rec.setLocation((int) (rec.getX() + 1000), (int) rec.getY());
            // textPane.scrollRectToVisible(rec);

            /* Refresh the display */
            textPane.update(textPane.getGraphics());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,我的窗口向下滚动,但只有在退出时actionPerformed.为什么?

一方面我可以看到文本在每次循环转换时都会更新,但另一方面,JScrollPane scrollPane在函数结束时向下滚动...

我想我想念一些摇摆哲学......

我已经在Oracle Documentation和StackO主题上漫游了几个小时,尝试了不同的"解决方案",但我现在有点绝望了......

不自动向下滚动的控制台是..好吧..不是控制台..

cam*_*ckr 7

textPane.update(textPane.getGraphics());
Run Code Online (Sandbox Code Playgroud)

不要在组件上手动调用update(...).Swing将确定何时需要重新绘制组件.

问题是,我的窗口向下滚动,但仅在退出actionPerformed时.为什么?

您的代码在循环中执行,该循环在Event Dispatch Thread上执行,该Thread是绘制GUI的Thread.在循环结束之前,GUI无法重绘自身.

长时间运行的代码需要在单独的线程上执行,然后当您更新文本窗格时,GUI可以自由重绘自身.

我可能会Swing Worker在这个帖子中使用a ,然后你可以在结果可用时"发布"结果.阅读有关并发的Swing教程中的部分,以获取有关使用SwingWorker的更多信息和示例.