You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Swing技术问题:如何通过JOptionPane打开新窗体并实现计时功能

解决Java Swing中Settings按钮打开新窗体及功能实现问题

首先,你的代码没有处理JOptionPane.showOptionDialog的返回值,所以点击Settings后没有任何动作。下面是完整的实现代码,包含所有作业要求的功能:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimerApp extends JFrame {
    private JLabel timeLabel;
    private javax.swing.Timer updateTimer;
    private boolean isRed = false;
    private Color defaultColor;

    public TimerApp() {
        // 初始化窗体设置
        this.setTitle("Timer Settings");
        this.setSize(300, 200);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // 关闭此窗体不退出整个程序
        this.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 20));

        // 1. 初始化时间标签
        timeLabel = new JLabel();
        timeLabel.setFont(new Font("Arial", Font.BOLD, 24));
        defaultColor = timeLabel.getForeground();
        this.add(timeLabel);

        // 初始化时间更新Timer,每秒触发一次
        updateTimer = new javax.swing.Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateTime();
            }
        });
        updateTimer.setInitialDelay(0); // 立即激活
        updateTimer.start();

        // 2. 颜色切换按钮
        JButton colorBtn = new JButton("切换标签颜色");
        colorBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (isRed) {
                    timeLabel.setForeground(defaultColor);
                } else {
                    timeLabel.setForeground(Color.RED);
                }
                isRed = !isRed;
            }
        });
        this.add(colorBtn);

        // 3. 停止按钮
        JButton stopBtn = new JButton("Stop");
        stopBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateTimer.stop();
            }
        });
        this.add(stopBtn);

        // 重启按钮
        JButton restartBtn = new JButton("Restart");
        restartBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateTimer.start();
                updateTime(); // 立即更新一次时间
            }
        });
        this.add(restartBtn);
    }

    // 更新时间标签的方法
    private void updateTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        timeLabel.setText(sdf.format(new Date()));
    }

    public static void main(String[] args) {
        // 在EDT线程中运行Swing组件
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                // 弹出选项对话框
                int option = JOptionPane.showOptionDialog(
                        null,
                        "Choose option",
                        "Option dialog",
                        JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE,
                        null,
                        new String[]{"Settings", "Close"},
                        null
                );

                // 处理用户选择
                if (option == 0) { // 点击了Settings
                    TimerApp timerFrame = new TimerApp();
                    timerFrame.setVisible(true);
                } else if (option == 1) { // 点击了Close
                    System.exit(0);
                }
            }
        });
    }
}

关键修改说明:

  1. 处理JOptionPane返回值:通过判断option的值(0对应Settings,1对应Close),在用户选择Settings时创建并显示Timer窗体。
  2. 使用Swing Timer:采用javax.swing.Timer而非java.util.Timer,确保UI更新在事件调度线程(EDT)中进行,避免线程安全问题。
  3. 立即激活Timer:通过setInitialDelay(0)让Timer启动后立即执行一次更新,无需等待1秒。
  4. 颜色切换逻辑:用布尔变量isRed标记当前颜色状态,点击按钮时在红色和默认颜色间切换。
  5. 窗体关闭行为:设置DISPOSE_ON_CLOSE,关闭Timer窗体不会退出整个程序,只有点击Close按钮或关闭对话框才会退出。
  6. EDT线程运行:所有Swing组件的创建和显示都放在SwingUtilities.invokeLater中,符合Swing的线程规范。

内容的提问来源于stack exchange,提问作者assblaster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 04:40:24