gumuruh
gumuruh

Reputation: 2570

How to use Scroll on JPanel? (Swing)

I'm actually having no problem when dealing with the JScrollPane with JTextArea... But here... I have a JPanel. And I wanted to use Scroll on it.

Take a look on my JPanel here Image Preview. I wonder how to do it in netbeans. I think I should do a bit of customized coding. So, I tried to do like this;

1) Right Click on jPanel2, Customize Code. 2) Using This modified code;

Initialization Code:

jPanel2 = new javax.swing.JPanel();
scrb = new javax.swing.JScrollPane(jPanel2);
// Code of sub-components - not shown here

// Layout setup code - not shown here
scrb.setPreferredSize(jPanel2.getPreferredSize());
jPanel1.add(jPanel2, "card2");

Variable Declaration Code:

private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane scrb;

Then re-run my Project again.... but,... sigh. THe Scroll didn't came up into the running app.

Is there anything I forget over here?

I tried to manipulate the Size of the jPanel2, but hence not work.... The Scroll didn't appeared.

Upvotes: 3

Views: 9244

Answers (4)

Renjith Thomas
Renjith Thomas

Reputation: 157

If you are using NetBeans IDE, it is better to use GUI designer to create scroll pane. Use the below steps to implement a scroll pane:

    1. In Netbeans GUI editor, select all panels which requires scroll pane using CTRL+left click
    2. Right click on the highlighted panels, select the option 'Enclose in' -> Scroll Pane. This will add a scroll pane for the selected panels.
    3. If there are other elements than Panel(say JTree), select all the elements ->Enclose in ->Panel. Then enlose the new parent panel to scroll pane
    4. Make sure that 'Auto Resizing' is turned on for the selected parent panel(Right click on panel -> Auto resizing -> Tick both Horizontal and vertical)

Upvotes: 0

camickr
camickr

Reputation: 324078

In addition to the other suggestions to add the scrollpane to the panel, I'm not sure if it will work because of the following line of code:

scrb.setPreferredSize(jPanel2.getPreferredSize()); 

Scrollbars only appear when the preferred size of the component added to the the scrollpane is greater than the size of the scrollpane. So if you layout manager respects the preferred size of the components this condition will never be true.

Upvotes: 0

Qwerky
Qwerky

Reputation: 18405

Try adding the scrb to jpanel1.

Here's a nice tutorial in scroll panes;

http://download.oracle.com/javase/tutorial/uiswing/components/scrollpane.html

Upvotes: 3

Harry Joy
Harry Joy

Reputation: 59650

The problem is in this line:

jPanel1.add(jPanel2, "card2");

Instead of this write this:

jPanel1.add(scrb, "card2");

What you are doing is adding jPnael2 to a scrollpant but then instead of adding that scrollpane to jPanel1 you add jPanel2 to jPanel1 so scrollPane doesn't even come to picture.

Upvotes: 6

Related Questions