2

I've seen some people using the setAlignmentX() and setAlignmentY() methods without a BoxLayout (e.g. when using a BorderLayout and other kinds of layouts).

Is this correct or does it do something at all? I haven't found any documentation explaining the use of alignmentX and alignmentY in JComponents but I have always thought it only affects BoxLayouts.

hexstorm
  • 318
  • 4
  • 14
  • Some Swing layout managers use the setAlignmentX method. Some Swing layout managers use the setHorizontalAlignment method. The same goes for the corresponding Y methods. I use these methods so infrequently that I try one, and if that doesn't work, try the other. Yes, it's confusing. – Gilbert Le Blanc Mar 03 '21 at 14:41
  • @GilbertLeBlanc *Some Swing layout managers use the setHorizontalAlignment method* - This method is NOT used by the layout manager. This is a method of certain Swing components. When a layout manager sets a components size different than the components preferred size, it will allow the component to determine how to paint itself in the space available. – camickr Mar 03 '21 at 16:25
  • 1
    *I have always thought it only affects BoxLayouts* - A layout manager can choose to respect this or not. I have also only used this with a BoxLayout. The value will simply be ignored if the layout manager does not support the property. So you will not get an error if you use it with a BorderLayout, but the code will indeed be confusing. – camickr Mar 03 '21 at 16:30
  • Thank you @camickr!! (and sorry for my late reply). That's the answer I was searching for. Then AlignmentX and AlignmentY are properties of every JComponent and layouts can choose whether to use them or not. – hexstorm Mar 11 '21 at 15:21

1 Answers1

1

As @camickr stated in the comments, alignmentX and alignmentY are attributes of a JComponent, and a layout manager can choose to support/respect them or not.

From the native layout managers, only BoxLayout does support this attributes, so if you try to use them on other layouts (e.g. FlowLayout, BorderLayout...) it won't do anything.

Of course you could create your custom layout manager and choose to respect these attributes or not.

hexstorm
  • 318
  • 4
  • 14