这是我上一篇文章Java: Animated Sprites on GridLayout的继续。多亏了一个答复,它使我有了一个想法,我只需要在触发条件中插入一个循环并在其中调用pi [i] .repaint()。到目前为止,它仍然有效。尽管我尝试将其集成到由多个精灵组成的游戏中,但并没有任何改进。没有动画,精灵将毫无问题地显示在网格上。我在GridFile类中插入了动画循环,但没有显示。我还尝试在MainFile中插入动画循环,它显示了不规则的动画,有点像小故障。有人可以告诉我我哪里做错了吗?欢迎提出想法。
MainFile类
public class MainFile {
JFrame mainWindow = new JFrame();
public JPanel gridPanel;
public MainFile() {
gridPanel= new GridFile();
mainWindow.add(gridPanel,BorderLayout.CENTER);
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setSize(700,700);
mainWindow.setResizable(false);
mainWindow.setVisible(true);
}
public static void main(String[]args){
new MainFile();
}
}
GridFile类
public class GridFile extends JPanel{
ImageIcon gameBackground = new ImageIcon(getClass().getResource("Assets\\GridBackground.png"));
Image gameImage;
int[] pkmArray = new int[12];
int random = 0;
Pokemon[] pkm = new Pokemon[36];
JPanel[] pokeball = new JPanel[36];
int j = 0;
public GridFile(){
setLayout(new GridLayout(6,6,6,6));
setBorder(BorderFactory.createEmptyBorder(12,12,12,12));
gameImage = gameBackground.getImage();
for(int i = 0;i < 36;i++){
do{
random = (int)(Math.random() * 12 + 0);
if(pkmArray[random] <= 3){
pokeball[i] = new Pokemon(random);
pokeball[i].setOpaque(false);
pokeball[i].setLayout(new BorderLayout());
pkmArray[random]++;
}
}while(pkmArray[random] >= 4);
add(pokeball[i],BorderLayout.CENTER);
}
while(true){
for(int i = 0; i < 36; i++){
pokeball[i].repaint();
}
}
}
public void paintComponent(Graphics g){
if(gameImage != null){
g.drawImage(gameImage,0,0,getWidth(),getHeight(),this);
}
}
}
最佳答案
使用秋千Timer进行重新绘制,并在两帧之间留一点时间进行秋千以进行绘画工作。试图以比显示的速度更快的速度绘画是没有意义的。如果main()
中有动画循环,则重新绘制管理器将尝试删除一些看起来彼此接近的重新绘制请求,这可能是您看到不规则动画的原因。
您只能在event dispatch thread中创建和访问swing组件。您当前的做法是违反线程规则。
另外:当动画循环现在就在其中时,GridFile
构造函数将永远不会返回,这说明您将看不到任何东西,因为代码永远不会显示窗口。