使用Swing Timer暂时隐藏通知

时间:2010-12-07 04:46:21

标签: java swing

我正在使用Swing Timer制作webNotification,自定义JFrame,会在特定时间出现。我希望用户可以选择单击“隐藏”按钮来取消通知,并在一小时后返回。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:7)

javax.swing.Timer有一个初始延迟;只需将其设置为60 * 60 * 1000即可。调用actionPerformed()后,您的start()将在一小时后调用。

附录:这是一个按钮的示例,它隐藏了它在指定时间段内的封闭窗口。

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();
            }
        });
    }
}