user1864229 user1864229 - 1 month ago 14
Java Question

How to add JPanel into another JPanel with vertical scrollpane at runtime?

I'm trying to insert a new panel into another panel in runtime everytime I press a button. My problem is the original panel runs out of space and I can't see the new panels I'm adding.

What I've tried so far:


  • Using scrollpane for vertical scrolling with no success.

  • Using flowlayout-no luck. Tried disabling horizontal scrolling-keep pushing the new panel to the right (can't get to it because there is no scrolling).

  • Tried using borderlayout-no luck.






testpanel t = new testpanel();
t.setVisible(true);
this.jPanel15.add(t);
this.jPanel15.validate();
this.jPanel15.repaint();


This code suppose to insert the
t
panel into
jpanel15
.
With flowlayout it pushes the
t
panel downwards just like I want it to but with no vertical scroll.

PS: I'm using netbeans in order to create my GUI.

TT. TT.
Answer
  1. Use JScrollPane instead of the (outer) JPanel
  2. Or have a BorderLayout for the JPanel, put in a JScrollPane at BorderLayout.CENTER as the only control. The JScrollPane takes a regular JPanel as view.

In any case you will then add the control to the JScrollPane. Suppose your JScrollPane variable is spn, your control to add is ctrl:

// Creation of the JScrollPane: Make the view a panel, having a BoxLayout manager for the Y-axis
JPanel view = new JPanel( );
view.setLayout( new BoxLayout( view, BoxLayout.Y_AXIS ) );
JScrollPane spn = new JScrollPane( view );

// The component you wish to add to the JScrollPane
Component ctrl = ...;

// Set the alignment (there's also RIGHT_ALIGNMENT and CENTER_ALIGNMENT)
ctrl.setAlignmentX( Component.LEFT_ALIGNMENT );

// Adding the component to the JScrollPane
JPanel pnl = (JPanel) spn.getViewport( ).getView( );
pnl.add( ctrl );
pnl.revalidate( );
pnl.repaint( );
spn.revalidate( );
Comments