Java Swing FlowLayout Alignments

I am new to Java and I am trying to create a GUI application with some shortcuts, buttons and text fields. The program is pretty simple, and I just wanted to use the default layout, which is FlowLayout. I managed to put everything and everything in order, but the only thing that does not seem to work is alignment. I want to place buttons and text fields with certain alignments, but whenever I set the alignment, it moves the text inside the whole object, not the object itself. For example, I wrote:

 button.setHorizontalAlignment(JButton.RIGHT);

but it looks like it aligns the text inside the button, not the button itself. Is there a way to align the button itself, and not the text inside?

I know that the alignment element may be easier with some other type of layout (e.g. BoxLayout), but I just want to use FlowLayout for this if it is not possible to coordinate using FlowLayout (which I don’t think so).

Thanks in advance.

+5
source share
3 answers

See the constructor FlowLayout(int align).

Creates a new one FlowLayoutwith the specified alignment and horizontal and vertical gap of 5 units by default. Meaning alignment argument must be one of FlowLayout.LEFT, FlowLayout.RIGHT, FlowLayout.CENTER, FlowLayout.LEADINGor FlowLayout.TRAILING.

It seems you are after FlowLayout.RIGHT, as shown in this answer (combo and checkbox at the top).

Jaqap.png

+13
source

setHorizontalAlignment AbstractButton , . AbstractButton SwingConstants.CENTER.

... .. - ....

p.add(button, BorderLayout.SOUTH);//using `BorderLayout`

. , .

+2

, FlowLayout.

:

  • MigLayout, . MigLayout , .
  • If you want to align subcomponents, it often also makes sense to put them inside a nested JPanel. Then you can use a separate layout for this JPanel (perhaps BorderLayout?), Which will allow you to get the exact alignment you want.
+2
source

All Articles