简体   繁体   中英

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.

//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. Is it displayable, prior to being rendered -- no.

  • Don't use Canvas with a JFrame. Use Swing components instead.
  • Understand that components are added to a JFrame's contentPane which is held by its root pane.
  • Read the Swing tutorials for the details on how to code with Swing. You can find them here with the other Java tutorials The Really Big Index .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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