Bra*_*don 2 java swing jtoolbar
我创建了一个JToolbar组件并将其添加到Frame中.工具栏使用BorderLayout.
我在工具栏中添加了三个按钮,它们显示得很好,除了我希望它们被添加到工具栏的右侧.右对齐.
然后每当我向工具栏添加其他按钮时,我希望它们添加到左侧.
我怎样才能做到这一点?
我做了以下但是会发生的事情是按钮出现在彼此的顶部:S右边的三个都在彼此之间,而左边的两个都在彼此之间..
public class Toolbar extends JToolBar {
private JToggleButton Screenshot = null;
private JToggleButton UserKeyInput = null;
private JToggleButton UserMouseInput = null;
private CardPanel cardPanel = null;
public Toolbar() {
setFloatable(false);
setRollover(true);
setLayout(new BorderLayout());
//I want to add these three to the right side of my toolbar.. Right align them :l
Screenshot = new JToggleButton(new ImageIcon());
UserKeyInput = new JToggleButton(new ImageIcon());
UserMouseInput = new JToggleButton(new ImageIcon());
cardPanel = new CardPanel();
add(Screenshot, BorderLayout.EAST);
add(UserKeyInput, BorderLayout.EAST);
add(UserMouseInput, BorderLayout.EAST);
addListeners();
}
public void addButtonLeft() {
JButton Tab = new JButton("Game");
Tab.setFocusable(false);
Tab.setSize(50, 25);
Tab.setActionCommand(String.valueOf(Global.getApplet().getCanvas().getClass().hashCode()));
Tab.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cardPanel.jumpTo(Integer.valueOf(e.getActionCommand()));
}
});
add(Tab, BorderLayout.WEST);
}
}
Run Code Online (Sandbox Code Playgroud)
dre*_*ore 12
他们在彼此之上,因为你把它们全部放在同一个地方 - 即BorderLayout.EAST和BorderLayout.WEST.
您可以在不使用BorderLayout但使用JToolBar默认布局的情况下实现所需效果.
add(tab);
// add other elements you want on the left side
add(Box.createHorizontalGlue());
add(Screenshot);
add(UserKeyInput);
add(UserMouseInput);
//everything added after you place the HorizontalGlue will appear on the right side
Run Code Online (Sandbox Code Playgroud)
编辑(根据您的评论):
创建一个新的JPanel并在粘贴之前将其添加到工具栏:
JPanel leftPanel = new JPanel();
add(leftPanel);
add(Box.createHorizontalGlue());
add(Screenshot);
add(UserKeyInput);
add(UserMouseInput);
Run Code Online (Sandbox Code Playgroud)
然后让您的addButtonLeft()方法向面板添加新按钮,而不是直接添加到工具栏.