Home > other >  JFrame Java. Window not showing
JFrame Java. Window not showing

Time:02-18

Heey, I tried to copy a game code from a tutorial for a simple game and was just creating the environment for it. The problem now is I copied the code and also checked it several times and it just does not show. The code itself does not seem to have any errors and the console only shows some "terminated Game [Java Application] C:/Users...." which I don´t really understand.


package com.tutorial.main;

import java.awt.Canvas;

public class Game extends Canvas implements Runnable{
    
    private static final long serialVersionUID = 1550691097823471818L;
    
    public static final int WIDTH = 640, HEIGTH = WIDTH / 12 * 9;
    
    public Game() {
        new Window(WIDTH, HEIGTH, "Let´s build a Game!", this);
    }
    
    public synchronized void start() {
        
    }
    public void run() {
        
    }
    
    public static void main(String []args ) {

        }
    }

and the class


package com.tutorial.main;

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

public class Window extends Canvas{

    enter code here
    private static final long serialVersionUID = -240840600533728354L;
    
    public Window(int width, int height, String title, Game game) {
        JFrame frame = new JFrame();
        
        frame.setPreferredSize(new Dimension(width, height));
        frame.setMinimumSize(new Dimension(width, height));
        frame.setMaximumSize(new Dimension(width, height));

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setLocation(null);
        frame.add(game);
        frame.setVisible(true);
        game.start();
    }

}

CodePudding user response:

Just create an object for the class Game.

new Game();

Also the frame.setLocation(null); throws an error.

CodePudding user response:

That's why it is not a good idea to copy paste code blindly. You have two classes. A Game class which I assume will handle the game logic and a Window function which will handle the GUI related. In your Game class, you have the main function, which is the function java will look for when you start the program. But it's empty. That's why your program terminates. You should define an instance of the Game class, which in turn will trigger the Game constructor and your window will be initiated and then call whatever method you need.

CodePudding user response:

Add a new Game(); in the main method. Instead of frame.setLocation(null); do `frame.setRelativeLocation(null);

CodePudding user response:

It works now, thanks guys! The problem was not the setLocationRelativetoNull(null); but that I forgot to create an object of the game class in the main method. And the Title was not being used because I created the Jframe frame = new Jframe(); instead of Jframe frame = new Jframe(title);

  • Related