首页 > Java > java教程 > 正文

Java Swing中利用JOptionPane启动新窗口及动态时间显示教程

霞舞
发布: 2025-11-21 15:30:18
原创
719人浏览过

Java Swing中利用JOptionPane启动新窗口及动态时间显示教程

本教程详细介绍了如何使用java swing中的`joptionpane`来创建交互式启动对话框,并根据用户选择打开新的`jframe`窗口。新窗口内将演示如何利用`javax.swing.timer`实现实时时间显示,并提供按钮控制时间的启动与停止,同时伴随ui元素的动态颜色变化,确保所有ui操作都在事件调度线程(edt)中安全执行。

在Java Swing应用程序开发中,我们经常需要通过对话框与用户进行初步交互,并根据用户的选择来启动不同的功能模块或显示不同的界面。JOptionPane是实现这一目标的高效工具。本教程将引导您完成一个示例,该示例首先弹出一个选项对话框,允许用户选择“设置”或“关闭”;选择“设置”后,将打开一个新窗口,该窗口会实时显示当前时间,并提供启动和停止计时器的功能,同时动态改变显示时间的文本颜色。

核心概念概览

在深入实现之前,了解以下核心Swing概念至关重要:

  1. JOptionPane.showOptionDialog(): 用于显示一个包含自定义选项按钮的对话框,并返回用户选择的选项索引。
  2. JFrame: Swing应用程序中的顶级窗口容器,用于承载所有UI组件。
  3. javax.swing.Timer: 专门用于Swing应用程序的计时器,它在事件调度线程(EDT)上触发事件,是更新UI的推荐方式。
  4. 事件调度线程(EDT): Swing应用程序的所有UI组件创建和更新操作都必须在EDT上执行,以避免线程安全问题。EventQueue.invokeLater()是确保代码在EDT上运行的标准方法。
  5. ActionListener: 用于响应组件(如按钮、计时器)触发的动作事件。Java 8及更高版本中,可以使用方法引用或Lambda表达式简化其实现。
  6. LocalTime 和 DateTimeFormatter: Java 8引入的日期时间API,用于获取和格式化当前时间。

实现步骤

我们将通过构建一个名为 StopWhat 的类来演示整个过程。

1. 创建主入口对话框

应用程序的启动点是 main 方法,在这里我们将使用 JOptionPane.showOptionDialog() 来呈现初始选择。

立即学习Java免费学习笔记(深入)”;

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

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

    // ... 其他类成员和方法 ...

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

        // 根据用户选择进行处理
        if (choice == JOptionPane.YES_OPTION) { // 如果用户选择了“Settings”
            // 尝试设置系统外观,提升用户体验
            String slaf = UIManager.getSystemLookAndFeelClassName();
            try {
                UIManager.setLookAndFeel(slaf);
            } catch (ClassNotFoundException |
                     IllegalAccessException |
                     InstantiationException |
                     UnsupportedLookAndFeelException x) {
                System.out.println("WARNING (ignored): Failed to set [System] look-and-feel.");
            }
            // 在EDT上创建并显示新窗口
            EventQueue.invokeLater(() -> new StopWhat().buildAndDisplayGui());
        } else { // 如果用户选择了“Close”或关闭了对话框
            System.exit(0);
        }
    }
}
登录后复制
  • JOptionPane.showOptionDialog() 的返回值是用户点击按钮的索引。在本例中,"Settings" 对应 JOptionPane.YES_OPTION。
  • UIManager.setLookAndFeel() 用于将应用程序的外观设置为操作系统默认样式,使界面更具原生感。
  • EventQueue.invokeLater() 是关键。它确保 buildAndDisplayGui() 方法(负责创建和显示新窗口)在EDT上执行,避免了潜在的UI线程问题。

2. 构建新窗口 (JFrame)

StopWhat 类需要一个方法来构建并显示我们的计时器窗口。

Alkaid.art
Alkaid.art

专门为Phtoshop打造的AIGC绘画插件

Alkaid.art 153
查看详情 Alkaid.art
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.Timer; // 注意这里是javax.swing.Timer

public class StopWhat {
    // ... 静态常量和main方法 ...

    private JFrame frame;
    private JLabel theWatch;
    private Timer timer; // Swing Timer实例

    public StopWhat() {
        // 初始化Swing Timer,每1000毫秒(1秒)触发一次,并立即开始
        timer = new Timer(1000, this::updateTimer);
        timer.setInitialDelay(0); // 确保第一次触发是立即的
    }

    private void buildAndDisplayGui() {
        frame = new JFrame("Timer App");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置关闭操作

        // 创建显示时间的JLabel
        theWatch = new JLabel(getCurrentTime(), SwingConstants.CENTER);
        theWatch.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30)); // 添加内边距
        theWatch.setForeground(Color.red); // 初始颜色为红色
        theWatch.setToolTipText("Timer is currently stopped."); // 提示文本
        frame.add(theWatch, BorderLayout.CENTER); // 将标签添加到窗口中央

        frame.add(createButtons(), BorderLayout.PAGE_END); // 添加按钮面板到窗口底部
        frame.pack(); // 调整窗口大小以适应内容
        frame.setLocationByPlatform(true); // 让操作系统决定窗口位置
        frame.setVisible(true); // 显示窗口
    }

    // ... 其他方法 ...
}
登录后复制
  • JFrame 被初始化,并设置了默认的关闭操作。
  • JLabel theWatch 用于显示时间,并设置了初始字体颜色为红色,表示计时器处于停止状态。
  • BorderLayout 是 JFrame 内容面板的默认布局管理器,我们将其用于放置时间标签和按钮面板。
  • timer.setInitialDelay(0) 确保计时器在启动后立即触发第一次事件,而不是等待第一个延迟周期。

3. 实现动态时间显示 (Swing Timer)

javax.swing.Timer 是实现周期性UI更新的核心。

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

// ... StopWhat类的其他部分 ...

public class StopWhat {
    // ... 成员变量和构造函数 ...

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

    private void updateTimer(ActionEvent event) {
        // 计时器触发时更新JLabel的文本
        theWatch.setText(getCurrentTime());
    }

    // ... 其他方法 ...
}
登录后复制
  • getCurrentTime() 方法利用 LocalTime.now() 获取当前时间,并通过 DateTimeFormatter 格式化为 "HH:mm:ss" 字符串。
  • updateTimer() 方法是 javax.swing.Timer 的 ActionListener。每当计时器触发时,它会调用 getCurrentTime() 并更新 theWatch 标签的文本。

4. 添加控制按钮

我们需要“Start”和“Stop”按钮来控制计时器的运行。

import java.awt.event.KeyEvent;
import javax.swing.JButton;

// ... StopWhat类的其他部分 ...

public class StopWhat {
    // ... 成员变量和构造函数 ...

    private JButton startButton;
    private JButton stopButton;

    private JPanel createButtons() {
        JPanel panel = new JPanel();
        startButton = new JButton("Start");
        startButton.setMnemonic(KeyEvent.VK_A); // 设置快捷键 Alt+A
        startButton.setToolTipText("Starts the timer.");
        startButton.addActionListener(this::startTimer); // 使用方法引用添加监听器
        panel.add(startButton);

        stopButton = new JButton("Stop");
        stopButton.setMnemonic(KeyEvent.VK_O); // 设置快捷键 Alt+O
        stopButton.setToolTipText("Stops the timer.");
        stopButton.addActionListener(this::stopTimer); // 使用方法引用添加监听器
        stopButton.setEnabled(false); // 初始状态下停止按钮不可用
        panel.add(stopButton);
        return panel;
    }

    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("Timer is currently stopped."); // 设置提示文本
        startButton.setEnabled(true); // 启动按钮启用
        stopButton.setEnabled(false); // 停止按钮禁用
    }

    // ... 其他方法 ...
}
登录后复制
  • createButtons() 方法创建了一个 JPanel 来容纳“Start”和“Stop”按钮。
  • 每个按钮都添加了 ActionListener,使用方法引用 (this::startTimer, this::stopTimer) 来指向相应的处理方法。
  • startButton 和 stopButton 的 setEnabled() 状态在计时器启动和停止时进行切换,以提供清晰的用户反馈。
  • 当计时器停止时,时间标签颜色为红色;启动时,颜色变为黑色。

完整示例代码

将以上所有代码片段组合,形成完整的 StopWhat 类:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
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.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.Timer; // 明确指出是javax.swing.Timer
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

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

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

    public StopWhat() {
        // 初始化Swing Timer,每1000毫秒触发一次,并立即触发第一次事件
        timer = new Timer(1000, this::updateTimer);
        timer.setInitialDelay(0);
    }

    private void buildAndDisplayGui() {
        frame = new JFrame("Timer App");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 创建并配置显示时间的JLabel
        theWatch = new JLabel(getCurrentTime(), SwingConstants.CENTER);
        theWatch.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));
        theWatch.setForeground(Color.red); // 初始颜色为红色,表示停止状态
        theWatch.setToolTipText("Timer is currently stopped.");
        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();

        // 创建并配置“Start”按钮
        startButton = new JButton("Start");
        startButton.setMnemonic(KeyEvent.VK_A); // Alt+A 快捷键
        startButton.setToolTipText("Starts the timer.");
        startButton.addActionListener(this::startTimer);
        panel.add(startButton);

        // 创建并配置“Stop”按钮
        stopButton = new JButton("Stop");
        stopButton.setMnemonic(KeyEvent.VK_O); // Alt+O 快捷键
        stopButton.setToolTipText("Stops the timer.");
        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("Timer is currently stopped.");
        startButton.setEnabled(true);
        stopButton.setEnabled(false);
    }

    private void updateTimer(ActionEvent event) {
        // 计时器事件:更新时间显示
        theWatch.setText(getCurrentTime());
    }

    public static void main(String[] args) {
        // 显示初始选项对话框
        int choice = JOptionPane.showOptionDialog(null,
                                                  "Choose option",
                                                  "Option dialog",
                                                  JOptionPane.YES_NO_OPTION,
                                                  JOptionPane.QUESTION_MESSAGE,
                                                  null,
                                                  new String[]{SETTINGS, CLOSE},
                                                  SETTINGS);
        if (choice == JOptionPane.YES_OPTION) {
            // 设置系统外观
            String slaf = UIManager.getSystemLookAndFeelClassName();
            try {
                UIManager.setLookAndFeel(slaf);
            }
            catch (ClassNotFoundException |
                   IllegalAccessException |
                   InstantiationException |
                   UnsupportedLookAndFeelException x) {
                System.out.println("WARNING (ignored): Failed to set [System] look-and-feel.");
            }
            // 在EDT上启动GUI
            EventQueue.invokeLater(() -> new StopWhat().buildAndDisplayGui());
        }
        else {
            // 用户选择“Close”或关闭对话框,则退出程序
            System.exit(0);
        }
    }
}
登录后复制

注意事项与最佳实践

  1. 事件调度线程 (EDT) 的重要性: 任何对Swing UI组件的创建、修改或查询操作都必须在EDT上执行。否则,可能导致UI冻结、不响应或出现不可预测的并发问题。EventQueue.invokeLater() 是将任务提交到EDT的正确方式。
  2. 选择正确的计时器: 对于Swing应用程序,务必使用 javax.swing.Timer。它保证其事件监听器在EDT上执行,从而安全地更新UI。避免使用 java.util.Timer,因为它在单独的线程中运行,需要额外的同步机制才能安全地与Swing组件交互。
  3. 方法引用: Java 8引入的方法引用(如 this::updateTimer)提供了一种简洁的方式来表示Lambda表达式,尤其适用于只有一个抽象方法的接口(如 ActionListener),使代码更具可读性。
  4. 布局管理器: 熟悉并合理使用Swing的布局管理器(如 BorderLayout, FlowLayout, GridLayout, GridBagLayout 等)对于创建响应式和美观的界面至关重要。本例中 JFrame 默认使用 BorderLayout。
  5. 错误处理: 在设置 LookAndFeel 时,建议捕获可能发生的异常,以防止程序因外观设置失败而崩溃。
  6. 用户体验: 通过 setToolTipText() 提供提示信息,通过 setMnemonic() 设置快捷键,以及动态启用/禁用按钮,都能显著提升用户体验。

总结

本教程演示了如何利用 JOptionPane 作为应用程序的入口点,根据用户选择动态启动不同的Swing窗口。我们深入探讨了如何在新窗口中实现一个实时更新的计时器,并通过 javax.swing.Timer 配合 LocalTime 和 DateTimeFormatter 实现时间显示。同时,通过“Start”和“Stop”按钮控制计时器的生命周期,并动态调整UI元素的颜色和状态。整个过程中,我们强调了在Swing应用程序中遵循EDT规则的重要性,并介绍了如何使用 EventQueue.invokeLater() 来确保UI操作的线程安全。掌握这些技术将帮助您构建更具交互性和响应性的Java Swing应用程序。

以上就是Java Swing中利用JOptionPane启动新窗口及动态时间显示教程的详细内容,更多请关注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号