Search code examples
javaswingcanvaswindowreplit

Repl.it Java SWING, the console keeps on ending with it not finding main class, how do I add one?


So this is the ending error I get:

could not find or load main class main caused by java.lang.classnotfoundexception main

This is the code I am using: Main.java

package com.test.main;

import java.awt.Canvas;

public class Main extends Canvas implements Runnable {

    private static final long serialVersionUID = -235234634745643747L;

    public static final int WIDTH = 640, HEIGHT = WIDTH /12 * 9;

    public Game() {
        new Window(WIDTH, HEIGHT, "Test Window", this);
    }

    public synchronized void start() {
    }

    public void run() {
    }

    public static void main(String args[]){
            new Game();
    }
}

Window.java

package com.test.main;

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

public class Window extends Canvas{

    private static final long serialVersionUID = -235234634745643747L;

    public Window(int width, int height, String title, Game game) {
        JFrame frame = new JFrame(title);

        frame.setPreferredSize(new Dimension(width, height));
        frame.setMaximumSize(new Dimension(width, height));
        frame.setMinimumSize(new Dimension(width, height));

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.add(game);
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.setUndecorated(true);
        frame.setVisible(true);
        game.start();
    }
}

So the question is, what am I doing wrong? I don't think that the error is coming from my code, I believe it has to do something with the files (PS: I am using Repl.it on java swing).


Solution

  • As the error says, the method is not defined properly because it's missing the return type. From the existing code it appears you intended to define a constructor because of the call

    new Game();
    

    in the main method. However a constructor must have the same name as the class where it is defined, so you should change its name, like this

    public Main() {
    

    and also update the call in main() to

    new Main();