1
ウィンドウが画面の上にあるときにだけ実行されるカウントダウンタイマーを作ろうとしています。カウントダウンタイマーでwindowFocusListenerを使用
私はこれを試してみました:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class TimerVisible extends JFrame implements WindowFocusListener{
static TimerVisible frame = new TimerVisible("chrono",2,1,3);//I set a random time
JTextArea display;
private Counter counter;
public static void main(String[] args) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addComponentsToPane();
frame.pack();
frame.setVisible(true);
}
private void addComponentsToPane() {
display = new JTextArea();
display.setEditable(true);
JScrollPane scrollPane = new JScrollPane(display);
scrollPane.setPreferredSize(new Dimension(500, 450));
getContentPane().add(scrollPane, BorderLayout.CENTER);
addWindowFocusListener(this);
}
public TimerVisible(String name, int hours, int minutes, int secondes) {
super(name);
counter=new Counter(hours, minutes, secondes); //Counter is in secondes but is created with hours, minutes and seconds
}
public void windowGainedFocus(WindowEvent e) {
displayMessage("WindowFocusListener method called: windowGainFocus.");
try{
while(counter.getCounter()!=0){
Thread.sleep(1000);
displayMessage(counter.toString());
counter.decrement();
}
}
catch(InterruptedException exc){
System.exit(-1);
}
}
public void windowLostFocus(WindowEvent e) {
displayMessage("WindowFocusListener method called: windowLostFocus.");
}
private void displayMessage(String msg) {
display.append(msg+"\n");
System.out.println(msg);
}
}
を、私はこのプログラムを実行すると、それは私の端末ではなく、ウィンドウ上のメッセージとカウントダウンを表示するが、私はコメントの下while loop
を設定した場合、それが正しく表示さメッセージをウィンドウに表示します。なぜ私はこの違いがあるのか考えている人はいますか?
は
おかげで、それが働いている、と私は今、タイマーを振る理解しています。 – Cariamole