Search code examples
javaswingfinal

final var changes value JAVA


I dont understand why i have initialized HEIGHT and WEIGHT as 32 and it's ok in Window(), but in inner class GamePanel it has value 1 and 2, btw SCALE is 20 as in 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)
        {
            //
        }

    }
}

Solution

  • The WIDTH and HEIGHT variables do not belong to your Window class. They are from java.awt.Image.ImageObserver interface.

    Here is the content of the interface I mentioned

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