Re: JScrollPane - strange repainting problem?



lmierzej wrote:
Hi,

why JScrollPane is not repainting like other components (like JButton)?

repaint()on main frame doesn't work on JScrollPane, only setVisible(true) on main frame works well

could anyone help? (there is a quick, working code example below)

thanks very much in advance for your help!


CODE SAMPLE: import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.ScrollPaneConstants;

public class ScrollPaneTest extends JFrame{
public ScrollPaneTest() {
this.setLayout(null);

May not set JFrame layout directly - only to its content pane

this.setBounds(100,100,300,300);
this.setVisible(true);

Don't setVisible true before finishing construction

//JScrollPane begin
JScrollPane scrollPane = new JScrollPane();
JLabel label = new JLabel("This is JLabel!");
scrollPane.setViewportView(label);
scrollPane.setBounds(50,50,80,80);



scrollPane.setVerticalScrollBarPolicy(
ScrollPaneConstants.
VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(
ScrollPaneConstants.
HORIZONTAL_SCROLLBAR_ALWAYS);
this.getContentPane().add(scrollPane);
//JScrollPane end

If you will not set content pane layout to null - you should specify position, because default layout for content pane is BorderLayout


//JButton begin
JButton button = new JButton();
button.setBounds(50,200,50,50);
this.getContentPane().add(button);
//JButton end
this.repaint(); //JScrollPane content is blank!

repaint may not need to be called.

//But setVisible(true) makes everything ok.
}


public static void main(String[] args) {
new ScrollPaneTest();
}
}

Construct UI. (Constructor) Pack it. (pack()) Show it (setVisible(true))

try this:
public ScrollPaneTest() {
  JLabel label = new JLabel("This is JLabel!");
  JScrollPane scrollPane = new JScrollPane(label,
	ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
	ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

  this.getContentPane().add(scrollPane, BorderLayout.CENTER);

  JButton button = new JButton("Button");
  getContentPane().add(button, BorderLayout.NORTH);

  pack();
}

public static void main(String[] args) {
  final ScrollPaneTest f = new ScrollPaneTest();
  f.setDefaultCloseOperation(EXIT_ON_CLOSE);

  EventQueue.invokeLater(new Runnable() {
    public void run() {
	f.setVisible(true);
    }
  });
}
.