我要实现的是:
该图像表示我想JMenuItem
在应用程序菜单栏(JMenuBar
)中放置一些按钮,例如,以允许切换某些操作。所以我写了这样的代码:
// 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库有成千上万的选择,因此我认为必须有更有效的方法来做到这一点。我该怎么办?
只需在评论中总结讨论,就可以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
该代码段将产生类似于菜单栏的结果:
请注意,必须使用适当的方法将菜单栏添加到顶层容器(JFrame
或JDialog
)setJMenuBar(...)
。这JToolBar
与必须像其他任何组件一样添加到内容窗格中的不同。请参阅此相关主题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句