簡體   English   中英

在指定的時間后,main(String [])上的Swing Timer退出程序

[英]Swing Timer on main(String[]) exits the program after the time specified

我需要每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秒后關閉,依此類推。

我在這里做錯了什么?

您能舉一個“顯示列表”的例子嗎?

您談論“球”。 關於球,您的程序需要了解什么? 大概是它的位置,也許是它的速度,也許是它的質量。 尺寸? 顏色? 其他的東西? 由你決定。 Ball對象的最簡單實現只是具有public字段的類來保存所有這些信息。 然后,如果Ball是動畫中唯一的移動對象,則顯示列表可能只是List<Ball>

在更復雜的程序中,您的Ball類可能是某個更通用的類(可能是VisibleObject ,然后您的顯示列表將是List<VisibleObject>

據我所知,要使游戲中的所有對象能夠同時工作,它們必須是Thread

從某種意義上說,您是對的,因為在所有Java中只有一個類可以完成任何工作,而該類是Thread 實際上沒有其他班級會任何事情。 其他類僅定義可以線程調用方法。

訣竅是,要使程序中的線程與執行的工作脫鈎。 這就是Runnable接口的動機。 除了擁有一個既是線程又對象(描述線程要完成的工作)的對象,您可以擁有兩個類; 一個負責所有y型線程(.start()、. interrupt()、. join(),...)的工作,另一個負責要完成的工作(.run())。

有人說,編寫一個類/對象太多的程序很困難,但是編寫一個類/對象太少的程序很容易。

只要您的Ball對象或VisibleObject對象清晰地描述了您想要在屏幕上看到的事物以及這些事物移動的方式,就沒有理由為什么每個人的方法都必須由自己的專用線程來調用。 沒有理由為什么不能只有一個線程來輪流對每個線程進行計算。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM