Java Scanner issues (JFrame)

£可爱£侵袭症+ 提交于 2019-12-02 10:01:33

A quick-and-dirty solution is, to test for Window.room not to be null, as well as .block:

        Scanner loadLevelsScanner = new Scanner (loadPath);
        if ((Window.room != null) && 
            (Window.room.block != null)) {
            // ... block until catch block 
        }

A simple Testapp I've written works so far, if done so.

But you need to understand what "static" is, and why and how to use it. A common beginner mistake is, to instert "static" keywords just to make the compiler silent.

Investigate, in which order to initialize your classes and their attributes.

In Block, to access the Window, you have to have a reference. The reference can be passed to the ctor of Block:

class Block extends Rectangle {
    public int groundID;
    public int airID;
    Window window; 

    public Block (int x, int y, int width, int height, int groundID, int airID, Window window) {
        setBounds (x, y, width, height);
        this.groundID = groundID;
        this.airID = airID;
        this.window = window;
    }
    public void draw (Graphics g) {
        g.drawImage (window.tileset_ground [groundID], x, y, width, height, null);
        if (airID != Value.airAir) {
            g.drawImage (window.tileset_air [airID], x, y, width, height, null);
        }
    }
}

Who creates Blocks? It is Room, so Room itself needs to know about the Window (as long as you don't change your design fundamentally).

public Room (Window w) {
    block = new Block [worldHeight] [worldWidth];
    for (int y=0; y <block.length; y++) {
        for (int x=0; x <block [0].length; x++) {
            block [y] [x] = new Block (x * blockSize, y * blockSize, blockSize, blockSize, Value.groundGrass, Value.airAir, w);
        }
    }
}

A block array is created, initialized, and the Blocks are passed the Window-parameter.

In draw, you don't recreate the array over and over again, nor do you recreate the Blocks, but just redraw them:

public void draw (Graphics g) {
    for (int y=0; y <block.length; y++) {
        for (int x=0; x <block [0].length; x++) {
            block [y] [x].draw (g);
        }
    }
}

In Window, you create the Room, and pass it the window-reference:

public void define () {
    room = new Room (this);
    levels = new Levels ();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!