Game类在构造函数中调用窗口类,在JFrame上打印它的内容。
public class Game extends javax.swing.JPanel {
public Game() {
initComponents();
addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
player.keyReleased(e);
}
@Override
public void keyPressed(KeyEvent e) {
player.keyPressed(e);
}
});
setFocusable(true);
new Window(this);
}
public static void main(String args[]) {
new Game();
}
Window类......
public class Window extends JFrame {
public Window(Game game) {
JFrame frame = new JFrame("Final Gunner");
frame.setPreferredSize(new Dimension(800, 600));
frame.setMaximumSize(new Dimension(800, 600));
frame.setMinimumSize(new Dimension(800, 600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.add(game);
frame.setVisible(true);
while (true) {
try {
game.move();
game.repaint();
Thread.sleep(5);
} catch (InterruptedException ex) {
Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
}
}
} }
在另一个名为“GameMenu”的JFrame类中,我通过“new Game();”调用Game类。当单击一个按钮时,它只显示一个空白帧,除了我通过“new Game()”调用Game类之外别无其他;在主方法的另一个类中它会完美运行,为什么会这样呢?