2010-12-07 3 views
1

スウィングTimerを使用して、webNotificationのカスタムJFrameを特定の時刻に表示しています。私は通知を却下し、それが1時間後に戻ってくるようにするために、「非表示」ボタンをクリックするオプションをユーザにもたせたい。どうすればこれを達成できますか?スイングタイマーを使用して通知を一時的に非表示にする

答えて

7

javax.swing.Timerに初期遅延があります。 60 * 60 * 1000に設定してください。 actionPerformed()start()を呼び出してから1時間後に呼び出されます。

補足:ここでは、指定した期間内にそのウィンドウを隠すボタンの例を示します。

import java.awt.EventQueue; 
import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.Timer; 

/** @see http://stackoverflow.com/questions/4373493 */ 
public class TimerFrame extends JFrame { 

    private void display() { 
     this.setTitle("TimerFrame"); 
     this.setLayout(new GridLayout(0, 1)); 
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     this.add(new TimerButton("Back in a second", 1000)); 
     this.add(new TimerButton("Back in a minute", 60 * 1000)); 
     this.add(new TimerButton("Back in an hour", 60 * 60 * 1000)); 
     this.pack(); 
     this.setLocationRelativeTo(null); 
     this.setVisible(true); 
    } 

    /** A button that hides it's enclosing Window for delay ms. */ 
    private class TimerButton extends JButton { 

     private final Timer timer; 

     public TimerButton(String text, int delay) { 
      super(text); 
      this.addActionListener(new StartListener()); 
      timer = new Timer(delay, new StopListener()); 
     } 

     private class StartListener implements ActionListener { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       TimerFrame.this.setVisible(false); 
       timer.start(); 
      } 
     } 

     private class StopListener implements ActionListener { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       timer.stop(); 
       TimerFrame.this.setVisible(true); 
      } 
     } 
    } 

    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       new TimerFrame().display(); 
      } 
     }); 
    } 
} 
+0

しかし、時間遅れが24時間以内ではなく1週間以内にそれ以上の場合はどうなりますか?その日までに数時間を数えて遅れて設定する必要がありますか?それとも他の方法がありますか? – bsm

+0

@bsm:[Quartz](http://stackoverflow.com/questions/tagged/quartz)は一般的な選択ですが、私は典型的に['at'](http://unixhelp.ed.ac.uk/CGI/man-cgi?at)。 – trashgod