java - JToolbar 左右插入

标签 java swing jtoolbar

我创建了一个 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.EASTBorderLayout.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/

相关文章:

java - 使用正则表达式从字符串中捕获所有数字而不拆分

java - JxBrowser - 如何在没有鼠标事件的情况下对 Kiosk 应用程序中的 HTML 按钮单击使用react

java - 如何在 JToolBar 中的两个按钮之间添加间隙?

java - JToolbar不显示背景颜色

java - 雨云:java.lang.ClassCastException:javax.swing.plaf.nimbus.DerivedColor$UIResource 无法转换为 javax.swing.Painter

java - 是否有用于在 java 中制作可配置工具栏的小部件

java - 类型推断似乎失败了 vavr 的 Try 对 jOOQ 的 fetchOne() 函数有效

java - 在两台服务器之间同步缓存数据的最佳方式

java - 判断ping是否发送成功

java - 打开文档时将图像的 url 转换为实际图像