【问题标题】:java.swing.Timer not stoppingjava.swing.Timer 没有停止
【发布时间】:2014-07-06 17:25:11
【问题描述】:

你能帮我写一下这个编码吗?这是一个运行某个任务的计时器,但它不会停止!我正在使用 java.swing.Timer 和 WebLookAndFeel(您会注意到 NotificationManager:它属于 WebLaF)。我尝试在其内部调用 <timer>.stop(); ,但随后它说它没有被实例化。我还尝试添加<timer>.setRepeats(false),这会导致 NPE。 <timer> 指代每个唯一的计时器。

没有计时器的编码可以完美运行,但最近添加到应用程序中需要使用计时器。

我自学了我在编码中使用的大部分内容,因此我不太擅长调试计时器。请多多包涵。

我的代码:

Timer updateEB;
try {
    updateEB = new Timer(2500, new ActionListener() 

    @Override
    public void actionPerformed(ActionEvent evt) {

        System.out.println("Update process started");

        try {
            // <editor-fold defaultstate="collapsed" desc="Get first message via SQL query">
            try {
                // Initiate SQL connection and execute query
                String sql = "Select * from APP.EBULLETINS ORDER BY msgid DESC FETCH FIRST 2 ROWS ONLY";
                Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
                Class.forName("org.apache.derby.jdbc.ClientDriver");
                Connection con = (Connection) DriverManager.getConnection("jdbc:derby:C:\\Program Files\\AmalgaIMS\\AIMSDB", "xxxxxxx", "xxxxxxxx");
                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery(sql);

                //  Get message details
                if (rs.next()) {
                    eBul1_Title = rs.getString("Title");
                    eBul1_Msg = rs.getString("Content");
                    eBul1_Type = rs.getString("MSGTYPE");
                }

                // Set message fields
                eBul1T.setText(eBul1_Title);
                eBul1M.setText(eBul1_Msg);

                // Debugging purposes
                System.out.println("Setting Icons...");
                System.out.print("1. ");

                // <editor-fold defaultstate="collapsed" desc="Set Message 1 Icon">
                if (eBul1_Type.equals("INFORMATION")) {
                    TypeImage1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/main/MainMenu/Information.png")));
                    System.out.println("Info");
                } else if (eBul1_Type.equals("ANNOUNCEMENT")) {
                    TypeImage1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/main/MainMenu/announcement.png")));
                    System.out.println("Announce");
                } else if (eBul1_Type.equals("WARNING")) {
                    TypeImage1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/main/MainMenu/Warning.png")));
                    System.out.println("Warning");
                } else {
                    TypeImage1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/main/MainMenu/misc 16x16.png")));
                    System.out.println("Other");
                }
                // </editor-fold>
                } catch (Exception eB1Exc) {
                    JOptionPane.showMessageDialog(null, eB1Exc);
                }
                // </editor-fold>

                // <editor-fold defaultstate="collapsed" desc="Get second message via SQL query">
                try {
                    // Initiate SQL connection and execute query
                    String sql = "Select * from app.EBULLETINS ORDER BY msgid DESC FETCH FIRST 2 ROWS ONLY";
                    Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
                    Class.forName("org.apache.derby.jdbc.ClientDriver");
                    Connection con = (Connection) DriverManager.getConnection("jdbc:derby:C:\\Program Files\\AmalgaIMS\\AIMSDB", "xxxxxxxx", "xxxxxxxxx");
                    Statement stmt = con.createStatement();
                    ResultSet rs = stmt.executeQuery(sql);

                    //  Get message details
                    while (rs.next()) {
                        eBul2_Title = rs.getString("Title");
                        eBul2_Msg = rs.getString("Content");
                        eBul2_Type = rs.getString("MSGTYPE");
                    }

                    // Debugging purposes
                    System.out.print("2. ");

                    // Set message fields
                    eBul2T.setText(eBul2_Title);
                    eBul2M.setText(eBul2_Msg);

                    // <editor-fold defaultstate="collapsed" desc="Set Message 2 Icon">
                    if (eBul2_Type.equals("INFORMATION")) {
                        TypeImage2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/main/MainMenu/Information.png")));
                        System.out.println("Info");
                    } else if (eBul2_Type.equals("ANNOUNCEMENT")) {
                        TypeImage2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/main/MainMenu/announcement.png")));
                        System.out.println("Announce");
                    } else if (eBul2_Type.equals("WARNING")) {
                        TypeImage2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/main/MainMenu/Warning.png")));
                        System.out.println("Warning");
                    } else {
                        TypeImage2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/main/MainMenu/misc 16x16.png")));
                        System.out.println("Other");
                    }
                    // </editor-fold>
                } catch (Exception eB2Exc) {
                    eB2Exc.printStackTrace();
                }
                // </editor-fold>

                //<editor-fold defaultstate="collapsed" desc="Update Successful">
                //<editor-fold defaultstate="collapsed" desc="Set eBulletin Notification Sound">
                try {
                    // Open an audio input stream.
                    URL url = this.getClass().getResource("/Resources/Sounds/Notifications/NotifB.wav");
                    AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
                    // Get a sound clip resource.
                    Clip clip = AudioSystem.getClip();
                    // Open audio clip from the audio input stream.
                    clip.open(audioIn);
                    clip.start();
                } catch (UnsupportedAudioFileException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (LineUnavailableException e) {
                    e.printStackTrace();
                }
                //</editor-fold>

                NotificationManager.showNotification("eBulletins updated!", NotificationIcon.mail.getIcon());

                Timer hideNotifs;
                try {
                    hideNotifs = new Timer(3000, new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        NotificationManager.hideAllNotifications();
                    }
                });

                hideNotifs.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception exc) {
                exc.printStackTrace();
            }
            //</editor-fold>

            //<editor-fold defaultstate="collapsed" desc="Set Refresh Icon">
            try {
                lbleBulUpdate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Resources/refresh 16x16.png")));
            } catch (Exception e) {
                System.out.println(e);
            }
            //</editor-fold>

            lblEBulStatus.setForeground(new java.awt.Color(51, 255, 0));
            lblEBulStatus.setText("ACTIVE");
        }
    });
    updateEB.start();
} catch (Exception e) {
}

【问题讨论】:

    标签: java swing debugging netbeans timer


    【解决方案1】:

    您在事件调度线程(或 EDT)上进行了大量长时间运行的调用,这将使其无能为力。相反,在后台线程中执行您的数据库代码和任何其他长时间运行的代码,例如 SwingWorker 可用的。

    顺便说一句,这个空的 catch 块让我害怕:

    } catch (Exception e) {
    }
    

    注意,如果你想让 Timer 只运行一次,那么你可以在 actionPerformed 方法中通过以下方式杀死它:

    ((Timer) evt.getSource()).stop();
    

    您甚至可以将此作为 actionPerformed 方法的第一行。

    【讨论】:

    • 感谢您的建议。我清空了 catch 块,试图通过删除无用的信息来尽可能缩短这篇文章。你的回答有帮助,谢谢。我刚刚更新了您的答案,将 () 添加到 evt.getSource
    猜你喜欢
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多