javaswingiconsalignmentjbutton

Is there 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)?


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, that worked fine in principle, but when I create multiple buttons, that 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 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)?


Solution

  • Have a look at JButton#setHorizontalTextPosition and JButton#setHorizontalAlignment

    And just because it might be helpful JButton#setVerticalTextPosition and JButton#setVerticalAlignment