Question

I'm currently writing a Java GUI application using NetbeansIDE 7.4 and have encountered the following problem:

I have a jPannel enclosed in a jScrollPane of initial dimension 300,160 Every time i click on a jButton at runtime, I resize the jPannel as follows:

jPanel3.setPreferredSize(new Dimension(300, (count + 3) * 30));
jPanel3.repaint();

if the count variable is larger than 3, the Vertical Scrollbar adapts to the jPannel every time I resize it.

But if count is less than 3, the vertical scrollbar dissapears, and when I resize the jPannel again ( lets say, count = 10), the Scrollbar doesn't show up anymore.

Is this normal? How can i fix it?

Was it helpful?

Solution

Is this normal? How can i fix it?

Don't know if that is normal or not, but that is not the proper way to resize the panel. A Swing component is responsible to determining its size, not your application code. This is done by creating a setter method when you want to change a property of your component.

If you want to dynamically change the size of the panel then you should override the getPreferredSize() method of your custom panel. Something like:

@Override
public Dimentsion getPreferredSize()
{
    return new Dimension( new Dimension(300, (getCount() + 3) * 30) );
}

Then in you class you should create a setter (and getter) method for your count:

public void setCount(int count)
{
    this.count = count;
    revalidate()
    repaint();
}

Now the revalidate will cause the preferred size to be recalculated and the scroll pane will then use the new preferred size.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top