Java Swing FlowLayout Alignments

Dennis picture Dennis · Mar 4, 2012 · Viewed 31.8k times · Source

I'm fairly new to Java and I'm trying to create a GUI application with some labels, buttons, and textfields. The program is pretty simple and I just wanted to use a default layout, which is FlowLayout. I managed to place and size everything fine, but the only thing seem to be not working is the alignment. I want to place buttons and textfields with certain alignments, but whenever I set an alignment, it moves the text inside of whatever the object rather than the object itself. For example, I wrote:

 button.setHorizontalAlignment(JButton.RIGHT);

but it seems like it aligns the text inside the button instead of the button itself. Is there any way to align the button itself rather than the text inside of it?

I know the alignment stuff could be easier with some other type of layout (e.g. BoxLayout), but I just want to use the FlowLayout for this one, unless it is impossible to align them using the FlowLayout (which I don't think so).

Thanks in advance.

Answer

Andrew Thompson picture Andrew Thompson · Mar 4, 2012

See the constructor FlowLayout(int align).

Constructs a new FlowLayout with the specified alignment and a default 5-unit horizontal and vertical gap. The value of the alignment argument must be one of FlowLayout.LEFT, FlowLayout.RIGHT, FlowLayout.CENTER, FlowLayout.LEADING, or FlowLayout.TRAILING.

It seems you are after a FlowLayout.RIGHT as seen in this answer (the combo and check box at the top).