首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JFrame中不会显示JMenuBar

JFrame中不会显示JMenuBar
EN

Stack Overflow用户
提问于 2014-07-24 08:48:00
回答 1查看 1.6K关注 0票数 0

我知道这个问题已经被问了很多,但似乎没有什么对我有效,所以我再问一遍。我正在尝试让一个带有JMenu的JMenuBar出现在我的窗口类中,它扩展了JFrame。下面是我的相关代码:

代码语言:javascript
复制
public class Window extends JFrame {
    //class variables
    JMenuBar menuBar;
    JMenu menu;

    Window() throws IOExcpetion {

    menuBar = new JMenuBar();
    menu = new JMenu("A Menu");
    menuBar.add(menu);
    this.setJMenuBar(menuBar);
    this.add(menuBar); //I've tried with and without this
    menu.setVisible(true);
    menuBar.setVisible(true);

    this.setVisible(true);

    while(true) {
        repaint(); //my paint method doesn't touch the JMenuBar or JMenu
    }
}
EN

回答 1

Stack Overflow用户

发布于 2014-07-24 08:49:26

杀..。

代码语言:javascript
复制
while(true) {
    repaint(); //my paint method doesn't touch the JMenuBar or JMenu
}

这阻塞了事件分派线程,使得系统无法绘制任何内容……

还有..。

代码语言:javascript
复制
menu.setVisible(true);
menuBar.setVisible(true);

Swing组件在缺省情况下是可见的,所以上面的内容是没有意义的,我知道,您只是在抓取面包屑,但您应该注意,很少会出现这种问题

代码语言:javascript
复制
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestWindow extends JFrame {

    //class variables
    JMenuBar menuBar;
    JMenu menu;

    TestWindow() throws IOException {

        menuBar = new JMenuBar();
        menu = new JMenu("A Menu");
        menuBar.add(menu);
        this.setJMenuBar(menuBar);
//        this.add(menuBar); //I've tried with and without this
//        menu.setVisible(true);
//        menuBar.setVisible(true);

        this.setVisible(true);

//        while (true) {
//            repaint(); //my paint method doesn't touch the JMenuBar or JMenu
//        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }

                    TestWindow frame = new TestWindow();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24923403

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档