Java JToolbar插入左侧和右侧
我创建了一个JToolbar组件并将其添加到框架中。 工具栏使用边框布局 我在工具栏上添加了三个按钮,它们显示得很好,只是我想将它们添加到工具栏的右侧。右对齐 然后,每当我向工具栏添加其他按钮时,我都希望它们添加到左侧 我该怎么做 我做了以下操作,但结果是按钮出现在彼此的顶部:S右侧的三个按钮都在彼此的上方,左侧的两个按钮都在彼此的上方Java JToolbar插入左侧和右侧,java,swing,jtoolbar,Java,Swing,Jtoolbar,我创建了一个JToolbar组件并将其添加到框架中。 工具栏使用边框布局 我在工具栏上添加了三个按钮,它们显示得很好,只是我想将它们添加到工具栏的右侧。右对齐 然后,每当我向工具栏添加其他按钮时,我都希望它们添加到左侧 我该怎么做 我做了以下操作,但结果是按钮出现在彼此的顶部:S右侧的三个按钮都在彼此的上方,左侧的两个按钮都在彼此的上方 public class Toolbar extends JToolBar { private JToggleButton Screenshot =
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()
方法将新按钮添加到面板,而不是直接添加到工具栏。每个有类似问题的人都可以查看。它提供了一个使用水平粘合的非常简单的示例,它省去了更改默认布局的必要性
以下是从上述链接复制的代码行:
JToolBar toolbar = new JToolBar();
// These buttons will be left aligned by default
toolbar.add(new JButton("Open"));
toolbar.add(new JButton("Save"));
// add some glue so subsequent items are pushed to the right
toolbar.add(Box.createHorizontalGlue());
// This Help button will be right aligned
toolbar.add(new JButton("Help"));
如果是一个示例代码,您的代码会更有用,然后我们可以运行它并立即看到您的问题。嗯,但是如果我想从右到左而不是从左到右呢。我问这个问题的原因是因为我想要上面的三个按钮在右边,然后在左边。你为什么不能把它们添加到你创建胶水的地方呢?因为addButtonLeft会动态创建它们。