这是我在滚动骰子时绘制错误的主要程序
我需要为它设置一个计时器吗?
这里我添加了一些例子,但我不确定要放入什么
for(形状:形状){
shape.move();
shape.decreaseDelay();
重绘();
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Timer;
public class Yahtzee extends JFrame implements ActionListener {
Die[] d; // array to hold the 5 dice
FourOfAKind[] f;
JPanel dicePanel; // panel to hold the dice
JPanel bugPanel;
Timer timer = new Timer();
public static void main(String[] args)
{
Yahtzee y = new Yahtzee();
}
public Yahtzee()
{
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
setLayout(new BorderLayout());
timer = new Timer(30, new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (Shape shape : shapes) {
shape.move();
shape.decreaseDelay();
repaint();
}
}
});
JButton start = new JButton("Start");
start.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
timer.start();
}
});
JPanel panel = new JPanel();
panel.add(start);
dicePanel = new JPanel();
dicePanel.setLayout(new GridLayout(5, 1));
dicePanel.setLayout(new FlowLayout());
dicePanel.setSize(new Dimension(50, 50));
add(dicePanel, BorderLayout.CENTER);
d = new Die[1];
for (int i = 0; i < 1; i++) {
d[i] = new Die(this);
dicePanel.add(d[i]);
}
bugPanel = new JPanel();
bugPanel.setLayout(new GridLayout(5, 5));
bugPanel.setLayout(new FlowLayout());
bugPanel.setSize(new Dimension(50, 50));
add(bugPanel, BorderLayout.SOUTH);
f = new FourOfAKind[1];
for (int w = 0; w < 1; w++) {
f[w] = new FourOfAKind(this);
bugPanel.add(f[w]);
}
setSize(new Dimension(715, 705));
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
repaint();
timer.start(); // start timer
}
public void setChoice(int choice) {
f[0].setChoice(choice);
}
public void drawBug() {
f[0].setChoice(d[0].getChoice());
f[0].drawBug();
}
}
答案 0 :(得分:1)
我想你想要一个javax.swing.Timer
。在那种情况下:
此Timer timer = new Timer();
无法正常工作。你需要传递参数
Timer timer = new Timer(1000, this);
也不是import java.util.Timer;
而是import javax.swing.Timer;
此外,不要在timer
中启动actionPerformed
,因为那是魔法发生的地方。在构造函数中启动它,或者为计时器和创建一个单独的监听器以启动计时器,或者将if语句作为ActionEvent
来检查按钮或计时器对象源。
除了repaint()
之外,在actionPerformed
中,您还想要更改某些内容的值然后调用repaint()
。如果您没有改变任何内容,则不会看到任何动画效果。
除此之外,你的问题还不够具体。在当前状态下,它只读为&#34;帮助我开发我的程序&#34;