简体   繁体   English

JMenu弹出窗口有时仅适用

[英]JMenu popup only sometimes works

I am having issue with JMenu popup. 我在JMenu弹出窗口中遇到问题。 It only sometimes works. 它仅在某些时候有效。 Sometimes I don't get a java popup at all. 有时我根本看不到Java弹出窗口。 Sometimes my File and Edit options are completely missing. 有时我的“文件”和“编辑”选项完全丢失。 This is what my code looks like. 这就是我的代码。

import javax.swing.*;

public class menu {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        JFrame f = new JFrame();
        f.setVisible(true);
        f.setSize(400,400);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLocationRelativeTo(null);

        JMenuBar mb = new JMenuBar();

        JMenu file = new JMenu ("File");
        mb.add(file);
        JMenu edit = new JMenu("Edit");
        mb.add(edit);

        f.setJMenuBar(mb);
    }

}

Call setVisible on the JFrame only after you have initialised the core UI... 仅在初始化核心UI后才在JFrame上调用setVisible

JFrame f = new JFrame();
// Don't call this here...
//f.setVisible(true);
f.setSize(400,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);

JMenuBar mb = new JMenuBar();

JMenu file = new JMenu ("File");
mb.add(file);
JMenu edit = new JMenu("Edit");
mb.add(edit);

f.setJMenuBar(mb);
// Call it here
f.setVisible(true);

Also, make sure you are creating/updating the UI only from within the context of the Event Dispatching Thread, see Initial Threads for more details 另外,请确保仅在事件分发线程的上下文内创建/更新UI,有关更多详细信息,请参见初始线程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM