2016-05-25 11 views
3

私は、Java日付とSwingのJSpinnerをDateEditorとして使用している既存のSwingアプリケーションにバグ修正を行っています。私は、ローカルタイムゾーンではなく、UTCを使用して時刻を表示するようにエディタをデフォルトに設定しようとしています。アプリケーションはJava 8を使用してWindows上で動作しています。JavaのJSpinner.DateEditorが初期化時のTimeZoneを尊重しない

私が使用しているコードは以下のとおりです。

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); 
    } 

} 

ただし、このコードには初期化の問題があります。 Dialogが最初に表示されると、時間はUTCではなくローカルタイムゾーンで表示されます。ユーザが最初にフィールドをクリックすることでフィールドとやりとりすると、UTCに切り替わり、そこから正しく動作します。

フィールドをUTC時間で最初に表示させるにはどうすればよいですか?

答えて

4

面白いバグ。私にとっては、スピナーの初期値をnew Date(0)(1970年1月1日)のように設定してから、エディターを調整した後、spinner.setValue(new Date())と呼んでください。

実際の問題は、Spinnerがエディタプロパティの変更に応じてテキストを更新しないように見えることです。実際、JSpinnerのドキュメンテーションは、エディタのプロパティがバインドされたプロパティではないことを示唆しています。もう1つの回避策は、エディタが変更されるたびにSpinnerを強制的に更新することです。

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

ありがとうございます、私たちが検討している可能性のある回避策です。しかし、それはハックのように思えたので、回避策としてそれを解決する前に、より適切な方法があるかどうかを見たいと思っていました。 – JohnnyO

+0

@ JohnnyO別の回避策を追加しました。残念ながら、それはまだハックです。私は、JSpinnerを標準的に使用すると、エディタの変更に基づいて更新されることはわかりません。 – VGR

関連する問題