Java JButton:图标左对齐,文本右对齐

Java JButton:图标左对齐,文本右对齐,java,swing,icons,alignment,jbutton,Java,Swing,Icons,Alignment,Jbutton,我正在尝试创建一个带有图标和一些文本的JButton。我的问题是我希望图标左对齐,文本右对齐(不需要右对齐,但我不希望文本粘在图标上) 由于我自己无法做到这一点,我尝试了一个稍微不同的解决方案。我使用iconTextGap在图标和文本之间创建了一些空间,原则上效果很好,但是当我创建多个按钮时,所有按钮的宽度都是最宽的,图标不再位于最左边(除了文本最长的按钮) 我包含了一个代码来证明: import java.awt.GridBagConstraints; import java.awt.Grid

我正在尝试创建一个带有图标和一些文本的
JButton
。我的问题是我希望图标左对齐,文本右对齐(不需要右对齐,但我不希望文本粘在图标上)

由于我自己无法做到这一点,我尝试了一个稍微不同的解决方案。我使用
iconTextGap
在图标和文本之间创建了一些空间,原则上效果很好,但是当我创建多个按钮时,所有按钮的宽度都是最宽的,图标不再位于最左边(除了文本最长的按钮)

我包含了一个代码来证明:

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

}
导入java.awt.gridbag约束;
导入java.awt.GridBagLayout;
导入java.awt.Insets;
导入java.io.File;
导入java.net.MalformedURLException;
导入javax.swing.BorderFactory;
导入javax.swing.ImageIcon;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.JPanel;
导入javax.swing.SwingConstants;
公共班机{
私有JFrame;
私人JPanel按钮面板;
私有网格约束;
public Main()引发错误的DurLexException{
frame=新的JFrame();
buttonPanel=新的JPanel();
框架。添加(按钮面板);
setLayout(新的GridBagLayout());
约束=新的GridBagConstraints();
constraints.insets=新的insets(5,5,3,5);
constraints.fill=gridbagsconstraints.HORIZONTAL;
constraints.gridx=0;
constraints.gridy=0;
字符串[]text={“某些文本”,“此文本较长”};
for(int i=0;i
是否有人知道如何将图标放在左端,并在图标和文本之间留出一些空间(或文本右对齐)?

查看并


仅仅因为使用额外的面板(其布局允许对齐组件,如
BorderLayout
)可能会有帮助并且是解决此问题的经典解决方案。然后将按钮和标签放入其中,并与相应的布局对齐。打包或验证框架

尝试在按钮属性中将边距设置为小于默认值,
然后将iconTextGap设置为最右边的水平位置

它确实可以使用
setHorizontalAlignment(SwingConstants.LEFT)