组合框选择不会在新窗口中加载/初始化类



在底部查看更新!!

几天来我一直在想怎么做,但到目前为止我还没有运气。

基本上我想做的是有一个组合框,当一个选项被选中加载一个applet,并传递一个值给applet 下面是ComboBox类的代码,它应该在一个新窗口中打开另一个类。另一个类是applet的主类。它们都在同一个项目中,但在不同的包中。我知道剩下的代码没有任何错误。

 //where I evaluate the selection and then open SteadyStateFusionDemo
 // more selections just showing one code block
      combo.addItemListener(new ItemListener(){
      public void itemStateChanged(ItemEvent ie){
          String str = (String)combo.getSelectedItem();
               if (str.equals("NSTX")) {
                   machine = "A";
                   JFrame frame = new JFrame ("MyPanel2");
                   frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
                   SteadyStateFusionDemo d = new SteadyStateFusionDemo();
                   frame.getContentPane().add (new SteadyStateFusionDemo());
                   d.init();
                   frame.pack();
                   frame.setVisible (true);

覆盖这里的所有内容是SteadyStateFusionDemo的init()方法的开始以及类中的主方法。太多的代码,否则发布。在init方法之前有几个不同的private。

    //method that initializes Applet or SteadyStateFusionDemo class       
    public void init() {
    //main method of the SteadyStateFusionDemo class
     public static void main (String[] args) {
          JFrame frame = new JFrame ("MyPanel");
          frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add (new SteadyStateFusionDemo());
          frame.pack();
          frame.setVisible (true);

我做错了什么?为什么我的课没上完?

UPDATED:更改代码,使JFrame打开,然后JApplet在其中加载。我已经在一个测试Java applet中成功地做到了这一点,但由于一些奇怪的原因,它无法与这个applet一起工作。我甚至以类似的方式设置了测试(其代码实际上是相同的,除了不同的类名,当然还有一个非常非常短的init()方法)。谁能帮我弄清楚为什么这不起作用?此外,如果我删除引用SteadyStateFusionDemo的行,JFrame将打开,但一旦我引用它将不起作用。为什么会发生这种情况?

UPDATE:
根据您的反馈,您似乎正在努力实现以下目标:
在桌面应用程序(即JFrame)中使用现有Applet (在这里找到)的代码。


将Applet转换为桌面应用程序是一项"可承担"的任务,其复杂性取决于Applet使用了多少"特定于Applet"的东西。它可以像创建JFrame和添加myFrame.setContentPane(new myApplet().getContentPane());一样简单,也可以像……地狱一样复杂。本教程可能是一个很好的开始。


看了手头的Applet之后,转换它似乎相当容易。唯一复杂的因素是使用Applet的方法getCodeBase()getImage(URL)(在代码的某个地方)。这两种方法导致NullPointerException,如果Applet没有部署为…Applet。

因此,您可以做的是重写这两个方法以返回预期的值(没有异常)。代码可能像这样:

/* Import the necessary Applet entry-point */
import ssfd.SteadyStateFusionDemo;
/* Subclass SSFD to override "problematic" methods */
SteadyStateFusionDemo ssfd = new SteadyStateFusionDemo() {
    @Override
    public URL getCodeBase() {
        /* We don't care about the code-base any more */
        return null;
    }
    @Override
    public Image getImage(URL codeBase, String imgPath) {
        /* Load and return the specified image */
        return Toolkit.getDefaultToolkit().getImage(
                this.getClass().getResource("/" + imgPath));
    }
};
ssfd.init();
/* Create a JFrame and set the Applet as its ContentPane */
JFrame frame = new JFrame();
frame.setContentPane(ssfd);
/* Configure and show the JFrame */
...

JFrame类示例的完整代码可以在这里找到


当然,你需要让原始Applet中的所有类都可以被你的新类访问(例如,把原始Applet放在你的类路径中)。

最新更新