用于随机移动对象的重绘方法

时间:2015-03-15 15:24:11

标签: java swing repaint jcomponent

我正在尝试随机移动一个对象。我有我的GUI类,它使用另一个类(比如说Obj)创建一个新图像,然后启动线程使对象随机移动。但我的repaint()在这种情况下不起作用。下面的代码可以让您了解我如何使用重绘方法。 谢谢,

桂班

 public class GUI extends JFrame implements ActionListener {

     public void addNewObj(){
                Obj f = new Obj();
                x = panel.getGraphics();
                f.paint(x);
                Thread thr=new Thread(f);
                thr.start();
            }
    }

创建对象类

public class Obj extends JPanel implements Runnable
{

public Obj()
{


    try {
    myImage = ImageIO.read(new File("b:\\imgs\\bottle.jpg"));
    }
      catch (IOException e) {}
}

public void run()
{
    long beforeTime, timeDiff, sleep;
    beforeTime = System.currentTimeMillis();
    while (true)
    {

        timeDiff = System.currentTimeMillis() - beforeTime;
        sleep = DELAY - timeDiff;


        try
        {
             moveRandom();
             repaint();
            Thread.sleep(1000);
        }
        catch (InterruptedException e)
        {
            System.out.println("interrupted");
        }

        beforeTime = System.currentTimeMillis();
    }
}

1 个答案:

答案 0 :(得分:2)

问题非常基本:永远不要像你那样画一个物体。您应该将其添加到框架或容器中。这也是为什么repaint()不起作用的原因。你的对象永远不会进入组件层次,因此重绘只会重绘这个单个对象,而不是其他任何东西(包括应该重新绘制的帧)。只需将对象直接添加到框架,验证并重新绘制框架。

新的addNewObj:

public void addNewObj(){
      Obj f = new Obj();

      Thread t = new Thread(f);
      t.start();

      panel.add(f);//add it to the panel
      panel.validate();//validate the hierachy
      panel.repaint();//repaint the whole thing to make the new obj visible
}

覆盖你的Obj类来绘制对象:

public void paintComponent(Graphics g){
     super.paintComponent(g);
     g.drawImage(myImage , 0 , 0 , Color.white , null);
}
相关问题