从其他类调用时未加载 JFrame [英] JFrame not loading when calling from other class

查看:29
本文介绍了从其他类调用时未加载 JFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我有一个主类的游戏.

Basically I have got a game with main class.

    public static void main(String[] args) throws InterruptedException {
    JFrame frame = new JFrame("Mini Tennis");
    Game game = new Game();
    frame.add(game);
    frame.setSize(300, 400);
    frame.setResizable(false);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    while (true) {
        game.move();
        game.repaint();
        Thread.sleep(10);
    }
}

当我直接加载一个类时它工作正常.

When I am loading a class directly it working fine.

但是当我从另一个类调用它时,它不会绘制任何东西.

But when I am calling it from another class, it does not paint anything.

    private void btnGameActionPerformed(java.awt.event.ActionEvent evt) {                                        
  try {
      String[] args = null;
      Game.main(args);
    } catch (InterruptedException ex) {
        Logger.getLogger(DrawerMain.class.getName()).log(Level.SEVERE, null, ex);
    }

}  

几秒钟后,它显示我输了一场比赛.所以基本上游戏正在运行,但我什么也做不了,也什么也没看到.

And after a few seconds it paints that I have lost a game. So basically game is running but I can't do anything and I don't see anything.

推荐答案

你需要将你的 main 代码移动到一个构造函数中,main 应该只在第一类或者你要运行的主"类.

You need to move your main code into a Constructor, main should be only on the 1st class or the "main" class you're going to run.

main 方法是您的应用程序的入口点运行,您不应该像调用任何其他方法一样调用它.

The main method is the entry point for your application to run, you shouldn't be calling it as if it were any other method.

public Game () {
    JFrame frame = new JFrame("Mini Tennis");
    Game game = new Game();
    frame.add(game);
    frame.setSize(300, 400);
    frame.setResizable(false);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    while (true) {
        game.move();
        game.repaint();
        Thread.sleep(10);
    }
}

然后你称之为:

private void btnGameActionPerformed(java.awt.event.ActionEvent evt) {                                        
  try {
      String[] args = null;
      Game game = new Game();
    } catch (InterruptedException ex) {
        Logger.getLogger(DrawerMain.class.getName()).log(Level.SEVERE, null, ex);
    }

}  

您应该阅读更多关于构造函数类和对象

正如其他答案中提到的,Thread.sleep() 会导致您的应用程序冻结,您应该使用 Swing Timer 而不是在另一个线程中处理它,因此您的应用程序不会冻结.

Also as mentioned in other answers, Thread.sleep() will cause your application to freeze, you should use a Swing Timer instead to handle it in another thread, so your application won't freeze.

使用 Thread.sleep(),您的应用程序将在重新绘制之前等待其内部的时间.

With Thread.sleep() your application will wait the time inside it before repainting it.

这篇关于从其他类调用时未加载 JFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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