user1776707
user1776707

Reputation: 33

why does the int not change? java

Can someone please tell me how i can get the value of int x in my following code: when i move the square left and right, the output from Test stays as 500.

I am wanting the Thread in Test to get the value of x every time it loops, but x is always 500 (from the thread) even though the value of x is changing in Drawing.java. please help me with this.

package block;


public class Test extends Drawing implements Runnable{
Thread collision = new Thread(this);

public Test() {
    collision.start();
}

@Override
public void run() {

    while(true) {
        System.out.println(x);
    }
}

}

package block;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Drawing extends Canvas implements Runnable, KeyListener{
Thread thread = new Thread(this);

int x = 500;
int y = 540;
public Drawing() {        
    setSize(1000, 800);
    addKeyListener(this);
    thread.start();
}

public void update(Graphics g) {
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, 1000, 700);
    paint(g);
}

public void paint(Graphics g) {
    g.setColor(Color.cyan);
    g.fillRect(x, y, 50, 50);
}

@Override
public void run() {
    while(true) {
        repaint();
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(Drawing.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}

@Override
public void keyTyped(KeyEvent ke) {

}

@Override
public void keyPressed(KeyEvent ke) {
    if(ke.getKeyCode() == KeyEvent.VK_LEFT) {
        x -= 5;
    }
    if(ke.getKeyCode() == KeyEvent.VK_RIGHT) {
        x += 5;
    }
}

@Override
public void keyReleased(KeyEvent ke) {

}

}

EDIT: --------------------

package block;

import javax.swing.JFrame;


public class Block extends JFrame{

    Test test = new Test();

    public Block() {
        setSize(1000, 700);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);        
        add(new Drawing());        
        setVisible(true);
        createBufferStrategy(2);
    }

    public static void main(String[] args) {
        new Block();
    }
}

Upvotes: 0

Views: 159

Answers (1)

Greg Hewgill
Greg Hewgill

Reputation: 992797

You are creating multiple instances of x because you are not using inheritance correctly. When you call new Test(), that creates one instance of a Test (which contains a Drawing, which contains a member x), and then the call to new Drawing() creates another instance of a Drawing (which contains a different member x).

To fix this, you could pass a reference to a Drawing object to your Test constructor, and access the x member through the reference.

Upvotes: 2

Related Questions