2016-11-11 70 views
1

我試圖在JToolBar中對齊JToggleButtons。我想要按鈕左對齊。我的代碼如下:JToolbar:JToggleButton對齊

JToolBar toolbar = new JToolBar(); 
toolbar.setLayout(new FlowLayout()); 
toolbar.setAlignmentX(FlowLayout.LEFT); 
toolbar.add(new JToggleButton("Test")); 
toolbar.add(new JToggleButton("Test2")); 
toolbar.add(new JToggleButton("Test3")); 
toolbar.add(new JToggleButton("Test with a long name")); 

這就是結果的樣子。 my JToolBar

另外,當停靠在左側時,它看起來像這樣。理想情況下,我希望按鈕垂直堆疊在一起(並仍然保持與左側對齊)。有小費嗎?

JToolBar docked to the left

理想的結果應該是這樣的: Ideal results - left aligned buttons, and stacked when the toolbar is docked to the left

回答

1

我想要的按鈕靠左對齊,

這是一個JToolBar中的默認行爲。無需與佈局管理員一起玩。

我想要的按鈕上互相疊加垂直

再次,這是默認的佈局管理器使用時的默認行爲。

有關更多信息和工作示例,請參閱How to Use Tool Bars上的Swing教程部分。

+0

嗯,謝謝你的迴應,但這仍然不能回答我的問題(也許我措辭怪異?)。我想將按鈕移動到如下圖所示的位置(例如,按鈕對齊左側的工具欄,並在停靠左側時豎直堆疊):http://puu.sh/seMS7/4e3347c203.png –

+0

@JoeBalin,你是否從本教程下載了演示代碼並進行了測試? – camickr

+0

我回去複製粘貼示例代碼。基本上,我已經在程序的前面初始化了ButtonGroup,所以我只需要遍歷按鈕組並將每個按鈕添加到工具欄。但是,通過定義一個新的ButtonGroup,然後將這些按鈕添加回來,它會奇蹟般地修復它,並且它們對齊正確。奇怪的。 –