나는 JFrame
과 일하고 있으며 while 회 돌이가 있습니다. 그 루프 내에서 프레임의 배경을 검정색으로 변경 한 후 다시 흰색으로 바꿉니다. 그러나 변경하기 전에 두 번째 또는 두 번째로 일시 중지해야 실제로 볼 수 있습니다. Thread.sleep()
및 Timer
이 작동하지 않는 것 같습니다. 누구든지 도와 줄 수 있습니까?프로그램 일시 중지
0
A
답변
0
당신이 swing
에서 timer
를 사용하려면이 그것을 할 수있는 적절한 방법 :
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
public class Animation extends JFrame implements ActionListener {
private Timer t;
private Color myColor;
private int howManyTimesIwantThis;
private int count = 0;
public Animation() {
t = new Timer(1000, this); // actionPerformed will be called every 1 sec
t.start();
this.howManyTimesIwantThis = 10;
this.setVisible(true);
this.setSize(500, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
myColor = Color.blue;
}
public void actionPerformed(ActionEvent e) {
if (count < howManyTimesIwantThis) {
count++;
if (myColor.equals(Color.blue)) {
myColor = Color.red;
} else {
myColor = Color.blue;
}
repaint(); //calls the paint method
}
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(myColor);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.dispose();
}
}
가 그리고 당신은 Thread.sleep()
을 사용하려는 경우,이 같은 작업을 수행 할 수 있습니다
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class Animation extends JFrame{
private Color myColor;
private int howManyTimesIwantThis;
private int count = 0;
public Animation() {
this.howManyTimesIwantThis = 10;
this.setVisible(true);
this.setSize(500, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
myColor = Color.blue;
}
public void paint(Graphics g) {
super.paint(g);
while (count < howManyTimesIwantThis) {
count++;
if (myColor.equals(Color.blue)) {
myColor = Color.red;
} else {
myColor = Color.blue;
}
g.setColor(myColor);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
g.dispose();
}
}
코드에 대한 질문이 있으시면 언제든지 문의하십시오.
+0
프로그래머가 paint() 안에 sleep()을 넣을 때마다 강아지가 죽습니다. : ( –
+0
나는 그것을 알고있다 :). 나는 paint() 내부에서 잠을 자지 않겠지 만,이 경우 다른 빠른 방법을 보지 못합니다. – Andy
'javax.swing.timer'. –
어떻게 지내니? 당신이 시도한 것을 게시하십시오. –
'Timer','java.util' 또는'javax.swing'이란 무엇입니까? – Azad