java - 计时器将 Graphics2D 对象移动到 JFrame 中的图像上? (日出程序示例)

标签 java swing timer graphics2d

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

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();
    }
});

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

关于java - 计时器将 Graphics2D 对象移动到 JFrame 中的图像上? (日出程序示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13105652/

相关文章:

android - 如何在android中停止计时器?

ios - 一段时间后通过编码自动从相机捕获图像

javascript - Java - 与使用 javax.script.ScriptEngine 的 1.7 相比,Javascript 正则表达式代码在 1.8 上失败;

java - 如果一条记录插入失败,如何让Preparedstatement.executeBatch() 为好记录工作

java - 无法在 fragment 内显示对话框?

java - 如何使用Where子句查询显示从jtextfield到jtable的搜索查询从mysql表

c# - 在 C# 中制作计时器 - 秒到分钟到小时等

java - GateIn:登录 servlet 的过滤器

java - 我想像在 ms excel 中一样在 JTable 中获得自动过滤

java - 如何更改工具提示的外观和感觉以适应系统?