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

1r0*_*n1k 3 java icons swing alignment jbutton

我正在尝试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();
    }
 }

}
Run Code Online (Sandbox Code Playgroud)

有没有人知道如何在左端使用图标并在图标和文本之间留出一些空格(或文本右对齐)?