Aligning components in a gui window

I have a window that looks like window1, and I would like it to look like window2:

enter image description here

This is my code:

String q = "Have you used GUI before?"; JLabel textLabel2 = new JLabel( "<html><div style=\"text-align: center;\">" + q + "</html>", SwingConstants.CENTER); add(textLabel2, BorderLayout.NORTH); JPanel radioPanel = new JPanel(); add(radioPanel, BorderLayout.CENTER); JPanel btnPanel = new JPanel(); add(btnPanel, BorderLayout.SOUTH); 

For a radio button, I tried to use GridLayout, but it broke the position of "Yes" and "No". And for the back and next buttons, horizontal alignment does not work ( btnPanel.setAlignmentX(RIGHT_ALIGNMENT); ), apparently. Any solutions would be much appreciated, I was stuck for too long. Thanks

- EDIT -
This works fine:

 btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.LINE_AXIS)); btnPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); btnPanel.add(Box.createHorizontalGlue()); 

therefore, the problem with the buttons is resolved. However, it is still impossible to fix the radio buttons.

- EDIT 2 -
Fixed background for buttons using setOpaque(false);

+4
source share
2 answers

What do you mean by this “broke” the position of “yes” and “no”, since the GridLayout should work fine. I would give it 1 column and 2 (or 0 for a variable number) rows through new GridLayout(0, 1) . Verify that its opaque property is set to false by running radioPanel.setOpaque(false); . Thus, it will show the background color of the container in which it is located. You may also have to make JRadioButtons opaque, I'm not sure.

Your btnPanel can use BoxLayout and use Box.createGlue () to push the buttons on the right side.

Most importantly, if you haven’t already done so, read the Swing Layout Managers tutorials that you can find here .

+4
source

A few things you can do about this. You need to change your LayoutManager. This is not a big task for BorderLayout. You can do nested BoxLayouts. A vertical box with a vertical fixed stand, height, label, vertical fixed stand, yes radio, vertical fixed stand, no radio, vertical glue and the last keypad. Then use your editing on the button bar to align them horizontally. This is one option, but nesting panels is annoying.

Another option: get a TableLayout and find out how to use it. TableLayout is one of the best LayoutManagers. It is easy to use, solidly tested, and it launched Swing again. You will never again use the GridBagLayout.

http://java.sun.com/products/jfc/tsc/articles/tablelayout/

The ultimate option is to use the new GroupLayout. I am not very familiar with this, but it looks pretty easy. And it does not take as much code or nesting of unnecessary panels as Box.

+4
source

All Articles