Search code examples
javaswingjbutton

How to make Icon and Text align Left side on JButton


I want to make text and icon align lift side only here is the code

import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class LeftSide
{
public LeftSide()
{
JFrame frame = new JFrame("Button");
JPanel panel = new JPanel();
JButton button = new JButton("Submit");
button.setPreferredSize(new Dimension(200, 30));
button.setIcon(new ImageIcon(this.getClass().getResource("submit.gif")));
panel.add(button);
frame.add(panel);
frame.setVisible(true);
}

public static void main(String[] args)
{
new LeftSide();
}

}

if i run this code i will get icon and text on button on center of button so how to make them left side;

enter image description here


Solution

  • To align the text to the left use button.setHorizontalAlignment(SwingConstants.LEFT);

    import java.awt.Dimension;
    import javax.swing.*;
    
    public class LeftSide
    {
        public LeftSide()
        {
            JFrame frame = new JFrame("Button");
            JPanel panel = new JPanel();
            JButton button = new JButton("Submit");
            button.setPreferredSize(new Dimension(200, 30));
            button.setIcon(new ImageIcon(this.getClass().getResource("submit.gif")));
            button.setHorizontalAlignment(SwingConstants.LEFT);
            panel.add(button);
            frame.add(panel);
            frame.setVisible(true);
        }
    
        public static void main(String[] args)
        {
            new LeftSide();
        }
    }