1

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

Nikolay Kuznetsov
  • 9,467
  • 12
  • 55
  • 101

1 Answers1

3

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Depends, where's the UI components? You can't rely on Applets being allowed to display frames – MadProgrammer Dec 28 '12 at 20:24
  • Yes, they are in JFrame. Why not possible to use it in Applet? – Nikolay Kuznetsov Dec 29 '12 at 02:22
  • 1
    So, remove all the UI components so that the not depend on any top level container (like `JFrame` or `JApplet`) - use instead, something like `JPanel`. When the program runs, depending how it runs, you would add this panel to the top level container as required – MadProgrammer Dec 29 '12 at 03:38
  • Sorry I previously overlooked this; more [here](http://stackoverflow.com/a/14156217/230513). – trashgod Jan 04 '13 at 11:24