JSpinner.DateEditor in Java Not Respecting TimeZone on Initialization

元气小坏坏 提交于 2019-12-12 14:11:13

问题


I'm working on bugfix to an existing Swing Application that is using java dates and the Swing's JSpinner as a DateEditor. I'm trying to get the Editor to default to using UTC to display the time, rather than our local timezone. The application is running on Windows, using Java 8.

The code I am using is below.

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;

    public class Test {

    public static void main(String [] args) {
        // Initialize some sample dates
        Date now = new Date(System.currentTimeMillis());


        JSpinner spinner = new JSpinner();

        // Create model with a current date and no start/end date boundaries, and set it to the spinner
        spinner.setModel(new SpinnerDateModel(now, null, null, Calendar.MINUTE));

        // Create new date editor with a date format string that also displays the timezone (z)
        // Set the format's timezone to be UTC, and finally set the editor to the spinner
        JSpinner.DateEditor startTimeEditor = new JSpinner.DateEditor(spinner, "yyyy-MMM-dd HH:mm zzz");

        startTimeEditor.getFormat().setTimeZone(TimeZone.getTimeZone("UTC"));
        spinner.setEditor(startTimeEditor);

        JPanel panel = new JPanel();
        panel.add(spinner);
        JOptionPane.showConfirmDialog(null, panel);
    }

}

This code, however, has an initialization issue. When the Dialog first appears, the time is shown in our local timezone, not UTC. Once the user first interacts with the field by clicking on it, it switches to UTC and works properly from there on out.

How can I get the field to display initially in UTC time?


回答1:


Interesting bug. A workaround that works for me is to set the spinner’s initial value to something like new Date(0) (which is January 1 1970), then after adjusting the editor, call spinner.setValue(new Date()).

The real problem is that the Spinner doesn’t seem to update its text in response to a change in the editor property. In fact, the JSpinner documentation suggests that the editor property is not a bound property at all. So another workaround is to force the Spinner to update whenever the editor is changed:

SpinnerModel model = new SpinnerDateModel(now, null, null, Calendar.MINUTE);
JSpinner spinner = new JSpinner(model) {
    @Override
    public void setEditor(JComponent editor) {
        super.setEditor(editor);
        fireStateChanged();
    }
};


来源:https://stackoverflow.com/questions/37444308/jspinner-dateeditor-in-java-not-respecting-timezone-on-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!