JMenuBar不会出现在JFrame中

时间:2014-07-24 00:48:00

标签: java swing jframe jmenu jmenubar

我知道这个问题已经被问了很多,但似乎没有什么对我有用,所以我再问一遍。我尝试使用JMenu来获取JMenuBar,以便在我的Window类中显示,该类扩展了JFrame。这是我的相关代码:

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
    }
}

1 个答案:

答案 0 :(得分:2)

杀死...

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

这阻止了事件调度线程,使系统无法绘制任何东西......

也...

menu.setVisible(true);
menuBar.setVisible(true);

默认情况下,Swing组件是可见的,所以上面的内容毫无意义,我知道,你在抓碎屑,但是你应该注意这个问题非常少

enter image description here

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();
                }
            }
        });
    }
}