简体   繁体   English

java.swing.Timer没有停止

[英]java.swing.Timer not stopping

Could you please help me with this coding? 你能帮我解释这个编码吗? It's a timer that runs a certain task, but it won't stop! 这是一个运行某项任务的计时器,但它不会停止! I'm using java.swing.Timer and WebLookAndFeel (You'll notice the NotificationManager: It belongs to WebLaF). 我正在使用java.swing.Timer和WebLookAndFeel(你会注意到NotificationManager:它属于WebLaF)。 I tried calling a <timer>.stop(); 我试过调用<timer>.stop(); inside of itself but it then says that it isn't instantiated. 在其内部,但它然后说它没有实例化。 I've also tried adding <timer>.setRepeats(false) , which results in an NPE. 我也尝试添加<timer>.setRepeats(false) ,这会导致NPE。 <timer> refers to each unique timer. <timer>指每个唯一的计时器。

The coding w/o the timers works perfectly, but a recent addition to the app required the use of timers. 没有定时器的编码工作得很好,但最近添加到应用程序需要使用定时器。

I taught myself most of what I've used in my coding, so I'm not very good at debugging timers. 我自学了大部分用于编码的东西,所以我不太擅长调试计时器。 Please bear with me. 请多多包涵。

My code: 我的代码:

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) {
}

You're making a lot of long-running calls on the event dispatch thread (or EDT) which will render it helpless. 你在事件调度线程(或EDT)上进行了很多长时间运行的调用,这将使它无助。 Instead, do your database code and any other long-running code in a background thread such as that available with a SwingWorker. 而是在后台线程中执行数据库代码和任何其他长时间运行的代码,例如SwingWorker提供的代码。

As an aside, this empty catch block scares me: 顺便说一句,这个空的挡块吓到我了:

} catch (Exception e) {
}

Note, if you want the Timer to run just once, then you can kill it in the actionPerformed method via: 注意,如果您希望Timer只运行一次,那么您可以通过以下方法在actionPerformed方法中将其终止:

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

You can even make this the first line of your actionPerformed method. 你甚至可以将它作为actionPerformed方法的第一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM