将JButton文本设置为左对齐?

20

我之前有一个JLabel,想让它可以被单击。我发现最简单的方法是将其转换为JButton并使用以下代码。现在它看起来像是JLabel。

button.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.setFocusPainted(false);

这正是我想要的,但文字现在居中对齐。 根据我在其他问题和搜索中所读到的,应该可以解决这个问题。

button.setHorizontalTextPosition( SwingConstants.LEFT );

但是,文本仍然与按钮的中间对齐。有什么办法可以改变这个吗?

2个回答

38

您需要使用

  setHorizontalAlignment(SwingConstants.LEFT)

HorizontalTextPosition指的是文本相对于图标的位置。


10

尝试一下

button.setHorizontalAlignment(SwingConstants.LEFT);

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