我需要每 2 秒生成一个新的Thread
。因此,我尝试在 main(String[])
方法中使用 Timer
类,但我的程序仅在我在 Timer
中指定的毫秒后存在> 构造函数。
Program.java:
public class Program
{
private static int panelWidth;
private static int panelHeight;
private static MyPanel panel = new MyPanel();
public static void main(String[] args)
{
MyFrame frame = new MyFrame();
frame.add(Program.panel);
Program.panelWidth = frame.getWidth();
Program.panelHeight = frame.getHeight();
Timer generateBallTimer = new Timer(2000, new GenerateBalls());
while (true)
{
generateBallTimer.start();
}
} // End of main method
/**
* Generate a new ball every 2 seconds.
*
*/
public static class GenerateBalls implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
Program.generateBalls();
}
}
public static void generateBalls()
{
// Generate a ball each 2 seconds
while (true)
{
Program.panel.balls.add(new Ball(Program.panel));
}
}
} // End of program class
如果在 Timer
构造函数中我将指定 3000ms,我的程序将在 3 秒后关闭,依此类推。
我在这里做错了什么?
最佳答案
Can you give me example of that "display list"?
你谈论“球”。您的程序需要了解关于球的哪些信息?可能是它的位置,也许是它的速度,也许是它的质量。尺寸?颜色?其他的东西?由你决定。 Ball
最简单的实现object 只是一个带有 public
的类保存所有这些信息的字段。那么,如果Ball
是动画中唯一一种移动对象,那么您的显示列表可能只是 List<Ball>
.
在更复杂的程序中,您的 Ball
类可能是一些更通用的类的扩展,也许 VisibleObject
,然后您的显示列表将是 List<VisibleObject>
.
As far as I know,for all the objects in a game to work concurrently they need to be
Thread
s.
从某种意义上说,你是对的,因为整个 Java 中只有一个类可以完成任何工作,该类是 Thread
。没有其他类实际上做任何事情。其他类仅定义可由线程调用的方法。
诀窍在于,将程序中的线程与其所做的工作分离。这就是 Runnable
的动机界面。您可以拥有两个类,而不是拥有一个既是线程又描述线程要完成的工作的对象;一个负责所有线程相关的事情(.start()、.interrupt()、.join()、...),另一个描述要完成的工作(.run())。
有人说,编写一个具有太多类/对象的程序很困难,但编写一个具有太少类/对象的程序很容易。
只要你的Ball
物体或你的VisibleObject
对象清楚地描述了您希望在屏幕上看到的事物以及您希望看到这些事物移动的方式,没有理由必须由其自己的专用线程调用每个对象的方法。没有理由不能让一个线程轮流为每个线程进行计算。
关于java - main(String[]) 上的 Swing Timer 在指定时间后退出程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36920935/