当我尝试向菜单添加菜单项时,菜单栏消失。代码如下:
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class WedgeTextFrame {
public static void main(String[] args){
JFrame f = new JFrame("Menu");
f.setVisible(true);
f.setSize(400,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu tools = new JMenu("Tools");
menubar.add(file);
menubar.add(tools);
f.setJMenuBar(menubar);
}
}
结果
当我在 menubar.add(tools);
之后添加以下行来定义 JMenuItem
并将其添加到 JMenu
中:
JMenuItem exit_item = new JMenuItem("Exit");
tools.add(exit_item);
菜单栏消失。我正在使用 JRE 1.8.0 运行 Eclipse 2019-06
最佳答案
这就是“所有 Swing 应用程序必须在自己的线程上运行”部分的由来。看看initial threads和 the Event Dispatch Thread 。通过调用 SwingUtilities#invokeLater
启动应用程序将解决您的问题。
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame("Menu");
f.setVisible(true);
f.setSize(400, 400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu tools = new JMenu("Tools");
menubar.add(file);
menubar.add(tools);
JMenuItem exit_item = new JMenuItem("Exit");
tools.add(exit_item);
f.setJMenuBar(menubar);
});
}
我还建议您在准备好整个框架后frame.setVisible(true)
:
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame("Menu");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//add stuff to frame
f.setSize(400, 400);
f.setVisible(true); //Here at the end
});
关于java - 将 JMenuItem 添加到 JMenu 会导致菜单栏消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57947553/