gpt4 book ai didi

java - 尽管我已经编写了frame.repaint()来从循环中调用paintComponent()方法,为什么仍观察到球的运动

转载 作者:行者123 更新时间:2023-12-02 03:49:07 24 4
gpt4 key购买 nike

import javax.swing.*;
import java.awt.*;

import java.awt.event.*;

class JAnimation implements ActionListener

{

JFrame frame;

int x=40,y=40;

public static void main(String args[])

{

new JAnimation().go();

}

public void go()

{

frame=new JFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton button=new JButton("CLICK TO START ANIMATION");

button.addActionListener(this);

MyDrawPanel panel=new MyDrawPanel();

frame.getContentPane().add(BorderLayout.SOUTH,button);

frame.getContentPane().add(BorderLayout.CENTER,panel);

frame.setSize(300,300);

frame.setVisible(true);

}

public void actionPerformed(ActionEvent e1)

{

System.out.println("INDIA")

for(int i=0;i<130;i++)

{

x++;

y++;

frame.repaint();

try

{

Thread.sleep(50);

}

catch(Exception e)

{

System.out.println(e);

}

}


}

class MyDrawPanel extends JPanel

{

public void paintComponent(Graphics g1)

{

System.out.println("HII");

Graphics2D g2=(Graphics2D)g1;

g2.setColor(Color.white);

g2.fillOval(0,0,this.getWidth(),this.getHeight());

g2.setColor(Color.green);

g2.fillOval(x,y,70,70);

System.out.println(x);

}

}
}

最佳答案

您正在阻塞 EDT 线程,因为该面板未更新。您卡住了 gui。您可以使用 Swing 计时器而不是线程来制作圆圈动画,而不会阻塞 EDT。阅读swing concurrency .

这是示例

  public void actionPerformed(ActionEvent e1) {

System.out.println("INDIA");

new Timer(50, new ActionListener() {

@Override
public void actionPerformed(ActionEvent ae) {
x++;

y++;

frame.repaint();
}
}).start();

}

enter image description here

关于java - 尽管我已经编写了frame.repaint()来从循环中调用paintComponent()方法,为什么仍观察到球的运动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36042240/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com