gpt4 book ai didi

java - JMenuBar不会出现在JFrame中

转载 作者:行者123 更新时间:2023-12-02 05:36:28 25 4
gpt4 key购买 nike

我知道这个问题已经被问了很多次,但似乎没有什么对我有用,所以我会再问一次。我试图让一个带有 JMenu 的 JMenuBar 显示在扩展 JFrame 的 Window 类中。这是我的相关代码:

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

最佳答案

杀...

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

关于java - JMenuBar不会出现在JFrame中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24923403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com