MrP*_*PNG 1 java icons swing alignment jbutton
基本上,我正在尝试制作一个文本左侧对齐的按钮(所以我正在使用setHorizontalAlignment(SwingConstants.LEFT))
按钮的右边框上的图像,远离文本.
我已经尝试了setHorizontalTextAlignment(SwingConstants.LEFT)
,但这只是使文本与图标的左侧相关,这不是我想要的,因为我需要将图标与其隔离.
另外,我不能制作任何固定的间距,因为它是一系列具有不同尺寸的不同文本的按钮.
我不能制作任何固定的间距,因为它是一系列具有不同尺寸的不同文本的按钮.
您可以使用以下代码动态更改间距:
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);
Run Code Online (Sandbox Code Playgroud)