final var更改值JAVA

时间:2018-01-14 18:14:56

标签: java swing final

我不明白为什么我将HEIGHT和WEIGHT初始化为32并且它在Window()中没问题,但是在内部类GamePanel中它有值1和2,顺便说一下SCALE是20,就像Window()

public class Window extends JFrame {
    private final int SCALE;
    private final int WIDTH;
    private final int HEIGHT;

    public Window()
    {
        super("Snake");
        SCALE=20;
        WIDTH=32;
        HEIGHT=32;
        setSize(new Dimension(SCALE*WIDTH,SCALE*HEIGHT));
        setLocation(getWidth()/2,0);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        GamePanel gamePanel = new GamePanel();
        setContentPane(gamePanel);
        setVisible(true);
    }

    private class GamePanel extends JPanel {

        @Override
        public void paint(Graphics g) {
            g.setColor(Color.BLACK);
            g.fillRect(0,0,getWidth(),getHeight());
            drawGrid(g);
            System.out.println(SCALE);
            System.out.println(WIDTH);
            System.out.println(HEIGHT);
        }

        public void drawGrid(Graphics g)
        {
            //
        }

    }
}

2 个答案:

答案 0 :(得分:2)

WIDTH和HEIGHT变量不属于您的Window类。它们来自java.awt.Image.ImageObserver接口。

以下是我提到的界面的内容

package java.awt.image;

import java.awt.Image;

public interface ImageObserver {

    public static final int WIDTH = 1;
    public static final int HEIGHT = 2;
    public static final int PROPERTIES = 4;
    public static final int SOMEBITS = 8;
    public static final int FRAMEBITS = 16;
    public static final int ALLBITS = 32;
    public static final int ERROR = 64;
    public static final int ABORT = 128;

    public boolean imageUpdate(Image image, int i, int i1, int i2, int i3, int i4);
}

答案 1 :(得分:1)

你什么时候: 私人类GamePanel扩展了JPanel

您正在扩展JPanel,以便继承其所有公共/受保护/包变量。如果检查所有继承树:

JPanel< - JComponent< - Container< - Component< - ImageObserver

如果您查看ImageObserver来源,您会发现:

public static final int WIDTH = 1;
public static final int HEIGHT = 2;

因为继承的变量是外部类的优先级。这就是显示的值。

因此,请考虑将它们作为参数传递,以获得正确的值。