2017-02-10 73 views
1

我想设置一个JButton,使其图标左对齐,而文本居中。将JButton图标对齐到左侧并保持文本居中

我发现如何让他们中的一个离开,另一个正确,或两者都在相同的设置,但我找不到我在找什么。

当然,我总是可以重新定义油漆方法,但我正在寻找一种更精简的方法来做到这一点。

回答

4

您可以添加layout managerJButton,例如Border Layout将有助于:

您有Icon和一个与文本创建JLabel“点击我”:

JLabel iconLabel = new JLabel(new ImageIcon(this.getClass().getResource("king.png"))); 
JLabel clickMe = new JLabel("Click me", SwingConstants.CENTER); //We give it the center alignment so it stays on the center of the label. 

然后你创建你的JButton,给它边界布局,并在你想要的位置添加你的组件。

button.setLayout(new BorderLayout()); 
button.add(iconLabel, BorderLayout.WEST); 
button.add(clickMe, BorderLayout.CENTER); 

我给每个标签的边界,所以你可以看到每个标签的样子,因为clickMe标签将不会是正确的JButton的中心,但其JLabel中心:

enter image description hereenter image description here

我认为这不是一个大问题,因为它是几乎察觉不到W/O边界

enter image description here

+0

真棒,谢谢!那么在滚动,按下或选择时也会显示不同的内容? –

+0

@VicSeedoubleyew“翻过来”是什么意思?和“显示不同”?点击时,它会像任何'JButton'被按下并具有相同的功能,它所做的只是改变其外观 – Frakcool

+0

@VicSeedoubleyew我得到你的意思与“翻身”,但我仍然没有得到你的意思与“显示不同“你能澄清吗? – Frakcool

相关问题