JFrame打开一个JApplet

时间:2011-02-28 22:47:00

标签: java swing japplet

我在java中创建一个程序,JFrame中的JButton将隐藏JFrame并运行JApplet

我做过像

这样的事情
OpenButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e){

                hide();
                JApplet startGame = new MainApplet();

                startGame.init();
                startGame.start();
        }
});
我做错了什么?谢谢

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找的解决方案是主逻辑和顶级容器JFrame和JApplet的单独类。

public class GamePanel extends JPanel { ... your game here ... }
public class GameApplet extends JApplet {  
   private final GamePanel game;
   public GameApplect(GamePanel gamePanel) {
      this.game = game;
      super.add(game);
   }

   public void init() {
      ... applet init ... 
      this.game.init();
   }

   public void start() {
      ... applet start ...
      this.game.start(); 
   }
}

public class GameWindow extends JFrame {  
   private final GamePanel game;
   public GameApplect(GamePanel gamePanel) {
      this.game = game;
      super.add(game);
   }

   public void init() {
      ... frame init ... 
      this.game.init();
   }

   public void start() {
      ... frame start ...
      this.game.start(); 
   }
}

然后,您可以在按钮点击时启动游戏窗口而不是GameApplet。如果您已在applet或窗口内运行,则无需创建单独的GameApplet和GamePanel类。您只需将GamePanel添加到您想要的任何容器中即可。