如何使图标和文本在 JButton 上对齐左侧

How to make Icon and Text align Left side on JButton

我只想让文字和图标对齐升降侧 这是代码

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();
}

}

如果我 运行 此代码我将在按钮中心的按钮上获得图标和文本,那么如何使它们位于左侧;

JButton 派生自 AbstractButton,它提供了一种方法 setHorizontalAlignment(int),它应该完全按照您的要求执行。使用例如SwingConstants.LEFTSwingConstants.LEADING 使图标和文本左对齐。 让 JavaDoc 尝试了解更多信息。

要使文本左对齐,请使用 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();
    }
}