日時を表示するJavaでデジタル時計が必要で、コロンが点滅するはずです。しかし、私はコロンを点滅させることはできません。ここに私のコードだ:ActionListener - Javaを使用して時計を更新します。
import java.awt.Font;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.SwingConstants;
import java.util.*;
import java.text.*;
public class DigitalClock {
public static void main(String[] arguments) {
ClockLabel dateLable = new ClockLabel("date");
ClockLabel timeLable = new ClockLabel("time");
ClockLabel dayLable = new ClockLabel("day");
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame f = new JFrame("Digital Clock");
f.setSize(300,150);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new GridLayout(3, 1));
f.add(dateLable);
f.add(timeLable);
f.add(dayLable);
f.getContentPane().setBackground(Color.black);
f.setVisible(true);
}
}
class ClockLabel extends JLabel implements ActionListener {
String type;
SimpleDateFormat sdf;
public ClockLabel(String type) {
this.type = type;
setForeground(Color.green);
Calendar calendar = Calendar.getInstance();
int seconds = calendar.get(Calendar.SECOND);
switch (type) {
case "date" : sdf = new SimpleDateFormat(" MMMM dd yyyy");
setFont(new Font("sans-serif", Font.PLAIN, 12));
setHorizontalAlignment(SwingConstants.LEFT);
break;
case "time" : if(seconds % 2 != 0) sdf = new SimpleDateFormat("hh:mm:ss a");
else sdf = new SimpleDateFormat("hh mm ss a");
setFont(new Font("sans-serif", Font.PLAIN, 40));
setHorizontalAlignment(SwingConstants.CENTER);
break;
case "day" : sdf = new SimpleDateFormat("EEEE ");
setFont(new Font("sans-serif", Font.PLAIN, 16));
setHorizontalAlignment(SwingConstants.RIGHT);
break;
default : sdf = new SimpleDateFormat();
break;
}
Timer t = new Timer(1000, this);
t.start();
}
public void actionPerformed(ActionEvent ae) {
Date d = new Date();
setText(sdf.format(d));
}
}
あなたが見ることができるように、私は次の行があります
case "time" : if(seconds % 2 != 0) sdf = new SimpleDateFormat("hh:mm:ss a");
else sdf = new SimpleDateFormat("hh mm ss a");
そのように秒が奇数の場合は、コロンはコロンが表示されていない他に、表示されます。
問題は、私がプログラムを起動し、その時に2番目が奇妙な場合、コロンは常に表示されるということです。私はなぜ、2番目の変更(時間の更新)ので、理解していないが、コロンはしません。
ClockLabelのコンストラクタで起動時にSimpleDateFormatを1回だけ設定しています。 actionPerformed()でフォーマットを切り替える必要があります – Johan
ちなみに、これらの日付時刻クラスは現在レガシーです。 java.timeクラス、ThreeTen-Backportプロジェクト、ThreeTenABPプロジェクトをチェックアウトします。 –