gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:38:11 24 4
gpt4 key购买 nike

我想刷新我的 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时才滚动。为什么?

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

我想我怀念这里的一些挥杆哲学..

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

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

最佳答案

textPane.update(textPane.getGraphics());

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

The thing is, my window is scrolled down, but only when exiting actionPerformed. Why ?

您的代码正在循环中执行,该循环在事件调度线程(即绘制 GUI 的线程)上执行。在循环完成之前,GUI 无法重新绘制自身。

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

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

关于java - JScrollPane 不会向下滚动以正确显示从 ActionListener 调用的 JTextPane,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31726678/

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