工具栏插入左侧和右侧

5
我创建了一个JToolbar组件并将其添加到Frame中。 工具栏使用BorderLayout。
我向工具栏添加了三个按钮,它们显示得非常好,但我希望它们被添加到工具栏的右侧。 右对齐。
然后,每当我向工具栏添加其他按钮时,我希望它们添加到左侧。
如何做到这一点?
我尝试了以下方法,但结果是按钮彼此上下堆叠:右侧的三个按钮都在彼此上方,而左侧的两个按钮也在彼此上方。
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);
    }
}

1
如果您提供的代码示例是一个SSCCE,那么我们就可以运行它并立即看到您的问题,这样会更有用。 - Duncan Jones
2个回答

17

它们重叠在一起是因为您将它们全部放置在相同的两个位置上,即BorderLayout.EASTBorderLayout.WEST

您可以通过使用JToolBar的默认布局而不是BorderLayout来实现所需的效果。

 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并将其添加到工具栏中glue之前:
 JPanel leftPanel = new JPanel();
 add(leftPanel);

 add(Box.createHorizontalGlue());

 add(Screenshot);
 add(UserKeyInput);
 add(UserMouseInput);

然后,将您的addButtonLeft()方法添加新按钮到面板中,而非直接添加到工具栏中。


嗯,但如果我想从右到左而不是从左到右怎么办呢?我问这个问题的原因是因为上面的三个按钮我想放在右边,然后在它们之后的所有内容都在左边。 - Brandon
为什么你不能在创建粘合剂的位置上方添加它们? - drew moore
因为 addButtonLeft 是动态创建它们的。 - Brandon

1

如果有类似的问题,可以看看http://helpdesk.objects.com.au/java/right-align-component-in-a-jtoolbar。它提供了一个非常简单的示例,使用水平胶水避免了更改默认布局的必要性。

这些是从上述链接中复制的代码行:

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"));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接