2015-03-02 45 views
-1

我遇到了一个Java实例化类的问题,实质上它每次都会产生一个新的世界,当程序运行时这有点令人沮丧。 虽然我需要做的是实例化它,然后访问类中的变量。Java - 在循环中实例化一个类

下面的代码:

Background.java

public class Background extends UserView { 
    private BufferedImage bg;  

    private static Game game;  

    public Background(World w, int width, int height) {   
     super(w, width, height); 
     try { 
      bg = ImageIO.read(new File("data/background.jpg")); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    @Override 
    public void paintBackground(Graphics2D g) {   
     super.paintBackground(g); 
     game = new Game(); 
     g.drawImage(bg, 0, 0, this); 
     int level = game.getLevel(); 
     g.drawString("Level: " + level, 25, 25); 
    } 

} 

Game.java

public Game() { 
    // make the world 
    level = 1; 
    world = new Level1(); 
    world.populate(this); 

    // make a view 
    view = new Background(world, 500, 500);  

    // uncomment this to draw a 1-metre grid over the view 
    // view.setGridResolution(1); 

    // display the view in a frame 
    JFrame frame = new JFrame("Save the Princess"); 

    // quit the application when the game window is closed 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setLocationByPlatform(true); 
    // display the world in the window 
    frame.add(view); 
    // don't let the game window be resized 
    frame.setResizable(false); 
    // size the game window to fit the world view 
    frame.pack(); 
    // make the window visible 
    frame.setVisible(true); 
    // get keyboard focus 
    frame.requestFocus(); 
    // give keyboard focus to the frame whenever the mouse enters the view 
    view.addMouseListener(new GiveFocus(frame)); 

    controller = new Controller(world.getPlayer()); 
    frame.addKeyListener(controller); 

    // start! 
    world.start(); 
} 

    /** Run the game. */ 
public static void main(String[] args) { 
    new Game(); 
} 

任何帮助,将不胜感激!谢谢!

+0

循环在哪里? – 2015-03-02 21:58:51

+0

抱歉,由于某种原因,当我运行游戏时,它只是循环运行,已经更新了主类中的代码。 – Henry 2015-03-02 22:00:47

回答

0

那么你可能需要NAD想想类的概念它的依赖,但是这是在你的情况下,最简单和最快的方法来保持游戏的只有一个实例:

public class Background extends UserView { 

    private BufferedImage bg; 

    private static Game game = new Game(); 

    public Background(World w, int width, int height) { 
     super(w, width, height); 
     try { 
      bg = ImageIO.read(new File("data/background.jpg")); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    @Override 
    public void paintBackground(Graphics2D g) { 
     super.paintBackground(g); 
     g.drawImage(bg, 0, 0, this); 
     int level = game.getLevel(); 
     g.drawString("Level: " + level, 25, 25); 
    } 
} 

如果你添加更多的代码和说出你想要的和你得到的,我们可以多说一些。

+0

谢谢,我已经添加了更多关于问题发生的代码。 – Henry 2015-03-02 22:02:48

+0

现在还不足以说你该做什么更好:)。 – libik 2015-03-02 22:03:48

+0

基本上我需要在后台类中实例化游戏,但每次我选择运行时都会在循环中继续生成新游戏。 – Henry 2015-03-02 22:04:49