2014-07-06 6 views
3

이 코딩을 도와 주시겠습니까? 특정 작업을 실행하는 타이머이지만 멈추지 않습니다! java.swing.Timer 및 WebLookAndFeel을 사용하고 있습니다 (NotificationManager : WebLaF에 속함). <timer>.stop(); 자체 내부에 전화를 시도했지만 인스턴스화되지 않는다고 말합니다. 또한 <timer>.setRepeats(false)을 추가하여 NPE를 시도했습니다. <timer>은 각 고유 한 타이머를 나타냅니다.java.swing.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) { 
} 

답변

2

당신은 그것을 무력 렌더링 이벤트 파견 스레드에서 장기 실행 호출 (또는 EDT)을 많이 만들고있어. 대신 데이터베이스 코드와 다른 장기 실행 코드를 SwingWorker와 같은 백그라운드 스레드에서 수행하십시오. 당신은 타이머가 한 번만 실행하려면 다음을 통해 actionPerformed 메소드에 죽일 수,

} catch (Exception e) { 
} 

참고 :

((Timer) evt.getSource()).stop(); 
여담으로

이 빈 catch 블록이 나를 무서워

actionPerformed 메소드의 첫 번째 행으로 만들 수도 있습니다.

+1

고마워. 나는 쓸모없는 정보를 제거함으로써 가능한 한이 게시물을 짧게 유지하기 위해 catch 블록을 비 웠습니다. 감사합니다. 방금 evt.getSource에()를 추가하여 답변을 업데이트했습니다. –

+0

@JohanBrink : 정정 해 주셔서 감사합니다! –

관련 문제