我知道这个问题已经被问了很多,但似乎没有什么对我有效,所以我再问一遍。我正在尝试让一个带有JMenu的JMenuBar出现在我的窗口类中,它扩展了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
}
}发布于 2014-07-24 08:49:26
杀..。
while(true) {
repaint(); //my paint method doesn't touch the JMenuBar or JMenu
}这阻塞了事件分派线程,使得系统无法绘制任何内容……
还有..。
menu.setVisible(true);
menuBar.setVisible(true);Swing组件在缺省情况下是可见的,所以上面的内容是没有意义的,我知道,您只是在抓取面包屑,但您应该注意,很少会出现这种问题

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();
}
}
});
}
}https://stackoverflow.com/questions/24923403
复制相似问题