这是我的简单代码的一部分。此代码包含可移动椭圆形和带有坐标newX=100,newY=100
的静态椭圆形。我试图实现点击鼠标左键后自动移动可移动椭圆形按钮。移动代码行位于新线程 thread
中。Thrad 实际上是通过单击鼠标按钮开始的,但没有任何反应。使用箭头键完成一次移动后,椭圆形开始移动。我尝试调用 repaint ()
方法在不同的地方,但它似乎没有帮助。有什么建议吗?谢谢!
public class Buffer extends JPanel implements Runnable,KeyListener,MouseListener{
public static int x;
public static int y;
public static int newX;
public static int newY;
public static Thread thread;
public static boolean check;
public static JFrame frame;
public static int pointX;
public static int pointY;
public static boolean repaint;
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawOval(x, y, 20, 20);
newX=100;
newY=100;
g.fillOval(newX, newY, 20, 20);
if(repaint)
repaint();
}
public static void main(String args[]){
Buffer z=new Buffer();
z.setBackground(Color.white);
frame=new JFrame();
frame.setSize(500,500);
frame.addKeyListener(z);
frame.addMouseListener(z);
frame.add(z);
frame.setVisible(true);
frame.requestFocusInWindow();
thread=new Thread(){
public void run(){
try{
for(int i=0;i<=5;i++){
x=x+i;
repaint=true;
thread.sleep(1000);
}
}catch(InterruptedException v){System.out.println(v);}
}
};
}
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==KeyEvent.VK_LEFT){
x=x-10;
repaint();
}
if(e.getKeyCode()==KeyEvent.VK_RIGHT){
x=x+10;
repaint();
}
if(e.getKeyCode()==KeyEvent.VK_UP){
y=y-10;
repaint();
}
if(e.getKeyCode()==KeyEvent.VK_DOWN){
y=y+10;
repaint();
}
}
public void mouseClicked(MouseEvent e) {
thread.start();
}
}
最佳答案
您正在从一个线程修改共享变量,并从另一个线程读取它们,没有任何类型的同步。那是错误的。对共享变量的每次访问都必须以同步方式完成,或者应使用线程安全对象(例如 AtomicInteger)。
此外,线程在循环中修改 x
值,但从不调用 repaint()
,因此面板没有理由重新绘制自身。
关于Java-启动线程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17885765/