2015-03-02 46 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