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

3
我正在尝试创建一个带有图标和文本的 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个回答

6

1
它使用setHorizontalAlignment(SwingConstants.LEFT)运行正常。 - 1r0n1k

2

解决这个问题的经典方法是使用附加面板,该面板具有可以对齐组件(例如BorderLayout)的布局。然后将按钮和标签放在其中,并进行相应的布局对齐。打包或验证框架。


虽然这样做按钮上就没有图标了。 - Adam Keenan
虽然这样做按钮上就没有图标了。 - undefined

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接