[英]Having trouble with java animations
這是我的 GUIPanel.java 文件
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class GUIPanel extends JPanel implements ActionListener {
static final int SCREEN_WIDTH = 800;
static final int SCREEN_HEIGHT = 600;
boolean running = false;
Color startingColor;
static final int delay = 120000;
Timer timer;
Random random;
GUIPanel() {
/*int color = random.nextInt(2);
if(color == 0) {
startingColor = Color.red;
}
else {
startingColor = Color.green;
}*/
this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
this.setBackground(Color.red);
this.setFocusable(true);
startSim();
}
public void startSim() {
running = true;
timer = new Timer(delay, this);
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
public void draw(Graphics g) {
//if(running) {
if(this.getBackground() == Color.green) {
this.setBackground(Color.red);
}
else {
this.setBackground(Color.green);
}
//delay = delay / 2;
//}
}
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
所以我嘗試同時使用 swing 定時器和 java.util.timer 並且都產生相同的產品,這是 gui 的背景改變 Z62848E3CE5804AA985Z513A7922FF8st7B 我希望每 2 分鍾調用一次 repaint,因此每 2 分鍾更改一次背景。
好的,所以我現在了解繪圖 function 總是在循環,所以我需要制定一種新方法來更改背景以獲得實際工作的時間。
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class GUIPanel extends JPanel implements ActionListener {
static final int SCREEN_WIDTH = 800;
static final int SCREEN_HEIGHT = 600;
boolean running = false;
Color startingColor;
static final int delay = 120000;
Timer timer;
Random random;
GUIPanel() {
this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
this.setBackground(Color.red);
this.setFocusable(true);
startSim();
}
public void startSim() {
running = true;
timer = new Timer(delay, this);
timer.start();
}
public void changeBackground() {
if(this.getBackground() == Color.green) {
this.setBackground(Color.red);
}
else {
this.setBackground(Color.green);
}
}
@Override
public void actionPerformed(ActionEvent e) {
changeBackground();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.