简体   繁体   English

无法将组件添加到JFrame

[英]Cannot add component to JFrame

I read lots of same issues, but still cant fix it. 我读了很多相同的问题,但仍然无法修复它。
My component just dont want to add to JFrame. 我的组件只是不想添加到JFrame。

//Game extends Canvas implements Runnable

public static void main(String[] args) {
    Game game = new Game();
    game.setPreferredSize(new Dimension(SIZE, SIZE));
    JFrame frame = new JFrame("");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());
    for (Component c : frame.getComponents())
        System.out.println(c.getClass().getName() + ": " + c.isVisible() + " " + c.isDisplayable());
    frame.add(game, BorderLayout.CENTER);
    for (Component c : frame.getComponents())
        System.out.println(c.getClass().getName() + ": " + c.isVisible() + " " + c.isDisplayable());
    frame.pack();
    frame.setResizable(false);
    frame.setVisible(true);
    mainFrame = frame;
    game.start();
} 

It outputs 它输出

javax.swing.JRootPane: true false  
javax.swing.JRootPane: true false

Your code is checking if the JFrame's root pane is present -- and it is. 您的代码正在检查JFrame的根窗格是否存在 - 它是否存在。 Is it displayable, prior to being rendered -- no. 它是否可以在渲染之前显示 - 没有。

  • Don't use Canvas with a JFrame. 不要将Canvas与JFrame一起使用。 Use Swing components instead. 请改用Swing组件。
  • Understand that components are added to a JFrame's contentPane which is held by its root pane. 了解组件是否已添加到由其根窗格保存的JFrame的contentPane中。
  • Read the Swing tutorials for the details on how to code with Swing. 阅读Swing教程,了解有关如何使用Swing进行编码的详细信息。 You can find them here with the other Java tutorials The Really Big Index . 您可以在这里找到其他Java教程The Really Big Index

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM