我有一個容納JPanel的JScrollPane。 JPanel上的佈局是一個GridBagLayout。在那個JPanel上,我添加了一些自定義組件 - 每個都是一個帶有3個JLabel的JPanel。強制JScrollPane和JPanel重繪
在程序中我第一次把所有這一切都解決了,它工作正常。當我調用代碼將另一個自定義組件添加到JPanel時,面板顯示爲空,但我可以通過檢查JPanel的內容來確定組件實際存在的內容。如果我調整這個所有站點的JDialog的大小,JPanel會正確繪製。如果我將JScrollPane水平滾動一點,它也可以工作。
我在添加項目時使用與初始佈局相同的方法。 (),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);
}
});
}
revalidate()調用是我所缺少的。 – Mitch
完美!謝謝 :) –