我有一个包含 JPanel 的 JScrollPane。 JPanel 上的布局是 GridBagLayout。在那个 JPanel 上,我添加了一些自定义组件——每个组件都是一个带有 3 个 JLabel 的 JPanel。
我第一次在程序中列出所有这些,它运行良好。当我调用代码将另一个自定义组件添加到 JPanel 时,面板显示为空,但我可以通过检查 JPanel 的内容来确定我的组件确实存在。如果我调整所有站点所在的 JDialog 的大小,JPanel 将正确绘制。如果我水平滚动 JScrollPane 哪怕是一点点,它也会起作用。
我对初始布局使用与添加项目时相同的方法。
我已经尝试了 repaint()、invalidate() 和 doLayout() 的各种组合,但似乎没有任何效果。我以前遇到过这种情况,一直没能完全解决。有什么建议吗?
在 OpenJDK 7u25 下运行。下面是布置滚动 Pane 和面板的代码。
private void displayRelatedBug(ArrayList<Bug> a_bugs) {
// sort the bugs by ID
ArrayList<Bug> l_sorted = new ArrayList<>(a_bugs);
Collections.sort(l_sorted);
pnlRelatedBugs.removeAll();
pnlRelatedBugs.setLayout(new GridBagLayout());
GridBagConstraints l_gbc = new GridBagConstraints();
l_gbc.gridx = 0;
l_gbc.gridy = 0;
l_gbc.gridwidth = 1;
l_gbc.gridheight = 1;
l_gbc.anchor = GridBagConstraints.NORTHWEST;
l_gbc.fill = GridBagConstraints.NONE;
l_gbc.insets = new Insets(3, 4, 0, 0);
for (Bug r : l_sorted) {
pnlRelatedBugs.add(new RelatedBugDisplay(r, this), l_gbc);
l_gbc.gridy++;
}
// add a filler at the bottom to push it up
l_gbc.weighty = 1.0;
pnlRelatedBugs.add(new MMPanel(), l_gbc);
// add a filler on the right to push them left
l_gbc.weighty = 0.0;
l_gbc.weightx = 1.0;
l_gbc.gridx++;
pnlRelatedBugs.add(new MMPanel(), l_gbc);
// try in vain to make it show up!!!
pnlRelatedBugs.invalidate();
pnlRelatedBugs.doLayout();
pnlRelatedBugs.repaint();
scrollerRelatedBugs.doLayout();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
pnlRelatedBugs.repaint();
scrollerRelatedBugs.repaint();
// this seems to help if the scroll bar is showing
scrollerRelatedBugs.getHorizontalScrollBar().setValue(1);
scrollerRelatedBugs.getHorizontalScrollBar().setValue(0);
}
});
}
最佳答案
每当您从可见面板中添加/删除组件时,基本代码是:
panel.remove(...);
panel.add(...);
panel.revalidate();
panel.repaint();
如果没有适当的 SSCCE
,我们无法真正了解您的代码在做什么。
关于java - 强制 JScrollPane 和 JPanel 重绘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19730671/