首页 > 编程语言 >Java定时弹窗提示与展示图片

Java定时弹窗提示与展示图片

时间:2023-07-28 12:55:37浏览次数:36  
标签:Java java swing JPanel import new 定时 public 弹窗

自顶向下介绍,首先是定时弹窗功能,可以用Java自带的ScheduledExecutorService库完成函数调用。

package healthReminder;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TimerScheduledTask {
    // how to write a timer task?
    // https://blog.csdn.net/qq_39731011/article/details/123332641
    public static void main(String[] args) {
        ScheduledExecutorService ses = Executors.newScheduledThreadPool(2);
        ses.scheduleAtFixedRate(()->{
            TipAfterAWhile.showAlarm();
        }, 1, 3000, TimeUnit.SECONDS);
    }
}

其次是所被调用的函数,即弹窗。

窗口布局为:标题、文本区、勾选框、两个按键,其中一个按键同右上角一样功能为关闭,另一个案件打开一张图片。

该程序为设计窗口布局和功能。

package healthReminder;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;

public class TipAfterAWhile extends JDialog {

    private static final long serialVersionUID = -6493879146336970741L;
    private final JPanel contentPanel = new JPanel();

    /**
     * Launch the application.
     */
    public static void showAlarm() {
        try {
            // UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (Throwable e) {
            e.printStackTrace();
        }

        try {
            TipAfterAWhile dialog = new TipAfterAWhile();
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            dialog.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public TipAfterAWhile() {
        setTitle("Health Reminder");
        setBounds(100, 100, 480, 300);
        getContentPane().setLayout(new BorderLayout());
        contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        getContentPane().add(contentPanel, BorderLayout.CENTER);
        contentPanel.setLayout(new BorderLayout(0, 0));
        
        {
            JPanel panel = new JPanel();
            contentPanel.add(panel, BorderLayout.NORTH);
            {
                JLabel label = new JLabel("Stand up and Relax!");
                label.setFont(new Font("微软雅黑", Font.PLAIN, 16));
                panel.add(label);
            }
        }

        {
            JPanel panel = new JPanel();
            contentPanel.add(panel, BorderLayout.SOUTH);
            panel.setLayout(new BorderLayout(0, 0));
            {
                JCheckBox checkBox = new JCheckBox("Don't Prompt Again!");
                checkBox.setFont(new Font("微软雅黑", Font.PLAIN, 16));
                panel.add(checkBox);
            }
        }
        {
            JPanel panel = new JPanel();
            contentPanel.add(panel, BorderLayout.WEST);
        }
        {
            JPanel panel = new JPanel();
            contentPanel.add(panel, BorderLayout.EAST);
        }
        {
            JScrollPane scrollPane = new JScrollPane();
            contentPanel.add(scrollPane, BorderLayout.CENTER);
            {
                JTextArea textArea = new JTextArea();
                textArea.setFont(new Font("微软雅黑", Font.PLAIN, 14));
                textArea.setLineWrap(true);
                textArea
                        .setText("You have been working for an hour, why not stand up and have a relax?");
                scrollPane.setViewportView(textArea);
            }
        }
        {
            JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
            getContentPane().add(buttonPane, BorderLayout.SOUTH);

            {
                JButton cancelButton = new JButton("Concel");
                cancelButton.setFont(new Font("微软雅黑", Font.PLAIN, 16));
                cancelButton.setActionCommand("Cancel");
                cancelButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        // dispose();  // 也可关闭但不是真的关闭
                        System.exit(0);
                    }
                });
                buttonPane.add(cancelButton);
            }
            {
                JButton okButton = new JButton("Give me a setu!");
                okButton.setFont(new Font("微软雅黑", Font.PLAIN, 16));
                okButton.setActionCommand("OK");
                okButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        new ShowAPictureOnJF();
                    }
                });
                buttonPane.add(okButton);
                getRootPane().setDefaultButton(okButton);
            }
        }
    }
}

接着是打开一张图片的功能(作为按键事件监听器的调用方法),该方法会访问下述自定义JPanel子类,BackgroundPanel,功能是展示图片的。

package healthReminder;

import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;

public class BackgroundPanel extends JPanel {
    
    private static final long serialVersionUID = 1L;
    /**
     * 背景图片
     */
    private Image image;
    
    /**
     * 构造方法
     */
    public BackgroundPanel() {
        super();
        setOpaque(false);
        setLayout(null);
    }
    
    /**
     * 设置图片的方法
     */
    public void setImage(Image image) {
        this.image = image;
    }
    
    @Override
    protected void paintComponent(Graphics g) {// 重写绘制组件外观
        if (image != null) {
            g.drawImage(image, 0, 0, this);// 绘制图片与组件大小相同
            // System.out.println("repaint!");
        }
        super.paintComponent(g);// 执行超类方法
    }
}

最后一个功能,设计图片所用到的弹窗,将作为按键的监听器调用方法:

package healthReminder;

import java.awt.BorderLayout;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ShowAPictureOnJF extends JFrame {

    private static final long serialVersionUID = 1L;
    
    private final JPanel contentPane = new JPanel();
    public ShowAPictureOnJF() {
        this.setTitle("relax");
        this.setBounds(100, 100, 960, 540);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        this.setVisible(true);
        String ppath = this.returnFileRandomly("D:/kingz/ANIME");
        System.out.println(ppath);
        setContentPane(this.contentPane);
        contentPane.setLayout(new BorderLayout(0, 0));
        BackgroundPanel backgroundPanel = new BackgroundPanel();// 创建背景面板
        try {
            Image img1 = ImageIO.read(new File(ppath));
            backgroundPanel.setImage(img1);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // backgroundPanel.setImage(getToolkit().getImage(
        //         getClass().getResource(ppath)));// 设置面板背景图片
        
        contentPane.add(backgroundPanel);// 把背景面板添加到窗体内容面板
    }

    // 返回某文件夹下随机一张图片
    private String returnFileRandomly(String dpath) {
        File directory = new File(dpath);
        File[] flist = directory.listFiles();
        int fllen = flist.length;
        if (flist == null || fllen == 0) {
            return null;
        }
        System.out.println("this directory has "+fllen+" pictures.");
        ArrayList<String> pngjpglist = new ArrayList<String>();
        for (File f : flist) {
            String fname = f.getName();
            if (f.isDirectory() || !((fname.substring(fname.length()-3)).equals("jpg")
                     || (fname.substring(fname.length()-3)).equals("png"))) {
                continue;
            }else {
                // System.out.println(fname.substring(fname.length()-3));
                pngjpglist.add(fname);
            }
        }
        System.out.println("the jpg or png picture's number is "+pngjpglist.size());
        Random rd = new Random();
        int iterNum = rd.nextInt(pngjpglist.size());
        int indexCount = 0;
        Iterator<String> it = pngjpglist.iterator();
        while (it.hasNext()) {
            String string = (String) it.next();
            indexCount++;
            if (indexCount>=iterNum) {
                return dpath + "/" + string;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        new ShowAPictureOnJF();
        // System.out.println(returnFileRandomly("D:\\kingz\\ANIME"));
    }
}
end

标签:Java,java,swing,JPanel,import,new,定时,public,弹窗
From: https://www.cnblogs.com/zhaoke271828/p/17587304.html

相关文章

  • .Net6实现定时任务
    首先创建一个类Background实现代码:usingMicrosoft.Extensions.Hosting;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceSmartMedicalCare.Web{publicclassBackground:IHostedService,......
  • centos俩个java版本共存
    环境背景centos7.9,java8,java11,Jenkins2.401.3本来想装老版的jenkins,但是各种插件装不上,而新版的jenkins又依赖java11,但maven的打包又是java8的,所以必须要折腾下了步骤下载jdk8,jdk11安装包略解压改名[root@VM-4-12-opencloudoshome]#lsjdk-11.0.18_linux-x64_bin.tar.g......
  • Java中常见的网络通信模型
    目前最近仔学习RocketMQ以及Dubbo还有Spring5框架的底层部分,了解到这些技术的底层都是采用的Netty作为底层的通信的软件,于是便需要详细了解以下网络中的通信的模型以及Netty的通信模型原理。本篇是通过Redis以及Netty进行网络通信模型的逐渐演化来进行介绍,其中还会夹杂着一些比......
  • Java复制
    将一个对象的引用复制给另外一个对象,一共有三种方式。第一种是直接赋值,第二种方式是浅拷贝,第三种是深拷贝。所以大家知道了哈,这三种概念都是为了拷贝对象。直接赋值复制直接赋值。在Java中,Aa1=a2,我们需要理解的是这实际上复制的是引用,也就是说a1和a2指向的是同一个对象。因......
  • java项目更改jdk版本出现问题
    这里demo中的java版本出了点问题,将jdk17改为jdk11打开项目结构设置Project中的SDK和Languagelevel为jdk11。一、java:错误:不支持发行版本17 打开settings中的JavaCompiler修改module中项目的java版本二、java:错误:无效的源发行版:17 打开项目结构,找到下图界面修改J......
  • java面试题带链接
    下面是在网下下载的,不知道哪来的了,发出来方便查看一、Java基础1.String类为什么是final的。https://www.zhihu.com/question/313455922.HashMap的源码,实现原理,底层结构。get(key)方法时获取key的hash值,计算hash&(n-1)得到在链表数组中的位置first=tab[hash&(n-1)],先判断first的k......
  • 要实现Java中的Excel导入导出功能,可以使用Apache POI库。
    下面是一个简单的示例:导入Excel文件:importorg.apache.poi.ss.usermodel.*;importorg.apache.poi.xssf.usermodel.XSSFWorkbook;importjava.io.FileInputStream;importjava.io.IOException;publicclassExcelImportExample{publicstaticvoidmain(String[]args){......
  • Java 大后端各种架构图汇总
    1.java类加载器架构2.JVM架构3.Java技术体系4.线程运行架构5.Java体系(编译与运行)结构6.JMS技术架构7.JMX技术架构8.Spring架构9.Hibernate架构10.ibatis架构11.Struts2架构12.Struts1架构13.JBPM14.EJB技术架......
  • SHA1签名算法,JAVA和C#
    java:publicstaticvoidmain(String[]args)throwsNoSuchAlgorithmException{Stringtoken="31a4a1aa-cffc-4aca-9ef6-0497edf7fbed";Stringnonce="Rzem0rlz19e6GZuZuFKyDzaxiS4baaqn8uvxVnntXKS";Stringtimestamp="1646......
  • JavaAPI
    Scanner类该类是文本扫描类构造方法//创建一个扫描输入内容的扫描器Scannersc=newScanner(Sytem.in);//扫描文本内容的扫描器Filefile=newFile("C:\\Users\\Administrator\\Desktop\\test.txt");Scannersc=newScanner(file);类中方法//从键盘中读取内容int......