我创建了一个 JToolbar 组件并将其添加到框架中。
工具栏使用 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);
}
}
最佳答案
它们彼此重叠,因为您将它们全部放在相同的两个位置 - 即 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
编辑(根据您的评论):
创建一个新的 JPanel 并将其添加到工具栏之前的胶水:
JPanel leftPanel = new JPanel();
add(leftPanel);
add(Box.createHorizontalGlue());
add(Screenshot);
add(UserKeyInput);
add(UserMouseInput);
然后有你的
addButtonLeft()
方法将新按钮添加到面板,而不是直接添加到工具栏。
关于java - JToolbar 左右插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16230181/