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?
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.
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.
You need to use
setHorizontalAlignment(SwingConstants.LEFT)
HorizontalTextPosition refers to the position of text in relation to the icon.
Try
button.setHorizontalAlignment(SwingConstants.LEFT);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With