How to organize code to build applet and applicati

2019-07-30 01:28发布

I have being implementing a client in Java as application with Swing. But now I want to build also Applet from it. What is the best way to redesign/refactor in order to be able to build both of them easily and keeping it DRY.

This is a short extraction of code which has main()

public class Client {
    public static final ScheduledExecutorService SERVICE;
    protected static String host;
    protected static int port;

    static {
         SERVICE = Executors.newSingleThreadScheduledExecutor();
         host =
         port = 
    }

    public static void main(String[] args) {
         //initalize netty

         //create user interface = JFrame in SwingUtilities.invokeLater

         connect();
    }

    public static void connect () {
         //connect using netty
    }

So I copy this file as a separate one, extend it from JApplet and change main to init, so it can be run, but of course it is ugly, because much of code is just copy-pasted.

Is there universal solution how to redesign it?

UPD:

public class Client {
    public static void main (String[] args) {
        App app = new App();
        app.connect();
    }
}

public class Applet extends JApplet {
    public void init () {
        App app = new App();
        app.connect();
    }
}

and to move all initialization logic to App

1条回答
\"骚年 ilove
2楼-- · 2019-07-30 02:03

Remove the bulk of the application to group of classes that do not rely on the top level container.

This means, you can reuse/redeploy the application as you need without chaining your self to a top level container.

You will then need a "main" class for your desktop entry point and a "applet" class. This would simply construct the applications main interface and attach it to a screen container.

This is one of the reasons why we suggest you never override from a top level container directly, but extend your application logic/UI from simple container, like JPanel

查看更多
登录 后发表回答