Setting JButton text to align to the left?

Halfwarr picture Halfwarr · Feb 19, 2012 · Viewed 33k times · Source

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?

Answer

Vincent Ramdhanie picture Vincent Ramdhanie · Feb 19, 2012

You need to use

  setHorizontalAlignment(SwingConstants.LEFT)

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