Java and layout

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

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

Container1 and its contents

Container2 and its contents

Container3 and its contents

Thanks for the help.

EDIT: I added some part of my code. I'm not sure if I am 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); 
+4
source share
3 answers

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

Here is a 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 ); 

Please note that the layout is set on the frame content panel, and not on the frame directly. If you try to install BoxLayout on a JFrame directly, you will get the error "BoxLayout cannot be shared."

+2
source

Looks like you want a BoxLayout layout manager. This layout manager simplifies vertical stacking of components.

+4
source

The behavior of web page elements is significantly different in what FlowLayout does: show everything in a row (horizontal or vertical) and flow over several lines if there is not enough space. If you want the device to be fixed, use BoxLayout .

But note that if you insert layout managers, things can get a little more complicated. Here's an article that explains it well .

+1
source

Source: https://habr.com/ru/post/1390043/


All Articles