带有 GUI (Eclipse) 的 Javax.swing.timer [英] Javax.swing.timer with GUI (Eclipse)

查看:19
本文介绍了带有 GUI (Eclipse) 的 Javax.swing.timer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个代码,使正方形从面板左侧移动到面板右侧...我意识到您可以简单地使图像出现在代码块中,然后出现在下一个代码块将图像与与背景颜色相同的完全相同的正方形重叠...为此,我需要一个类似代码的计时器,使图像出现,然后在 1 秒后得到重叠,然后新图像出现在它旁边

I want to make a code that makes a square move from the left side of the panel to the right side of the panel... I realized that you could simply make a image appear in on block of code and then in the next block of code have the image be overlapped by a exactly the same square just with the same color as the background... To do that I need a timer like code that makes it so that the image appears and then 1 second later it gets over lapped and then the new image appears right beside it

意识到 sleep.thread 不能很好地与 gui 配合使用,我正在求助于 Javax.Swing.Timer

Realizing that sleep.thread doesn't work nice with gui i'm resorting to Javax.Swing.Timer

我只是想让它现在旁边出现一个框

I just want it to make one box appear beside it for now

但是我没有使用它的经验,需要一些帮助才能让它与我的代码一起工作-安德鲁

However i have no experience with it and need some help getting it to work with my code -Andrew

    {

          g.setColor(Color.GREEN);
          g.fillRect(50, 100, 100, 100); //first box on a red background

                      //Timer goes here

                      g.setColor(Color.RED);
          g.fillRect(50, 100, 100, 100);//overlapps the first box
                      g.setColor(Color.GREEN);
          g.fillRect(50, 110, 100, 100);//sets a new box right beside it

    }

}

推荐答案

创建一个 javax.swing.Timer 其实很简单.您不必担心自己的线程,因为调度会在后台线程中自动发生,但是您实现的侦听器的代码是在 GUI 线程中执行的.因此,您可以使用侦听器主体中所需的任何摆动组件.

Creating a javax.swing.Timer is quite simple actually. You don't have to worry about the threads yourself, because the scheduling happens automatically in a background thread, but the code of the listener you implement is executed in the GUI thread. Therefore you can work with whatever swing components you need in the listener body.

int interval = 1000; // repeating every 1000 ms
new Timer(interval, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // do whatever painting that you want
    }
}).start();

这篇关于带有 GUI (Eclipse) 的 Javax.swing.timer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆