有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java在循环中实例化类

我在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);
    }

}

游戏。爪哇

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();
}

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


共 (1) 个答案

  1. # 1 楼答案

    你可能需要考虑类的概念和它的依赖关系,但在你的情况下,这是最简单、最快的方法,只保留一个游戏实例:

    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);
        }
    }
    

    如果你添加更多代码,说出你想要什么,得到什么,我们可以告诉你更多