gpt4 book ai didi

java - 如何使用Swing Timers来制定整体更新率?

转载 作者:行者123 更新时间:2023-12-01 22:50:59 25 4
gpt4 key购买 nike

换句话说,我希望能够以一定的赫兹级别运行我的程序。这是我的其他问题 Getting out of a potential deadlock 的部分扩展.

首先,我在 how to use Swing Timers 上阅读了一些 oracle 的 Java 文档。 ,但是有没有一种更简单的方法,这样我就可以做到这一点,而不是调用 wait() 将当前线程暂停一段时间并搞砸我的基于 Swing 的 Pong 游戏?

@Hover_Craft_Full_Of_Eels 状态

"Rather than a while (true) loop that will block the EDT, use a Swing Timer instead."

但是,我从未使用过 Swing Timers,也没有听说过它们,也没有教过我的导师。我可以举个例子来说明如何使用和实现这些 Swing 计时器吗?

编辑:

我发现如何使用 Swing Timers 的解释相当令人困惑。这就是为什么我可以使用 stackoverflow 的一些帮助。

附注:

有没有一种方法可以让图像平滑地移动,只需让图像一次移动一个像素,然后使用 Swing 计时器来使图像移动一个像素的速度或速率更快或这样慢吗?这很大程度上就是我想要创造的效果。否则,如果图像跳过像素,即使在高帧速率下,您也会看到图像每次移动时都会跳跃 5 个像素。

最佳答案

Can I please have an example of how I should use and implement these Swing Timers?

了解更多关于How to Use Swing Timers的信息

这里是示例代码:

int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
}
};
new Timer(delay, taskPerformer).start();

查找 Sample code here

enter image description here

<小时/>

Is there a way to make the images move smoothly by just having the image move one pixel at a time?

示例代码:(以 200 毫秒的间隔将图像从左向右水平移动 1px)

private int x = 1;
...
final Image image = ImageIO.read(new File("resources/1.png"));
final JPanel panel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image,x,10,null);
}
};

int delay = 200; // milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
x++;
if (x > 100) {
x = 1;
}
panel.repaint();
}
};
new Timer(delay, taskPerformer).start();

关于java - 如何使用Swing Timers来制定整体更新率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24726578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com