Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting JButton text to align to the left?

I previously had a JLabel, that I wanted to be click-able. The easiest way I found to do this was make it a JButton and using the following code. It now looks like a JLabel

button.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.setFocusPainted(false);

Which is exactly what I wanted except the text is now aligned in the middle. Now from what I was able to read on other questions and searching. This should work

button.setHorizontalTextPosition( SwingConstants.LEFT );

Yet, the text still aligns in the middle of the button. Any ideas what I can do to change this?

like image 426
Halfwarr Avatar asked Feb 19 '12 21:02

Halfwarr


People also ask

How do I change the text of a JButton?

By default, we can create a JButton with a text and also can change the text of a JButton by input some text in the text field and click on the button, it will call the actionPerformed() method of ActionListener interface and set an updated text in a button by calling setText(textField.

What is alignment button?

To align text using the alignment buttons:Left-align text: Word's default lines up objects to the left with a ragged right edge. Center text: This centers selected text, numbers, and inline objects. Right-align text: Selected text, numbers, and inline objects are aligned to the right with a ragged left edge.


2 Answers

You need to use

  setHorizontalAlignment(SwingConstants.LEFT)

HorizontalTextPosition refers to the position of text in relation to the icon.

like image 77
Vincent Ramdhanie Avatar answered Oct 12 '22 13:10

Vincent Ramdhanie


Try

button.setHorizontalAlignment(SwingConstants.LEFT);
like image 28
Yanflea Avatar answered Oct 12 '22 14:10

Yanflea