
本教程详细介绍了如何使用java swing中的`joptionpane`来创建交互式启动对话框,并根据用户选择打开新的`jframe`窗口。新窗口内将演示如何利用`javax.swing.timer`实现实时时间显示,并提供按钮控制时间的启动与停止,同时伴随ui元素的动态颜色变化,确保所有ui操作都在事件调度线程(edt)中安全执行。
在Java Swing应用程序开发中,我们经常需要通过对话框与用户进行初步交互,并根据用户的选择来启动不同的功能模块或显示不同的界面。JOptionPane是实现这一目标的高效工具。本教程将引导您完成一个示例,该示例首先弹出一个选项对话框,允许用户选择“设置”或“关闭”;选择“设置”后,将打开一个新窗口,该窗口会实时显示当前时间,并提供启动和停止计时器的功能,同时动态改变显示时间的文本颜色。
在深入实现之前,了解以下核心Swing概念至关重要:
我们将通过构建一个名为 StopWhat 的类来演示整个过程。
应用程序的启动点是 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);
}
}
}StopWhat 类需要一个方法来构建并显示我们的计时器窗口。
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); // 显示窗口
}
// ... 其他方法 ...
}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());
}
// ... 其他方法 ...
}我们需要“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); // 停止按钮禁用
}
// ... 其他方法 ...
}将以上所有代码片段组合,形成完整的 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);
}
}
}本教程演示了如何利用 JOptionPane 作为应用程序的入口点,根据用户选择动态启动不同的Swing窗口。我们深入探讨了如何在新窗口中实现一个实时更新的计时器,并通过 javax.swing.Timer 配合 LocalTime 和 DateTimeFormatter 实现时间显示。同时,通过“Start”和“Stop”按钮控制计时器的生命周期,并动态调整UI元素的颜色和状态。整个过程中,我们强调了在Swing应用程序中遵循EDT规则的重要性,并介绍了如何使用 EventQueue.invokeLater() 来确保UI操作的线程安全。掌握这些技术将帮助您构建更具交互性和响应性的Java Swing应用程序。
以上就是Java Swing中利用JOptionPane启动新窗口及动态时间显示教程的详细内容,更多请关注php中文网其它相关文章!
Windows激活工具是正版认证的激活工具,永久激活,一键解决windows许可证即将过期。可激活win7系统、win8.1系统、win10系统、win11系统。下载后先看完视频激活教程,再进行操作,100%激活成功。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号