使用Swing Timer暂时隐藏通知 [英] Using a Swing Timer to hide a notification temporarily

查看:96
本文介绍了使用Swing Timer暂时隐藏通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Swing 计时器来制作 webNotification ,自定义 JFrame ,在某个时间出现。我希望用户可以选择单击隐藏按钮来取消通知,并在一小时后返回。我怎样才能实现这个目标?

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?

推荐答案

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

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

这篇关于使用Swing Timer暂时隐藏通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆