【问题标题】:Adding a JMenuItem to JMenuBar to create a toggle button in menu将 JMenuItem 添加到 JMenuBar 以在菜单中创建切换按钮
【发布时间】:2015-02-28 17:07:41
【问题描述】:

我想要实现的是:

图像表示我想在应用程序菜单栏 (JMenuBar) 中放置一些按钮,例如 JMenuItem,以允许切换某些操作。所以我写了这样的代码:

        // Start button
        JMenuItem startbut = new JMenuItem();
        startbut.setText("Start");
        startbut.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ToggleAction();
            }
        });
        menuBar1.add(startbut);

但它并没有按预期运行:

尤其是白色背景令人不安,看起来很破旧。

Java GUI 库有数以千计的选项,所以我认为必须有更有效的方法来做到这一点。我该怎么办?

【问题讨论】:

  • 只是一个建议,如果您使用JToolBar 添加JToggleButton 怎么办?我不会过多地使用菜单栏,因为它们是一种单一的组件。
  • 伙计,太好了!它确实有效,我什至喜欢它看起来不像普通的菜单项:!screenshot
  • @dic19 JMenuBar 是 BoxLayout 的容器
  • @mKorbel 你是对的。我在谈论菜单上的一些渲染问题 for example 但当然我们可以直接将切换按钮添加到菜单栏,就像我认为 OP 刚刚所做的那样。

标签: java swing jmenuitem jmenubar


【解决方案1】:

简单总结一下cmets中的讨论,可以在菜单栏添加JToggleButton而不是添加JMenuItem,像这样:

Action toggleAction = new AbstractAction("Start") {
    @Override
    public void actionPerformed(ActionEvent e) {
        AbstractButton button = (AbstractButton)e.getSource();
        if (button.isSelected()) {
            button.setText("Stop");
            // Start the action here
        } else {
            button.setText("Start");
            // Stop the action here
        }
    }
};

JMenuBar menuBar = new JMenuBar();
menuBar.add(new JMenu("Settings"));
menuBar.add(new JToggleButton(toggleAction));

正如@mKorbel 指出的那样,菜单栏是一个容器,因此我们可以向其中添加组件,而不仅仅是JMenu

另一方面,使用JToolBar 代替菜单栏是另一种选择。从最终用户的角度来看,放置在工具栏中的按钮比放置在菜单栏中的按钮更自然,因此可能值得考虑这种方法。这样的事情会成功:

JToolBar toolBar = new JToolBar();
toolBar.add(new JButton("Settings"));
toolBar.add(new JToggleButton(toggleAction)); // Here 'toggleAction' is the same than the previous one

这个 sn-p 会产生类似于菜单栏的结果:

注意

请注意,必须使用适当的setJMenuBar(...) 方法将菜单栏添加到顶级容器(JFrameJDialog)。这与JToolBar 不同,JToolBar 必须像任何其他组件一样添加到内容窗格中。见this related topic

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    相关资源
    最近更新 更多