[英]Force JScrollPane and JPanel to repaint
我有一個包含JPanel的JScrollPane。 JPanel上的布局是GridBagLayout。 在那個JPanel上,我添加了許多自定義組件 - 每個組件都是一個帶有3個JLabel的JPanel。
在程序中我第一次將所有這些都放在一邊,它運行正常。 當我調用代碼將另一個自定義組件添加到JPanel時,面板顯示為空,但我可以通過檢查JPanel的內容來確定我的組件實際存在。 如果我調整所有網站的JDialog大小,JPanel將正確繪制。 如果我水平滾動JScrollPane甚至一點點也可以。
我在添加項目時使用與初始布局相同的方法。
我已經嘗試了repaint(),invalidate()和doLayout()的各種組合,但似乎沒有任何東西一直在工作。 我以前遇到過這種情況,從來沒有能夠完全解決它。 有什么建議么?
在OpenJDK 7u25下運行。 下面是列出滾動窗格和面板的代碼。
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
我們無法確切知道您的代碼在做什么。
如果您在顯示容器上添加/刪除/替換/其他操作與組件,則必須revalidate
並repaint
容器,並向其添加組件以進行正確顯示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.