如何组织代码轻松构建小程序和应用程序? [英] How to organize code to build applet and application easily?

查看:21
本文介绍了如何组织代码轻松构建小程序和应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在用 Java 实现一个客户端作为 Swing 的应用程序.但是现在我想从中构建 Applet.什么是重新设计/重构以便能够轻松构建它们并保持干燥的最佳方法.

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.

这是一段简短的代码提取,其中包含 main()

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
    }

所以我把这个文件作为一个单独的文件复制,从JApplet扩展它并将main改为init,这样它就可以运行了,但当然它是丑陋的,因为大部分代码只是复制粘贴的.

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

并将所有初始化逻辑移动到App

and to move all initialization logic to App

推荐答案

将大部分应用程序移除到不依赖于顶级容器的类组中.

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.

然后,您将需要一个用于桌面入口点的main"类和一个applet"类.这将简单地构建应用程序主界面并将其附加到屏幕容器.

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.

这就是为什么我们建议您不要直接从顶级容器覆盖,而是从简单容器(例如 JPanel

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

这篇关于如何组织代码轻松构建小程序和应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆