简体   繁体   中英

Running Java Code as a Java Application and not an Applet

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.

The bad news begins with the fact that an ACM based GraphicsProgram extends Applet / JApplet .

在此处输入图像描述

That's bad news because the Java Plug-In technology needed to run applets and web-start apps was deprecated around Java 9 & removed from the Java API.


To do custom painting as suggested in the example, I'd extend a Swing-based JPanel and change the paint method, then display it in a JFrame .

Anything ACM based is no longer functional.

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);

        }
    }
}

你需要一个主要的方法,哟。

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

Try the following

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

You could try to run it in Applet Runner for Eclipse plug-in. It's a free plug-in to run applets in the IDE.

Full disclosure, I'm the developer of the plug-in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM