Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

swing - Java JMenuBar is spread over the whole width of the window

I want to create a very simple JMenuBar with 2 clickable JMenuItems with the following code:

JFrame window = new JFrame();
JMenuBar bar = new JMenuBar();
JMenuItem open = new JMenuItem("Open"), reload = new JMenuItem("Reload");
bar.add(open);
bar.add(reload);
window.setJMenuBar(bar);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.pack();
window.setVisible(true);

However, the two Items have a huge space in between them and I have no idea where this is coming from: enter image description here

I would expect the "Reload" item to be right next to the "Open" item.
This is the very first part of the code that runs (with a breakpoint immediately after), so nothing else can interfere with it.
Is there something 'obvious' I am missing?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The point is that I don't want to create Menus,

Well, a menu is designed to be clicked on and then display a popup with menu items.

If you want the ability to click on a button directly, then use a JToolBar. Read the section from the Swing tutorial on How to use Toolbars for more information and working examples.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...