KenigOri
KenigOri

Reputation: 3

Error in JFrame

I saw this video [ 10:00 ] to start create a 2d game in Java and I tried using the code he used in the video and I get error and I don't know how to fix him.

package me.Kenig.game2d;

import java.awt.Canvas;
import java.awt.Dimension;

import javax.swing.JFrame;


public class Game extends Canvas implements Runnable {

    private static final long serialVersionUID = 1L;

    public static final int WIDTH = 160;
    public static final int HEIGHT = WIDTH/12*9;
    public static final int SCALE = 3;
    public static final String NAME = "Game";

    private JFrame frame; // error

    public Game(){
    setMinimumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
    setMaximumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
    setPreferredSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
    }

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // error


    @Override
    public void run() {
        // TODO Auto-generated method stub

    }

}

Upvotes: 0

Views: 2250

Answers (1)

Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31225

1)You never instantiate your JFrame

Try

this.frame = new JFrame();

in your constructor

2)Another problem :

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

is not in the right place : it should be in a method. You should also prefer WindowConstants.EXIT_ON_CLOSE rather than JFrame.EXIT_ON_CLOSE.

3)You should also call frame.pack() to force the frame to adapt its size to fit with the size of its contained elements.

Here is a piece of code :

public Game(){
  JFrame frame = new JFrame();
  frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

  setMinimumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
  setMaximumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));

  //Not really necessary because of frame.pack()
  //setPreferredSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));

  //You should add some elements here
  JPanel panel=new JPanel();
  panel.add(new JTextField(10));

  frame.add(panel);

  //Forces the frame to take the minimum-size to contain its elements
  frame.pack();
  frame.show();
}

You should look at Visual guide to Swing components to see which component exist and how they behave.

You should also have a look at visual guide to layout managers to understand how your components are placed

Good luck :)

Upvotes: 2

Related Questions