【发布时间】:2012-01-06 21:02:57
【问题描述】:
编辑:现已解决,但两天内无法标记为已接受
在我的课堂上,我有一个JScrollPanel,里面也有一个JPanel。
我的代码类似于这样:
import java.awt.Color;
import java.awt.Container;
import javax.swing.*;
public class MyClass {
private JPanel p;
private JScrollPane s;
private Container contentPane;
public MyClass(Container contentPane) {
this.contentPane = contentPane;
this.p = new JPanel();
this.p.setBackground(Color.WHITE);
BoxLayout boxLayout = new BoxLayout(this.p, BoxLayout.Y_AXIS);
this.p.setLayout(boxLayout);
this.s = new JScrollPane(this.p);
this.s.setSize(400, 364);
this.contentPane.add(this.s);
}
public final JLabel makeJLabel(String message) {
JLabel jLabel = new JLabel("<html><p style=\"padding-left:15px;padding-right:15px;width:280px;\">" + message.replaceAll("(\r\n|\n)", "<br />") + "</p></html>");
/*
some stuff here to calculate pref/max size and add an imageicon
*/
p.add(jLabel);
this.p.revalidate();
this.s.revalidate(); //just added because the above line made no effect
scrollToBottom();
return jLabel;
}
public void scrollToBottom() {
JScrollBar vertical = s.getVerticalScrollBar();
vertical.setValue(vertical.getMaximum());
}
}
在我班的其他地方,我有一个方法可以将JLabel 添加到JPanel。这个实际方法很长,所以我不会全部发布,但这是将其添加到面板的代码:p.add(jLabel1);
感谢 Box Layout,所有这些 JLabels 都以垂直方式添加。
在 JLabel 添加到 JPanel 之后,我希望 JScrollPane 滚动到底部。但这要等到JPanel 实际被绘制(绘制?)到JPanel 上之后才能完成。否则我会得到这个结果:
所以我想要做的是向JPanel 添加某种形式的监听器,它检测我的JLabel 何时被绘制到它,这样我就可以告诉我的JScrollPane 滚动到底部。我已经编写了一个将窗格滚动到底部的方法,但是我还没有适合调用它的地方。
请问有人对此有什么想法吗?谢谢。
【问题讨论】: