質問

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.

役に立ちましたか?

解決 2

  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( );

他のヒント

My problem is the original panel runs out of space and I cant see the new panels i'm adding. Tried using scrollpane for vertical scrolling with no success.

A FlowLayout adds components horizontally, not vertically so you will never see vertical scrollbars. Instead you can try the Wrap Layout.

The basic code to create the scrollpane would be:

JPanel main = new JPanel( new WrapLayout() );
JScrollPane scrollPane = new JScrollPane( main );
frame.add(scrollPane);

Then when you dynamically add components to the main panel you would do:

main.add(...);
main.revalidate();
main.repaint(); // sometimes needed
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top