开发 Java Web Start 应用程序

原文: https://docs.oracle.com/javase/tutorial/deployment/webstart/developing.html

使用基于组件的体系结构设计的软件可以轻松地作为 Java Web Start 应用程序进行开发和部署。考虑具有基于 Swing 的图形用户界面(GUI)的 Java Web Start 应用程序的示例。通过基于组件的设计,GUI 可以使用较小的构建块或组件构建。以下常规步骤用于创建应用程序的 GUI:

  • 创建一个MyTopJPanel类,它是JPanel的子类。在MyTopJPanel类的构造器中布置应用程序的 GUI 组件。
  • 创建一个名为MyApplication的类,它是JFrame类的子类。
  • MyApplication类的main方法中,实例化MyTopJPanel类并将其设置为JFrame的内容窗格。

以下部分通过使用动态树演示应用程序更详细地探讨了这些步骤。如果您不熟悉 Swing,请参阅使用 Swing 创建 GUI 以了解有关使用 Swing GUI 组件的更多信息。

单击以下“启动”按钮以启动“动态树演示”应用程序。


Note: If you don’t see the example running, you might need to enable the JavaScript interpreter in your browser so that the Deployment Toolkit script can function properly.


创建 Top JPanel

创建一个作为JPanel子类的类。此顶部JPanel充当所有其他 UI 组件的容器。在以下示例中,DynamicTreePanel类是最顶层的JPanelDynamicTreePanel类的构造器调用其他方法来正确创建和布置 UI 控件。

  1. public class DynamicTreePanel extends JPanel implements ActionListener {
  2. private int newNodeSuffix = 1;
  3. private static String ADD_COMMAND = "add";
  4. private static String REMOVE_COMMAND = "remove";
  5. private static String CLEAR_COMMAND = "clear";
  6. private DynamicTree treePanel;
  7. public DynamicTreePanel() {
  8. super(new BorderLayout());
  9. //Create the components.
  10. treePanel = new DynamicTree();
  11. populateTree(treePanel);
  12. JButton addButton = new JButton("Add");
  13. addButton.setActionCommand(ADD_COMMAND);
  14. addButton.addActionListener(this);
  15. JButton removeButton = new JButton("Remove");
  16. ....
  17. JButton clearButton = new JButton("Clear");
  18. ...
  19. //Lay everything out.
  20. treePanel.setPreferredSize(
  21. new Dimension(300, 150));
  22. add(treePanel, BorderLayout.CENTER);
  23. JPanel panel = new JPanel(new GridLayout(0,3));
  24. panel.add(addButton);
  25. panel.add(removeButton);
  26. panel.add(clearButton);
  27. add(panel, BorderLayout.SOUTH);
  28. }
  29. // ...
  30. }

创建应用程序

对于具有基于 Swing 的 GUI 的应用程序,请创建一个作为javax.swing.JFrame子类的类。

实例化您的 top JPanel类并将其设置为应用程序main方法中JFrame的内容窗格。 DynamicTreeApplication类的main方法调用 AWT 事件调度程序线程中的createGUI方法。

  1. package webstartComponentArch;
  2. import javax.swing.JFrame;
  3. public class DynamicTreeApplication extends JFrame {
  4. public static void main(String [] args) {
  5. DynamicTreeApplication app = new DynamicTreeApplication();
  6. app.createGUI();
  7. }
  8. private void createGUI() {
  9. //Create and set up the content pane.
  10. DynamicTreePanel newContentPane = new DynamicTreePanel();
  11. newContentPane.setOpaque(true);
  12. setContentPane(newContentPane);
  13. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  14. pack();
  15. setVisible(true);
  16. }
  17. }

从最终部署机制中分离核心功能的好处

创建应用程序的另一种方法是删除抽象层(单独的顶部JPanel)并在应用程序的main方法本身中布置所有控件。直接在应用程序的main方法中创建 GUI 的缺点是,如果您稍后选择这样做,将您的功能部署为小程序将更加困难。

在 Dynamic Tree Demo 示例中,核心功能分为DynamicTreePanel类。现在将DynamicTreePanel类放入JApplet并将其作为 applet 部署是微不足道的。

因此,为了保持可移植性并保持部署选项的开放,请遵循本主题中描述的基于组件的设计。

下载动态树演示示例的源代码以进一步试验。