有人可以告诉我如何在以下代码中获取 int x 的值:当我左右移动方块时,Test 的输出保持为 500。
我希望测试中的线程在每次循环时都获取 x 的值,但 x 始终为 500(来自线程),即使 x 的值在 Drawing.java 中发生变化。请帮我解决一下这个。
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) {
}
}
编辑: - - - - - - - - - -
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();
}
}