Home > Software design >  Running Java Code as a Java Application and not an Applet
Running Java Code as a Java Application and not an Applet

Time:09-25

I'm new to Java and I've been trying to run this code as a Java Application instead of a Java applet and it doesn't work (using Eclipse IDE). When I click run, it doesn't give me the option to run it as a Java Application. How would I fix this?

Here is my code:

import java.awt.Color;

import acm.graphics.GOval;
import acm.graphics.GPoint;
import acm.graphics.GRect;
import acm.program.*;
import acm.graphics.*;

public class Coordinates extends GraphicsProgram {
    public void run() {
        GOval myOval = new GOval(-8, -8, 16, 16);
        myOval.setColor(Color.RED);
        myOval.setFilled(true);
        add(myOval);

    }

}

Here are the options given to me when I click run:

Java_Screenshot

Thank you.

CodePudding user response:

This is just guess work, as we don't have access to acm.* and applets have their defined life cycle, but the intention would be to create a JFrame and add the Coordinates component to it

public class Test {

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

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                Coordinates coordinates = new Coordinates();
                coordinates.init();
                frame.add(coordinates);
                coordinates.start();
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class Coordinates extends GraphicsProgram {

        public void run() {
            GOval myOval = new GOval(-8, -8, 16, 16);
            myOval.setColor(Color.RED);
            myOval.setFilled(true);
            add(myOval);

        }
    }
}

CodePudding user response:

You need a main method, yo.

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

CodePudding user response:

Try the following

    public static void main(String[] args) {
        try {
            SwingUtilities.invokeAndWait(new Coordinates());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • Related