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);
}
}
}
you are blocking EDT thread because of that panel is not updating .you freeze the gui.you can use swing timer instead of thread to animate circle without blocking EDT. read swing concurrency .
here is example
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.