Search code examples
javaswingiconsalignmentjbutton

How to create a JButton with text on the button left and the icon separated from it on the button right


Basically, I'm trying to make a button that has the text aligned to the left (so I'm using setHorizontalAlignment(SwingConstants.LEFT)) and the image on the right border of the button, far from the text.

I already tried setHorizontalTextAlignment(SwingConstants.LEFT), but that just makes the text go relativity to the left of the icon, which is not exactly what I want, since I needed the icon to be secluded from it.

Also, I can't make any fixed spacing because it's a series of buttons with different texts with different sizes.


Solution

  • I can't make any fixed spacing because it's a series of buttons with different texts with different sizes.

    You can dynamically change the spacing with code like:

    JButton button = new JButton("Text on left:")
    {
        @Override
        public void doLayout()
        {
            super.doLayout();
    
            int preferredWidth = getPreferredSize().width;
            int actualWidth = getSize().width;
    
            if (actualWidth != preferredWidth)
            {
                int gap = getIconTextGap() + actualWidth - preferredWidth;
                gap = Math.max(gap, UIManager.getInt("Button.iconTextGap"));
                setIconTextGap(gap);
            }
        }
    };
    button.setIcon( new ImageIcon("copy16.gif") );
    button.setHorizontalTextPosition(SwingConstants.LEADING);