2016-11-11 71 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,然后将这些按钮添加回来,它会奇迹般地修复它,并且它们对齐正确。奇怪的。 –