java - 带有 SpinnerDateModel 奇怪行为的 JSpinner

标签 java swing jspinner

我发誓这太奇怪了。我制作了一个 Spinner,使用具有当前日期、无限制和 Calendar.MINUTE 单位的新 SpinnerDateModel 设置模型。

正如文档中所说:

Creates a SpinnerDateModel that represents a sequence of dates between start and end. The nextValue and previousValue methods compute elements of the sequence by advancing or reversing the current date value by the calendarField time unit. The start and end parameters can be null to indicate that the range doesn't have an upper or lower bound.

这是我的代码:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JSpinner;
import javax.swing.JSpinner.DefaultEditor;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.DateFormatter;
import javax.swing.text.DefaultFormatterFactory;

public class JSpinnerTest {

    public JSpinnerTest() {
        initComponents();
    }

    private void initComponents() {
        JFrame frame = new JFrame("JSpinner Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JSpinner spinner = new JSpinner();
        spinner.setModel(new javax.swing.SpinnerDateModel(new Date(), null, null, Calendar.MINUTE));
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");

        ((DefaultEditor) spinner.getEditor()).getTextField().setFormatterFactory(new DefaultFormatterFactory(new DateFormatter(format)));


        System.out.println("ORIGINAL VALUE: " + spinner.getValue().toString());

        spinner.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                System.out.println("VALUE: " + ((JSpinner) e.getSource()).getValue().toString());
            }
        });

        frame.add(spinner);

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JSpinnerTest();
            }
        });
    }
}

但每次我点击小箭头按钮时,日期都会重置为 1970 年 1 月 1 日。为什么?

示例输出:

原始值:2012 年 12 月 6 日星期四 17:06:13 ICT

值:1970 年 1 月 1 日星期四 17:06:00

值:1970 年 1 月 1 日星期四 17:06:00

值:1970 年 1 月 1 日星期四 18:06:00

最佳答案

您正在修改附加到 Spinner 的编辑器使用的日期格式。看起来当您使用 HH:mm 格式时,其余字段都用纪元初始化。如果您不更改日期编辑器使用的格式,它会按预期工作。

关于java - 带有 SpinnerDateModel 奇怪行为的 JSpinner,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13741371/

相关文章:

Java Swing - 我需要将输入数字转换为 HH :MM format 中的分钟和秒

java - 带有自定义 UI 的 JSpinner

java - 如何在Java中将OpenSSH私钥转换为RSA私钥?

Java 对 Guava TreeBasedTable 进行排序

java - JPanel 没有显示它的其余部分

java - 在新的 JFrame-2 中显示 Jtable 内容后,如何将其保留在主 JFrame-1 上

java - 禁用 JSpinner 上的向上和向下箭头按钮

java - 如何为仅与所需列映射的实体选择特定列

java - SonarQube 5.6 是否执行使用 sonar-plugin-api 版本 4.5.2 开发的插件中的装饰器?

java - 如何使用 Swing 减少打开文件的加载时间?