java - 谁能帮我使用 StartingClass 中的 loadMap() 方法加载 map (文本文件)?

标签 java swing methods text-files paintcomponent

这是一个Applet 游戏。我想让它成为一个应用程序。所以我在我的 StartingClass 中扩展了 JPanel。这是有效的,但是当从 start() 方法调用 loadMap() 方法时,map 不会加载。 map 实际上是一个文本文件。但这并没有加载。谁能帮我解决这个问题吗?

起始类(class):

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class StartingClass extends JPanel implements Runnable, KeyListener {

    // enum GameState {
    // Running, Dead
    // }
    //
    // GameState state = GameState.Running;

    private static final int Running = 1;
    private static final int Dead = 2;
    private static int state = Running;

    private static Robot robot;
    public static Heliboy hb, hb2;
    public static int score = 0;
    private Font font = new Font(null, Font.BOLD, 30);
    private static Background bg1, bg2;
    private BufferedImage image, currentSprite, character, character2,
            character3, characterDown, characterJumped, background, heliboy,
            heliboy2, heliboy3, heliboy4, heliboy5;
    private Graphics second;

    private Animation anim, hanim;
    public static Image tilegrassTop, tilegrassBot, tilegrassLeft,
            tilegrassRight, tiledirt;
    private ArrayList<Tile> tilearray = new ArrayList<Tile>();

    public void init() {
        setSize(800, 480);
        setBackground(Color.BLACK);
        setFocusable(true);

        addKeyListener(this);

        try {

            character = ImageIO.read(this.getClass().getResource(
                    "data/character.png"));
            character2 = ImageIO.read(this.getClass().getResource(
                    "data/character2.png"));
            character3 = ImageIO.read(this.getClass().getResource(
                    "data/character3.png"));

            characterDown = ImageIO.read(this.getClass().getResource(
                    "data/down.png"));
            characterJumped = ImageIO.read(this.getClass().getResource(
                    "data/jumped.png"));

            heliboy = ImageIO.read(this.getClass().getResource(
                    "data/heliboy.png"));
            heliboy2 = ImageIO.read(this.getClass().getResource(
                    "data/heliboy2.png"));
            heliboy3 = ImageIO.read(this.getClass().getResource(
                    "data/heliboy3.png"));
            heliboy4 = ImageIO.read(this.getClass().getResource(
                    "data/heliboy4.png"));
            heliboy5 = ImageIO.read(this.getClass().getResource(
                    "data/heliboy5.png"));

            background = ImageIO.read(this.getClass().getResource(
                    "data/background.png"));

            tiledirt = ImageIO.read(this.getClass().getResource(
                    "data/tiledirt.png"));
            tilegrassTop = ImageIO.read(this.getClass().getResource(
                    "data/tilegrasstop.png"));
            tilegrassBot = ImageIO.read(this.getClass().getResource(
                    "data/tilegrassbot.png"));
            tilegrassLeft = ImageIO.read(this.getClass().getResource(
                    "data/tilegrassleft.png"));
            tilegrassRight = ImageIO.read(this.getClass().getResource(
                    "data/tilegrassright.png"));
        } catch (Exception e) {

        }
        anim = new Animation();
        anim.addFrame(character, 1250);
        anim.addFrame(character2, 50);
        anim.addFrame(character3, 50);
        anim.addFrame(character2, 50);

        hanim = new Animation();
        hanim.addFrame(heliboy, 100);
        hanim.addFrame(heliboy2, 100);
        hanim.addFrame(heliboy3, 100);
        hanim.addFrame(heliboy4, 100);
        hanim.addFrame(heliboy5, 100);
        hanim.addFrame(heliboy4, 100);
        hanim.addFrame(heliboy3, 100);
        hanim.addFrame(heliboy2, 100);

        currentSprite = anim.getImage();
    }

    public void start() {

        bg1 = new Background(0, 0);
        bg2 = new Background(2160, 0);
        robot = new Robot();
        hb = new Heliboy(340, 360);
        hb2 = new Heliboy(700, 360);

        // Initialize tiles
        try {

            loadMap("data/map1.txt"); //What is the problem here??
            System.out.print("Pobon File Inside");
        } catch (Exception e) {
            // TODO: handle exception
        }

        Thread thread = new Thread(this);
        thread.start();
    }

    // Loading the tile map
    private void loadMap(String filename) throws IOException {
        ArrayList lines = new ArrayList();
        int width = 0;
        int height = 0;
        FileReader fReader = new FileReader(filename);
        BufferedReader reader = new BufferedReader(fReader);
        while (true) {
            String line = reader.readLine();
            if (line == null) {
                reader.close();
                break;
            }
            if (!line.startsWith("!")) {
                lines.add(line);
                width = Math.max(width, line.length());
            }
        }
        height = lines.size(); // it represents the total arraylist value size

        for (int j = 0; j < 12; j++) {
            String line = (String) lines.get(j);
            for (int i = 0; i < width; i++) {
                System.out.println(i + " is i");
                if (i < line.length()) {
                    char ch = line.charAt(i);
                    Tile t = new Tile(i, j, Character.getNumericValue(ch));
                    tilearray.add(t);
                }
            }
        }
    }

    @Override
    public void run() {
        if (state == Running) {
            while (true) {

                robot.update();
                if (robot.isJumped() == true) {
                    robot.setDucked(false);
                    currentSprite = characterJumped;

                } else if (robot.isJumped() == false) {
                    currentSprite = anim.getImage();
                }
                if (robot.isDucked() == true) {
                    currentSprite = characterDown;
                }

                ArrayList<Projectile> projectiles = robot.getProjectiles();
                for (int i = 0; i < projectiles.size(); i++) {
                    Projectile p = (Projectile) projectiles.get(i);
                    if (p.isVisible() == true) {
                        p.update();
                    } else {
                        projectiles.remove(i);
                    }
                }

                updateTiles();

                hb.update();
                hb2.update();

                bg1.update();
                bg2.update();

                animate();

                repaint();
                System.out.print("Pobon run");
                try {
                    Thread.sleep(17);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (robot.getCenterY() > 500) {
                    state = Dead;
                }
            }
        }
    }

    public void animate() {
        anim.update(10);
        hanim.update(50);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (state == Running) { // set for game state Running
            g.drawImage(background, bg1.getBgX(), bg1.getBgY(), this); // This is line `242`
            g.drawImage(background, bg2.getBgX(), bg2.getBgY(), this);
            paintTiles(g);
            g.drawImage(currentSprite, robot.getCenterX() - 61,
                    robot.getCenterY() - 63, this);
            g.drawImage(hanim.getImage(), hb.getCenterX() - 48,
                    hb.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb2.getCenterX() - 48,
                    hb2.getCenterY() - 48, this);

            ArrayList<Projectile> projectiles = robot.getProjectiles();
            for (int i = 0; i < projectiles.size(); i++) {
                Projectile p = (Projectile) projectiles.get(i);
                g.setColor(Color.YELLOW);
                g.fillRect(p.getX(), p.getY(), 10, 5);
            }

            g.setFont(font);
            g.setColor(Color.WHITE);
            g.drawString("Score: " + Integer.toString(score), 640, 30);

            // Set for Enemy Health
            if (hb.enemyVisibility == true) {
                g.drawString("Health: " + Integer.toString(hb.health), 450, 30);
            } else if (hb2.enemyVisibility == true) {
                g.drawString("Health: " + Integer.toString(hb2.health), 450, 30);
            }

        } else if (state == Dead) { // set for game state Dead
            g.setColor(Color.BLACK);
            g.fillRect(0, 0, 800, 480);
            g.setFont(new Font("SansSerif", Font.BOLD, 60));
            g.setColor(Color.WHITE);
            g.drawString("DEAD", 310, 240);
        }
    }

    private void updateTiles() {
        for (int i = 0; i < tilearray.size(); i++) {
            Tile t = (Tile) tilearray.get(i);
            t.update();
        }
    }

    private void paintTiles(Graphics g) {
        for (int i = 0; i < tilearray.size(); i++) {
            Tile t = (Tile) tilearray.get(i);
            g.drawImage(t.getTileImage(), t.getTileX(), t.getTileY(), this);
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {

        switch (e.getKeyCode()) {
        case KeyEvent.VK_UP:
            System.out.println("moving up");
            break;
        case KeyEvent.VK_DOWN:

            if (robot.isJumped() == false) {
                // currentSprite = anim.getImage();
                robot.setDucked(true);
                robot.setSpeedX(0);
            }
            break;
        case KeyEvent.VK_LEFT:
            robot.moveLeft();
            robot.setMovingLeft(true);
            break;
        case KeyEvent.VK_RIGHT:
            robot.moveRight();
            robot.setMovingRight(true);
            break;
        case KeyEvent.VK_SPACE:
            robot.jump();
            break;
        case KeyEvent.VK_CONTROL:
            if (robot.isDucked() == false && robot.isJumped() == false) {
                robot.shoot();
                robot.setReadyToFire(false);
            }
            break;
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {

        switch (e.getKeyCode()) {
        case KeyEvent.VK_UP:
            System.out.println("stop moving up");
            break;
        case KeyEvent.VK_DOWN:
            currentSprite = character;
            robot.setDucked(false);
            break;
        case KeyEvent.VK_LEFT:
            robot.stopLeft();
            break;
        case KeyEvent.VK_RIGHT:
            robot.stopRight();
            break;
        case KeyEvent.VK_SPACE:

            break;
        case KeyEvent.VK_CONTROL:
            robot.setReadyToFire(true);
            break;
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }

    public static Background getBg1() {
        return bg1;
    }

    public static Background getBg2() {
        return bg2;
    }

    public static Robot getRobot() {
        return robot;
    }
}

主类:

    import java.awt.BorderLayout;

import javax.swing.JFrame;

public class MainClass {

    public static void main(String[] args) {
        JFrame frame = new JFrame();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setSize(800, 480);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);

        StartingClass startingClass = new StartingClass();
        startingClass.init();
        startingClass.start();


        frame.add(startingClass, BorderLayout.CENTER);



    }

}

StackTrace 显示的是:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at StartingClass.paintComponent(StartingClass.java:242)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JLayeredPane.paint(Unknown Source)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paintToOffscreen(Unknown Source)
    at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
    at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
    at javax.swing.RepaintManager.paint(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at java.awt.GraphicsCallback$PaintCallback.run(Unknown Source)
    at sun.awt.SunGraphicsCallback.runOneComponent(Unknown Source)
    at sun.awt.SunGraphicsCallback.runComponents(Unknown Source)
    at java.awt.Container.paint(Unknown Source)
    at java.awt.Window.paint(Unknown Source)
    at javax.swing.RepaintManager$3.run(Unknown Source)
    at javax.swing.RepaintManager$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
    at javax.swing.RepaintManager.access$1100(Unknown Source)
    at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

最佳答案

swing 使用 paintComponent 方法来绘制内容,并且在 start 方法中初始化 bg1bg2 之前调用此方法。 一个简单的解决方法是引入一个附加状态:

private static final int Initializing = 0;
private static int state = Initializing;

在启动方法中将状态更新为Running:

public void start() {

        bg1 = new Background(0, 0);
        bg2 = new Background(2160, 0);
        robot = new Robot();
        hb = new Heliboy(340, 360);
        hb2 = new Heliboy(700, 360);

        state = Running;
        ...

关于java - 谁能帮我使用 StartingClass 中的 loadMap() 方法加载 map (文本文件)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34220489/

相关文章:

java - 如何获取JOptionPane的退出值

Java 面板向下滚动

java - swing中视觉组件的动态更新

javascript - 如何在Android中添加通知徽章计数?

javascript - 多条路由 Backbone 上的相同事件

javascript - 如何最好地覆盖 Javascript 对象方法

Java:检查符号链接(symbolic link)文件是否存在

java - 未加载高级 GWT 组件主题 CSS

java - PinView 子采样比例 ImageView 错误

java - 在java中显示图像