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

时间:2012-10-23 09:22:06

标签: java swing icons 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();
    }
 }

}

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

3 个答案:

答案 0 :(得分:6)

答案 1 :(得分:1)

此问题的经典解决方案是使用具有布局的其他面板,该布局可以对齐BorderLayout等组件。然后将按钮和标签放在其中,并使用相应的布局对齐方式。打包或验证框架。

答案 2 :(得分:1)

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