Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

java - Using a Swing Timer to hide a notification temporarily

I'm using a Swing Timer to make webNotification, a custom JFrame, appear at a certain time. I want the user to have the option of clicking a "Hide" button that dismisses the notification and makes it come back after an hour. How can I achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

javax.swing.Timer has an initial delay; just set it to 60 * 60 * 1000. Your actionPerformed() will be called an hour after invoking start().

Addendum: Here's an example of a button that hide's it's enclosing window for a specified period of time.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...