3D-kreativ
3D-kreativ

Reputation: 9319

Java and layout

I want to use JPanels like containers from top to bottom just like DIV tags when creating a web page? If I use BorderLayout, I can have only two (NORTH and SOUTH)?

I want to place different JButtons, JLabels and JTextFields into each JPanels. This is the layout I'm trying to do:

Container1 and it's content

Container2 and it's content

Container3 and it's content

Thanks for help.

EDIT: I added some part of my code beacuse I'm not sure I'm doing it right?

JPanel container1, container2, container3;
container1 = new JPanel();
container2 = new JPanel();
container3 = new JPanel();

container1.setLayout(new BoxLayout(container1, BoxLayout.Y_AXIS));
container2.setLayout(new BoxLayout(container2, BoxLayout.Y_AXIS));
container3.setLayout(new BoxLayout(container3, BoxLayout.Y_AXIS));

// lägg till komponenter till containers
container1.add(button1);
container2.add(button2);
container3.add(button3);

// lägg till containers till fönster
frame.add(container1);
frame.add(container2);
frame.add(container3);

Upvotes: 4

Views: 197

Answers (3)

You can use the GridLayout for this, when you set the number of columns to 1.
There is also the BoxLayout, which should give this effect when you use the PAGE_LAYOUT or Y_AXIS orientations.

Here is some sample code for BoxLayout:

Container container = frame.getContentPane( );
frame.setLayout( new BoxLayout( container, BoxLayout.Y_AXIS ) );

JPanel panel1 = new JPanel( );
panel1.add( new JButton( "Button #1" ) );
frame.add( panel1 );

JPanel panel2 = new JPanel( );
panel2.add( new JLabel("Label #1") );
frame.add( panel2 );

Note that the layout is set on the content pane of the frame, not on the frame directly. If you try to set the BoxLayout on the JFrame directly, you will get a "BoxLayout can't be shared" error.

Upvotes: 2

Michael Borgwardt
Michael Borgwardt

Reputation: 346476

The behaviour of elemts of a webpage is pretty much what FlowLayout does: show everything in a row (horizontal or vertical) and spill over into multiple rows if there is not enough space. If you want the arrangement to be fixed, use BoxLayout.

But note that if you nest layout managers, things can get a bit trickier. Here's an article that explains it well.

Upvotes: 1

mre
mre

Reputation: 44250

Sounds like you want the BoxLayout layout manager. This particular layout manager makes vertically stacking components quite easy.

Upvotes: 4

Related Questions