JButton: Icon left-aligned, text right-aligned
Solution 1
Have a look at JButton#setHorizontalTextPosition and JButton#setHorizontalAlignment
And just because it might be helpful JButton#setVerticalTextPosition and JButton#setVerticalAlignment
Solution 2
Try to set margin to smaller then default values in button properties, and then set iconTextGap to have it rightmost horizontal position
Solution 3
Classic solution to this problem to use additional panel that has a layout that alows to align components such as BorderLayout
. Then put the button and label inside it with the corresponding layout alignment. Pack or validate the frame.
1r0n1k
Student at the University of Applied Sciences and Arts of Northwestern Switzerland. Experience in Java, PHP, MySQL/MSSQL, HTML, Hudson, C/C++. Special Interest in Usability, UX and GUI-Design.
Updated on June 04, 2022Comments
-
1r0n1k almost 2 years
I'm trying to create a
JButton
with an icon and some text in it. My problem is that I want the icon to be left-aligned and the text right-aligned (It isn't necessary to be right-aligned, but I don't want the text to stick to the icon).Not being able to do this on my own, I tried a slightly different solution. I used the
iconTextGap
to create some space between the icon and the text, what worked fine in principle, but when I create multiple buttons, which all have the width of the widest, the icon isn't at the very left anymore (except in the button with the longest text).I included a code to demonstrate that:
import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.io.File; import java.net.MalformedURLException; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingConstants; public class Main{ private JFrame frame; private JPanel buttonPanel; private GridBagConstraints constraints; public Main() throws MalformedURLException{ frame = new JFrame(); buttonPanel = new JPanel(); frame.add(buttonPanel); buttonPanel.setLayout(new GridBagLayout()); constraints = new GridBagConstraints(); constraints.insets = new Insets(5, 5, 3, 5); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 0; constraints.gridy = 0; String[] text = { "some Text", "this text is longer" }; for (int i = 0; i < text.length; i++) { JButton button= new JButton(text[i], new ImageIcon(new File("icon.png").toURI().toURL())); button.setAlignmentX(SwingConstants.WEST); button.setIconTextGap(30); button.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 10)); buttonPanel.add(button, constraints); constraints.gridy++; } frame.pack(); frame.setVisible(true); } public static void main(String[] args){ try { new Main(); } catch (Exception e) { e.printStackTrace(); } } }
Does anyone know of a way to have the icon at the left end and have some space between the icon and the text (or the text right-aligned)?