ComboBox で選択したインデックスに基づいて、タイム ゾーンやその他のものを変更するクラス用の簡単なスイング プログラムを作成しました。メソッド run() が次のようになっている場合、正常に動作します。
public void run() {
while(true){
Calendar c = Calendar.getInstance();
int h = c.get(Calendar.HOUR);
int m = c.get(Calendar.MINUTE);
int s = c.get(Calendar.SECOND);
l.setText(""+h+":"+m+":"+(s<10?"0"+s:s));
try {
t.sleep(1000);
} catch (InterruptedException ex) {}
}
}
しかし、それを再定義して時間変更を機能させようとすると、次の行で null ポインター例外が発生します。
p.cb.addItemListener(new ItemListener() {
メソッド run() は次のようになりますが、機能しません。何か案は?
public void run() {
while(true){
p.cb.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
Calendar c = Calendar.getInstance();
int h = c.get(Calendar.HOUR);
int m = c.get(Calendar.MINUTE);
int s = c.get(Calendar.SECOND);
int index = p.cb.getSelectedIndex();
if(index == 0){
l.setText(""+h+":"+m+":"+(s<10?"0"+s:s));
}
else if(index == 1){
l.setText(""+(h-6)+":"+m+":"+(s<10?"0"+s:s));
}
else if(index == 2){
l.setText(""+(h-1)+":"+m+":"+(s<10?"0"+s:s));
}
else if(index == 3){
l.setText(""+(h-6)+":"+m+":"+(s<10?"0"+s:s));
}
else if(index == 4){
l.setText(""+(h+8)+":"+m+":"+(s<10?"0"+s:s));
}
}
});
try {
t.sleep(1000);
} catch (InterruptedException ex) {}
}
}
混乱している方のために説明すると、p は JFrame クラスのインスタンスであり、cb は JFrame クラスの ComboBox への参照です。