问题
Sometimes (not always) when scrolling the bar of my JScrollPane, some of the components (usually the text ones like JLabels) don't repaint properly and they end up only being partially rendered.
I don't know why this is. I've tried invoking paint() inside of an AdjustmentListener, but that doesn't seem to help.
Any ideas?
EDIT: Initialization of the components
panel = new JPanel();
ImageIcon img = new ImageIcon("editor.png");
setIconImage(img.getImage());
initComponents();
final JScrollPane pane = new JScrollPane(panel);
this.setContentPane(pane);
//pane.setLayout(new ScrollPaneLayout());
//pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
Dimension dim = panel.getSize();
dim.height = dim.height - 100;
pane.setSize(dim);
this.setSize(dim);
AdjustmentListener hListener = new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
repaint();
for(Component c : panel.getComponents())
c.repaint();
for(Component c : pane.getComponents())
c.repaint();
panel.repaint();
panel.revalidate();
pane.repaint();
pane.revalidate();
}
};
pane.getVerticalScrollBar().addAdjustmentListener(hListener);
panel.setVisible(true);
pane.setVisible(true);
回答1:
Violations of any of these basic principles can cause rendering artifact.
Verify that Swing GUI objects are constructed and manipulated only on the event dispatch thread.
Ensure that you honor the opacity property. In particular,
JLabel
is not opaque by default."Swing programs should override
paintComponent()
instead of overridingpaint()
."—Painting in AWT and Swing: The Paint Methods.
Addendum: Incorporating these dicta, this related example scrolls thousands of flashing JLabel
instances without artifact.
来源:https://stackoverflow.com/questions/11388810/swing-jscrollpane-causing-render-issues