views:

31

answers:

2

At the moment I have the following code which works fine.

label = new JLabel(panelLabel,SwingConstants.CENTER);
outputPanel.add(label,BorderLayout.CENTER);

I get the text in the center of the panel (in terms of the left-right position as well as in terms of the top-bottom).

Now I want to set the position to the bottom (and center in terms of "left-right"). I tried to use SOUTH instead of the CENTER in the first line. Compiler does not complains but during the execution i get IllegalArgumentException: HorizontalAlignment. What is that?

+1  A: 

What layout manager did you use for outputPanel ? Did you try

outputPanel.add(label,BorderLayout.PAGE_END);

?

Had you set outputPanel's layout manager to BorderLayout, you would not get this error. There is nothing wrong as far as I can see.

ring bearer
For the outputPanel I use BorderLayout. The "cell" with the text is added to the correct place I just wanted to have the text in the correct position of the cell. But I just realized that I do not know where my "cell" ends and begins. So, my be the text is on the bottom.
Roman
Are you still getting the IllegalArgumentException: HorizontalAlignment exception? If not set border to your label as label.setBorder(LineBorder.createGrayLineBorder());and it will show you where your "cell" ends and begins.
ring bearer
@ring - read again his question, he was using SwingConstants.SOUTH in the **first** line, not in the second.
Gnoupi
@GnoupiGood catch. I was too quick to jump to conclusion.
ring bearer
+3  A: 

The JLabel constructor you are using is JLabel(String label, int horizontalAlignement).

As defined in the javadoc, this int should be only in certain values:

JLabel public JLabel(String text, int horizontalAlignment)
Creates a JLabel instance with the specified text and horizontal alignment. The label is centered vertically in its display area.

Parameters:
text - The text to be displayed by the label.
horizontalAlignment - One of the following constants defined in SwingConstants: LEFT, CENTER, RIGHT, LEADING or TRAILING.

This value sets where your text is aligned, inside the JLabel. You can't use "SOUTH" here, and this is why you get the "InvalidArgument" exception.


If you want to make your text on the bottom of the label, you have to use setVerticalAlignment(int), with Swingconstants.BOTTOM. That supposes that your label is centered and will potentially take a wide height on your panel.

If you use a BorderLayout for this panel, you might want to try to add your label with BorderLayout.SOUTH, as hint for the layout manager. This will stick the label to the bottom part, and it will have a minimal height (the one necessary to display the text). In this case, the vertical alignment of the text doesn't really matter.

Gnoupi