首页 > Java > java教程 > 正文

从JOptionPane启动新Swing窗口:构建动态计时器应用

花韻仙語
发布: 2025-11-21 12:32:23
原创
471人浏览过

从JOptionPane启动新Swing窗口:构建动态计时器应用

本文详细介绍了如何在java swing应用中,利用`joptionpane`对话框作为入口,根据用户选择启动一个新的窗体。教程将演示如何在新窗体中实现一个动态更新的数字时钟,并集成开始/停止计时器、以及根据计时器状态改变显示颜色等功能,同时强调swing应用中事件调度线程(edt)的重要性及`javax.swing.timer`的正确使用。

在Java Swing应用程序开发中,我们经常需要通过一个初始的对话框来引导用户进行操作,例如选择进入不同的功能模块。JOptionPane是实现这一目的的强大工具。本教程将引导您完成一个示例,该示例从一个JOptionPane开始,根据用户的选择来启动一个新的Swing窗体,并在新窗体中展示一个带有计时器控制功能的动态时钟。

1. 核心概念与挑战

在构建此类应用时,主要涉及以下几个关键点:

  • JOptionPane 的使用及返回值处理:JOptionPane.showOptionDialog方法可以显示一个包含自定义选项的对话框,并根据用户的选择返回一个整数值,我们需要根据这个返回值来决定后续操作。
  • Swing应用的线程安全:事件调度线程 (EDT):Swing组件的创建和所有UI更新操作都必须在事件调度线程(EDT)上执行。直接在main方法中进行UI操作可能会导致不可预测的行为。EventQueue.invokeLater()是确保UI操作在EDT上执行的标准方式。
  • 动态UI更新:javax.swing.Timer:为了实现每秒更新一次时间的动态效果,我们需要使用javax.swing.Timer(注意与java.util.Timer的区别),它专为Swing的UI更新设计,其事件回调总是在EDT上执行。
  • 现代日期时间API:使用java.time包(如LocalTime和DateTimeFormatter)来获取和格式化当前时间,这比旧的java.util.Date和SimpleDateFormat更加简洁和安全。

2. 构建主启动逻辑

应用程序的入口点是main方法。在这里,我们首先通过JOptionPane向用户提供“设置”和“关闭”两个选项。

import java.awt.EventQueue;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TimerApplication {
    private static final String SETTINGS = "Settings";
    private static final String CLOSE = "Close";

    public static void main(String[] args) {
        // 显示选项对话框
        int choice = JOptionPane.showOptionDialog(null,
                                                  "选择一个选项",
                                                  "选项对话框",
                                                  JOptionPane.YES_NO_OPTION,
                                                  JOptionPane.QUESTION_MESSAGE,
                                                  null,
                                                  new String[]{SETTINGS, CLOSE},
                                                  SETTINGS);

        // 根据用户选择进行处理
        if (choice == JOptionPane.YES_OPTION) { // 用户选择了“Settings”
            // 尝试设置系统外观(Look and Feel)
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException |
                       IllegalAccessException |
                       InstantiationException |
                       UnsupportedLookAndFeelException x) {
                System.out.println("警告:未能设置系统外观 (已忽略)。");
            }
            // 在EDT上创建并显示新的计时器窗体
            EventQueue.invokeLater(() -> new TimerFrame().buildAndDisplayGui());
        } else { // 用户选择了“Close”或关闭了对话框
            System.exit(0); // 退出应用程序
        }
    }
}
登录后复制

解释:

豆绘AI
豆绘AI

豆绘AI是国内领先的AI绘图与设计平台,支持照片、设计、绘画的一键生成。

豆绘AI 485
查看详情 豆绘AI
  • JOptionPane.showOptionDialog方法用于显示一个自定义选项的对话框。
    • null:父组件,如果为null,对话框将居中显示在屏幕上。
    • "选择一个选项":对话框中显示的消息。
    • "选项对话框":对话框的标题。
    • JOptionPane.YES_NO_OPTION:指定对话框按钮类型,这里用于返回YES_OPTION或NO_OPTION。
    • JOptionPane.QUESTION_MESSAGE:指定对话框图标类型。
    • null:自定义图标。
    • new String[]{SETTINGS, CLOSE}:自定义按钮文本数组。
    • SETTINGS:默认选中的按钮。
  • 当用户点击“Settings”按钮时,showOptionDialog返回JOptionPane.YES_OPTION。
  • 在启动新窗体之前,我们尝试设置系统默认的“Look and Feel”,以使应用程序界面更符合操作系统风格。
  • 最重要的是,new TimerFrame().buildAndDisplayGui()被包装在EventQueue.invokeLater()中。这确保了TimerFrame的创建和显示操作都在EDT上执行,保证了Swing应用程序的线程安全性。

3. 设计计时器窗口 (TimerFrame)

新窗体 (TimerFrame,这里为了避免与javax.swing.Timer冲突,使用TimerFrame作为类名) 将包含一个显示时间的JLabel和控制计时器的“开始”/“停止”按钮。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.Timer; // 注意这里是javax.swing.Timer

class TimerFrame {
    private JButton startButton;
    private JButton stopButton;
    private JFrame frame;
    private JLabel theWatch;
    private Timer timer; // Swing Timer

    public TimerFrame() {
        // 初始化Swing Timer,每1000毫秒(1秒)触发一次
        timer = new Timer(1000, this::updateTimer);
        // 第一次触发立即执行,然后每秒执行
        timer.setInitialDelay(0);
    }

    public void buildAndDisplayGui() {
        frame = new JFrame("计时器应用");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 关闭窗口时退出应用

        // 创建显示时间的标签
        theWatch = new JLabel(getCurrentTime(), SwingConstants.CENTER);
        theWatch.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30)); // 添加边距
        theWatch.setForeground(Color.red); // 初始颜色为红色
        theWatch.setToolTipText("计时器当前已停止。"); // 停止时的提示信息
        frame.add(theWatch, BorderLayout.CENTER); // 将标签添加到窗体中央

        frame.add(createButtons(), BorderLayout.PAGE_END); // 将按钮面板添加到窗体底部
        frame.pack(); // 根据组件的首选大小调整窗体大小
        frame.setLocationByPlatform(true); // 窗体位置由平台决定
        frame.setVisible(true); // 显示窗体
    }

    private JPanel createButtons() {
        JPanel panel = new JPanel();
        startButton = new JButton("开始");
        startButton.setMnemonic(KeyEvent.VK_A); // 设置助记符 (Alt+A)
        startButton.setToolTipText("启动计时器。");
        startButton.addActionListener(this::startTimer); // 绑定启动事件
        panel.add(startButton);

        stopButton = new JButton("停止");
        stopButton.setMnemonic(KeyEvent.VK_O); // 设置助记符 (Alt+O)
        stopButton.setToolTipText("停止计时器。");
        stopButton.addActionListener(this::stopTimer); // 绑定停止事件
        stopButton.setEnabled(false); // 初始时停止按钮禁用
        panel.add(stopButton);
        return panel;
    }

    // 获取当前时间并格式化
    private String getCurrentTime() {
        return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss", Locale.ENGLISH));
    }

    // 启动计时器
    private void startTimer(ActionEvent event) {
        theWatch.setToolTipText(null); // 清除提示信息
        theWatch.setForeground(Color.black); // 启动时颜色变为黑色
        startButton.setEnabled(false); // 禁用开始按钮
        timer.start(); // 启动Swing Timer
        stopButton.setEnabled(true); // 启用停止按钮
    }

    // 停止计时器
    private void stopTimer(ActionEvent event) {
        timer.stop(); // 停止Swing Timer
        theWatch.setForeground(Color.red); // 停止时颜色变为红色
        theWatch.setToolTipText("计时器当前已停止。"); // 设置停止提示信息
        startButton.setEnabled(true); // 启用开始按钮
        stopButton.setEnabled(false); // 禁用停止按钮
    }

    // 更新时间标签
    private void updateTimer(ActionEvent event) {
        theWatch.setText(getCurrentTime());
    }
}
登录后复制

4. 实现动态时间显示与控制

  • javax.swing.Timer:在TimerFrame的构造函数中,我们创建了一个javax.swing.Timer实例。它被配置为每1000毫秒触发一次ActionEvent,并通过方法引用this::updateTimer将事件处理委托给updateTimer方法。timer.setInitialDelay(0)确保计时器启动后立即更新一次时间。
  • getCurrentTime():这个辅助方法使用LocalTime.now()获取当前时间,并通过DateTimeFormatter.ofPattern("HH:mm:ss", Locale.ENGLISH)将其格式化为“HH:mm:ss”字符串。
  • startTimer() 和 stopTimer():这两个方法分别处理“开始”和“停止”按钮的点击事件
    • 它们控制timer的启动和停止。
    • 它们还会更新theWatch标签的颜色(启动时为黑色,停止时为红色)、工具提示文本,并切换“开始”和“停止”按钮的启用/禁用状态,以提供良好的用户体验。
  • updateTimer():这个方法由timer每秒调用一次,负责获取最新的时间并更新theWatch标签的文本。

5. 完整代码示例

为了运行上述代码,您需要将TimerApplication.java和TimerFrame.java(或将TimerFrame作为内部类)放在同一个项目中。

// TimerApplication.java
import java.awt.EventQueue;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TimerApplication {
    private static final String SETTINGS = "Settings";
    private static final String CLOSE = "Close";

    public static void main(String[] args) {
        int choice = JOptionPane.showOptionDialog(null,
                                                  "选择一个选项",
                                                  "选项对话框",
                                                  JOptionPane.YES_NO_OPTION,
                                                  JOptionPane.QUESTION_MESSAGE,
                                                  null,
                                                  new String[]{SETTINGS, CLOSE},
                                                  SETTINGS);

        if (choice == JOptionPane.YES_OPTION) {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException |
                       IllegalAccessException |
                       InstantiationException |
                       UnsupportedLookAndFeelException x) {
                System.out.println("警告:未能设置系统外观 (已忽略)。");
            }
            EventQueue.invokeLater(() -> new TimerFrame().buildAndDisplayGui());
        } else {
            System.exit(0);
        }
    }
}

// TimerFrame.java (可以作为单独文件或 TimerApplication 的内部类)
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.Timer;

class TimerFrame {
    private JButton startButton;
    private JButton stopButton;
    private JFrame frame;
    private JLabel theWatch;
    private Timer timer;

    public TimerFrame() {
        timer = new Timer(1000, this::updateTimer);
        timer.setInitialDelay(0); // 确保计时器启动后立即更新一次
    }

    public void buildAndDisplayGui() {
        frame = new JFrame("计时器应用");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        theWatch = new JLabel(getCurrentTime(), SwingConstants.CENTER);
        theWatch.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));
        theWatch.setForeground(Color.red);
        theWatch.setToolTipText("计时器当前已停止。");
        frame.add(theWatch, BorderLayout.CENTER);

        frame.add(createButtons(), BorderLayout.PAGE_END);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JPanel createButtons() {
        JPanel panel = new JPanel();
        startButton = new JButton("开始");
        startButton.setMnemonic(KeyEvent.VK_A);
        startButton.setToolTipText("启动计时器。");
        startButton.addActionListener(this::startTimer);
        panel.add(startButton);

        stopButton = new JButton("停止");
        stopButton.setMnemonic(KeyEvent.VK_O);
        stopButton.setToolTipText("停止计时器。");
        stopButton.addActionListener(this::stopTimer);
        stopButton.setEnabled(false);
        panel.add(stopButton);
        return panel;
    }

    private String getCurrentTime() {
        return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss", Locale.ENGLISH));
    }

    private void startTimer(ActionEvent event) {
        theWatch.setToolTipText(null);
        theWatch.setForeground(Color.black);
        startButton.setEnabled(false);
        timer.start();
        stopButton.setEnabled(true);
    }

    private void stopTimer(ActionEvent event) {
        timer.stop();
        theWatch.setForeground(Color.red);
        theWatch.setToolTipText("计时器当前已停止。");
        startButton.setEnabled(true);
        stopButton.setEnabled(false);
    }

    private void updateTimer(ActionEvent event) {
        theWatch.setText(getCurrentTime());
    }
}
登录后复制

6. 注意事项与最佳实践

  • 线程安全:始终牢记Swing组件的创建和修改必须在EDT上进行。EventQueue.invokeLater()是确保这一点的关键。
  • 资源管理:JFrame的setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)确保在关闭主窗口时应用程序彻底退出。对于更复杂的应用,可能需要更精细的关闭策略。
  • 可扩展性:本示例中的颜色切换是硬编码的(红/黑),如果需要用户选择颜色,可以引入JColorChooser。
  • 代码组织:将不同的功能模块(如TimerApplication和TimerFrame)分离到不同的类中,有助于提高代码的可读性和维护性。
  • 用户体验:通过设置按钮的ToolTipText和Mnemonic(助记符),可以增强应用程序的用户友好性。

总结

本教程演示了如何利用JOptionPane作为应用程序的启动入口,并根据用户选择动态地创建和显示一个新的Swing窗体。通过集成javax.swing.Timer和现代日期时间API,我们成功实现了一个带有开始/停止功能的动态数字时钟。理解并正确应用EDT原则是开发健壮Swing应用程序的关键。

以上就是从JOptionPane启动新Swing窗口:构建动态计时器应用的详细内容,更多请关注php中文网其它相关文章!

Windows激活工具
Windows激活工具

Windows激活工具是正版认证的激活工具,永久激活,一键解决windows许可证即将过期。可激活win7系统、win8.1系统、win10系统、win11系统。下载后先看完视频激活教程,再进行操作,100%激活成功。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号