I've got GridLayout-JPanel. In every cell there is a JLabel with some String. How can I right-align this text in my cells?
Asked
Active
Viewed 6.2k times
3 Answers
23
@Noran In response to your comment on @mre's answer, you could initialize all the JLabels into an array. Then, all you'd have to do is loop through the array and set the alignment that way.
for (JLabel label: arrayOfJLabels) {
label.setHorizontalAlignment(SwingConstants.LEFT);
}

fireshadow52
- 6,298
- 2
- 30
- 46
-
This should be the correct answer. – John R Perry Jun 22 '17 at 14:59
10
A couple JLabel
constructors take horizontal alignment arguments. These constants are inherited from SwingConstants
.

mre
- 43,520
- 33
- 120
- 170
-
Yes, thats right. But let's say I've got 100 JLabels. When I right-align them with constructor, and decide change that to left-align, I'll have to do it one hundred times by hand. Is there a way, to align them all with one move from layout manager level? – Ariel Grabijas Dec 28 '11 at 16:17
-
If you're unwilling to encapsulate such logic, use the [`setAlignmentY`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#setAlignmentY%28float%29) method. That is how a container can set the horizontal alignment of any `JComponent` instance (e.g. a `JLabel`). – mre Dec 28 '11 at 16:18
-
@Noran you can create class or void with parameters that returns JLabel, you can use SwingConstant, JLabel#possition, or by using Html <=3.2 +1 – mKorbel Dec 28 '11 at 16:36
1
I have read your question and I have a suggestion. There are a few methods to fulfill your requirement. Since you didn't mention the exact requirement, I can give you a simple example as I understand it:
//create a JLabel and name it as jLabel2
javax.swing.JLabel jLabel2 = new javax.swing.JLabel();
jLabel2.setText("Dehans Label");
jLabel2.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
Please refer following methods @ JLabel
class in JavaSE API through following links:

Andrew Thompson
- 168,117
- 40
- 217
- 433

Dehan Wjiesekara
- 3,152
- 3
- 32
- 46
-
It is best to link to the latest version of the JavaDocs. I have edited your answer to point to J2SE 7. For tips on getting a link to the latest docs, see [point 2 of advantages](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7090875). – Andrew Thompson Dec 29 '11 at 00:24