2017-02-10 75 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

相關問題