Java 杰门努巴赢得';我不会出现在JFrame中
我知道这个问题被问了很多次,但似乎没有什么对我有用,所以我会再问一次。我正试图获得一个带有JMenu的JMenuBar,以显示在扩展JFrame的窗口类中。这是我的相关代码:Java 杰门努巴赢得';我不会出现在JFrame中,java,swing,jframe,jmenu,jmenubar,Java,Swing,Jframe,Jmenu,Jmenubar,我知道这个问题被问了很多次,但似乎没有什么对我有用,所以我会再问一次。我正试图获得一个带有JMenu的JMenuBar,以显示在扩展JFrame的窗口类中。这是我的相关代码: public class Window extends JFrame { //class variables JMenuBar menuBar; JMenu menu; Window() throws IOExcpetion { menuBar = new JMenuBar();
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组件在默认情况下是可见的,所以上面的内容毫无意义,我知道,您在抓碎屑,但是您应该注意,这很少是问题所在
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();
}
}
});
}
}
“//我的绘画方法不接触JMenuBar或JMenu”
——但它“接触”并冻结Swing事件线程(根据Mad的回答——1+)。感谢您的帮助。那么,重申一下,repaint()会杀死swing线程吗?上面的代码通过在不同的线程中创建runnable来处理这个问题?我需要调用paint来不断更新屏幕(这是一个移动游戏,屏幕不断更新)。如何在更新屏幕时保持菜单栏在顶部?我尝试将我的JMenuBar代码移动到我的paint方法中,但这似乎不起作用。不,循环终止了事件调度线程。您不能阻止EDT,这将阻止它处理事件队列,在所有其他与用户相关的事件(如鼠标和键盘事件以及一系列其他事件)中,重新绘制请求是在事件队列中调度的。我的代码确保在事件调度线程Swing(如大多数UI框架)的上下文中创建UI是单线程环境,并且不是线程安全的。这意味着您必须仅从事件调度线程的上下文中更新UI元素。如果您需要对屏幕执行定期更新,则需要使用类似于javax.swing.Timer
,这将允许您设置定期回调(到ActionListener
)这将在EDT的上下文中调用,使其适合用于安全地更新UI的状态。您需要更好地了解并发性,但特别是它与Swing框架的关系,请查看和了解更多详细信息