Mitchell Conrad
Mitchell Conrad

Reputation: 51

frame.add(game); not working

I'm new to java and have decided to make a simple game. I found this tutorial https://www.youtube.com/watch?v=iH1xpfOBN6M&list=ELmvNdIhZY1t4 and this is my code:

package com.MyGame.Display;

import java.awt.Canvas;
import javax.swing.JFrame;

public class Display {

    private static final long serialVersionUID = 1L;
    public static final int WIDTH = 800;
    public static final int HEIGHT = 600;
    public static final String TITLE = "MyGame Version Pre-Alpha 0.1";

    public static void main(String args[]){

        Display game = new Display();
        JFrame frame = new JFrame();
        frame.add(game);
        frame.pack();
        frame.setTitle(TITLE);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(WIDTH,HEIGHT);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setVisible(true);
    }
}

There seems to be an error with the frame.add(game); code but nothing that I do works. I've tried everything. The error is "The method add(Component) in the type Container is not applicable for the arguments ". It should be a quick fix so I hope you can help!

Upvotes: 0

Views: 1082

Answers (3)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

You're trying to add a Display object into a JFrame, but what is this Display object? It doesn't extend any Swing components such as a JPanel, and so you really can't add it to a JFrame since doing so has no meaning, makes no sense.

Consider:

  • having Display extend JPanel
  • Reading/studying the Swing tutorials. You can find links to the Swing tutorials and other Swing resources here: Swing Info.
  • Also go through the basic Java tutorials and learn to use and use frequently the Java API.

Upvotes: 3

Love Lindeborg
Love Lindeborg

Reputation: 13

I may be late now but:

public class Display extends Canvas { <--here

}

I followed the same tutorial and got the same problem but solved it with this

Upvotes: 0

ArcaneEnforcer
ArcaneEnforcer

Reputation: 124

You need Display to extend (IN TERMS OF THAT TUTORIAL)Canvas. You cant add random things to JFrames in Java.

Better to do something like this

 public class Game extends JFrame {

   public Game() {

       initUI();
   }  

   private void initUI() {


       pack();
       repaint();

       setResizable(false);
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       setLocationRelativeTo(null);
   }

   public static void main(String[] args) {
       EventQueue.invokeLater(new Runnable() {
           @Override
           public void run() {
               Game g = new Game();
               g.setVisible(true);
               running = true;
               Update update = new Update();
           }
       });

   }

Upvotes: 0

Related Questions