我创建了一个自定义 JComponent,它在paintComponent 中绘制文本。将它放在 ScrollPane 中我想在附加文本超出视口时自动显示 scollbars。当我调整整个框架的大小时,滚动条会正确更新。但我想以编程方式进行。我尝试了几个#validate() 和#invalidate() 调用,但无济于事。
如何使用自定义组件作为客户端更新滚动窗格的滚动条?
我创建了一个简化的可运行示例来说明我的意思:
package swingscroll;
import java.awt.Color;
import java.awt.Dimension;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class SwingScroll {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
final JFrame frame = new JFrame(SwingScroll.class.getSimpleName());
final JComponent myComponent = new JComponent() {
private Dimension preferredSize;
@Override
public void setPreferredSize(Dimension preferredSize) {
super.setPreferredSize(preferredSize);
this.preferredSize = preferredSize;
}
@Override
public Dimension getPreferredSize() {
return this.preferredSize;
}
};
myComponent.setPreferredSize(new Dimension(380, 50));
final JScrollPane scrollPane = new JScrollPane(myComponent);
frame.getContentPane().add(scrollPane);
frame.setSize(400, 100);
frame.setVisible(true);
// simulate the internal change of preferredSize in myComponent
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(SwingScroll.class.getName()).log(Level.SEVERE, null, ex);
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// this should trigger the scrollbar right?
myComponent.setPreferredSize(new Dimension(380, 1000));
// TODO insert code to update scrollbars
}
});
}
}).start();
}
}