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

时间:2015-07-30 14:33:45

标签: java swing actionlistener jscrollpane jtextpane

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

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

    // ...
}

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

我想通过按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());
        }
    }
}

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

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

我想我在这里错过了一些摇摆哲学。

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

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

2 个答案:

答案 0 :(得分:7)

textPane.update(textPane.getGraphics());

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

  

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

您的代码正在循环中执行,该循环在事件调度线程上执行,该线程是绘制GUI的线程。在循环结束之前,GUI无法重新绘制。

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

我可能会在此线程中使用Swing Worker,然后您可以在结果可用时“发布”结果。阅读Concurrency上Swing教程中的部分,了解有关使用SwingWorker的更多信息和示例。

答案 1 :(得分:1)

正如@camickr建议的那样,在SwingWorker中运行actionPerformed()的内容。其内容应包含以下内容:

    Runnable runner = new Runnable() {
        @Override
        public void run() {
           textPane.appendANSI(line+"\n");
           textpane.setCaretPosition(textpane.getDocument().getLength());
        }
    }
    while ((line = in.readLine()) != null) {
        SwingUtilities.invokelater( runner );
    }