質問

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.

役に立ちましたか?

解決

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).

他のヒント

I don't think you can do this with a FlowLayout alone.

My suggestions would be:

  • Consider switching to MigLayout which is a much more powerful layout mechanism. MigLayout basically lets you position you components within a flexible grid, and you can set the specific alignment of a component within each grid cell.
  • When you want alignment of subcomponents, it also often makes sense to put them inside a nested JPanel. You can then use a separate layout for this JPanel (BorderLayout perhaps?) which will enable you to get the exact alignment that you want.

setHorizontalAlignment of AbstractButton sets the horizontal alignment of the icon and text not the position of the button. AbstractButton's default is SwingConstants.CENTER.

If you want to align the button..set the position while adding it to the panel or frame..something like this....

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

Flow layouts are typically used to arrange buttons in a panel. It will arrange buttons left to right until no more buttons fit on the same line.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top