Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 计时器在JFrame中的图像上移动Graphics2D对象?(日出计划示例)_Java_Swing_Timer_Graphics2d - Fatal编程技术网

Java 计时器在JFrame中的图像上移动Graphics2D对象?(日出计划示例)

Java 计时器在JFrame中的图像上移动Graphics2D对象?(日出计划示例),java,swing,timer,graphics2d,Java,Swing,Timer,Graphics2d,我正试图编写一个程序,通过使用计时器、JFrame和JComponent来设计日出动画。Graphics2D的对象是将在JFrame上移动的太阳。我的问题是,我不知道在哪里放置计时器和移动图形C2D!这里是我到目前为止所做的,在JFrame中放置一个图像,然后在该图像上放置太阳。请告诉我在哪里可以移动太阳。我应该在哪里定义计时器类?在JFrame、JComponent或main类中 public class Main(){ public static void main(String

我正试图编写一个程序,通过使用计时器、JFrame和JComponent来设计日出动画。Graphics2D的对象是将在JFrame上移动的太阳。我的问题是,我不知道在哪里放置计时器和移动图形C2D!这里是我到目前为止所做的,在JFrame中放置一个图像,然后在该图像上放置太阳。请告诉我在哪里可以移动太阳。我应该在哪里定义计时器类?在JFrame、JComponent或main类中

public class Main(){

     public static void main(String[] args){

          myFrame frame = new myFrame();
     }
}

class myFrame extends JFrame
{
    public  myFrame()
    {
        Draw component = new Draw();
        add(component);
    }
}

class Draw extends JComponent
{
    public Draw()
    {
          //Read the image here
          //set the newImage
    }

    public void paintComponent(Graphics g)
    {
            Graphics2D g2 = (Graphics2D) g; 
            g2.drawImage(newImage, 0, 0, null);
            g2.fill(new Ellipse2D.Double(x,y,20,20));
            //For the sunrise I need to change x,y during the Timer class!!
    }

}
这应该做到:

int x, y;
Timer timer = new Timer(50, new ActionListener(){

    public void actionPerformed(ActionEvent evt){
        // update x and y 

        repaint();
    }
});
不要忘记启动计时器(最好在构造函数中启动)。

这应该可以:

int x, y;
Timer timer = new Timer(50, new ActionListener(){

    public void actionPerformed(ActionEvent evt){
        // update x and y 

        repaint();
    }
});

不要忘记启动计时器(最好在构造函数中启动)。

在构造函数结束后启动计时器更安全,通常是通过导出调用
timer.start()
start()方法来启动计时器。另请参阅。我试图在计时器上重新绘制帧,但重新绘制图形是正确的方法。您的代码提供了解决问题的线索。在构造函数结束后启动计时器更安全,通常是通过导出调用
timer.start()
start()方法。另请参阅。我试图在计时器上重新绘制帧,但重新绘制图形是正确的方法。您的代码提供了解决问题的线索。请确保您调用了
super.paintComponent(g)
,这项工作非常重要,除非您有充分的理由这样做,否则不应避免;)请确保您调用了
super.paintComponent(g)
,这项工作非常重要,除非您有充分的理由,否则不应回避;)