如何创建一个 JButton,文本位于按钮左侧,图标与按钮右侧分开

How to create a JButton with text on the button left and the icon separated from it on the button right

基本上,我试图制作一个文本左对齐的按钮(所以我使用 setHorizontalAlignment(SwingConstants.LEFT)) 和按钮右边框上的图像,远离文本。

我已经尝试过 setHorizontalTextAlignment(SwingConstants.LEFT),但这只会使文本相对于图标的左侧移动,这并不是我想要的,因为我需要将图标与它隔离开来。

此外,我无法制作任何固定间距,因为它是一系列具有不同大小的不同文本的按钮。

您可以将布局管理器添加到您的按钮。

JButton btn = new JButton();
btn.add(new JLabel(text));
btn.add(new JLabel(img));
btn.setLayout(/*best layout choice here*/);
btn.setPreferredSize(new Dimension(x,y));
btn.setMaximumSize(new Dimension(maxX, minY));
btn.setMinimumSize(new Dimension(minX, minY)); //this one is most important when it comes to layoutmanagers

抱歉,在选择一个好的布局方面我帮不上什么忙 - 但这最终会让你得到你想要的。也许其他人可以评论使用哪个。

I can't make any fixed spacing because it's a series of buttons with different texts with different sizes.

您可以使用如下代码动态更改间距:

JButton button = new JButton("Text on left:")
{
    @Override
    public void doLayout()
    {
        super.doLayout();

        int preferredWidth = getPreferredSize().width;
        int actualWidth = getSize().width;

        if (actualWidth != preferredWidth)
        {
            int gap = getIconTextGap() + actualWidth - preferredWidth;
            gap = Math.max(gap, UIManager.getInt("Button.iconTextGap"));
            setIconTextGap(gap);
        }
    }
};
button.setIcon( new ImageIcon("copy16.gif") );
button.setHorizontalTextPosition(SwingConstants.LEADING);

这是 camickr 允许在 GUI 生成器中进行编辑以及将其放置在动态布局中的答案的衍生版本。我还删除了 UIManager.getInt("Button.iconTextGap"),因此必要时间隙会缩小到 0。

我将其称为 'Justified' 按钮,类似于对齐文本对齐(通过增加 space 个字符的宽度向左和向右拉伸段落)。

public class JustifiedButton extends JButton {
    @Override
    public void doLayout() {
        super.doLayout();

        setIconTextGap(0);
        if (getHorizontalTextPosition() != CENTER) {
            int newGap = getSize().width - getMinimumSize().width;
            if (newGap > 0)
                setIconTextGap(newGap);
        }
    }

    @Override
    public Dimension getMinimumSize() {
        Dimension minimumSize = super.getMinimumSize();

        if (getHorizontalTextPosition() != CENTER)
            minimumSize.width -= getIconTextGap();

        return minimumSize;
    }

    @Override
    public Dimension getPreferredSize() {
        Dimension preferredSize = super.getPreferredSize();

        if (getHorizontalTextPosition() != CENTER)
            preferredSize.width -= getIconTextGap();

        return preferredSize;
    }
}

这还不能完全投入生产,需要进行一些现场测试。如果我发现了什么,我会编辑代码。

[edit] 现在适用于垂直文本对齐。也简化了一点。
[edit2] 同时操纵 getPreferredSize 以与滚动窗格一起玩(否则它会继续增长并且永远不会再次收缩)