import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SimpleAnimationTest {
private int distanceHorizonal= 100;
private int distanceVertical= 200;
public static void main(String[] args) {
new SimpleAnimationTest().go();
}
public void go() {
JFrame f = new JFrame( );
BallPanel panel = new BallPanel( );
f.add(panel);
f.setSize(300, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
while( distanceHorizonal > 0){
distanceHorizonal--;
distanceVertical -= 2;
panel.repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
class BallPanel extends JPanel {
public void paintComponent(Graphics g) {
Graphics2D g2= (Graphics2D) g;
g2.fillRect(0, 0, this.getWidth(), this.getHeight());
g2.setColor(Color.red);
g2.fillOval((distanceHorizonal), (distanceVertical),
10, 10);
}
}
}
the code above is copied from the book(head first java). When i was trying to write
the code myself, i want to add a start button to control the ball's movement. In what follows is my code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SimpleAnimationTest {
private int distanceHorizonal= 100;
private int distanceVertical= 200;
public static void main(String[] args) {
new SimpleAnimationTest().go();
}
public void go() {
JFrame f = new JFrame( );
JButton btn = new JButton("Start");
BallPanel panel = new BallPanel( );
btn.addActionListener(panel);
f.add(panel);
f.add(btn, BorderLayout.SOUTH);
f.setSize(300, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
class BallPanel extends JPanel implements ActionListener{
public void paintComponent(Graphics g) {
Graphics2D g2= (Graphics2D) g;
g2.fillRect(0, 0, this.getWidth(), this.getHeight());
g2.setColor(Color.red);
g2.fillOval((distanceHorizonal), (distanceVertical),
10, 10);
}
@Override
public void actionPerformed(ActionEvent e) {
while( distanceHorizonal > 0){
distanceHorizonal--;
distanceVertical -= 2;
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
}
Maybe the inner class (BallPanel) looks strange.when I attempt to want to creat another inner class which implement action listeners, I find the new inner class
can't refer the BallPanel's repaint() method. So........
My problem is that the ball in my code don't move slowly as expected when i click
the start button.it appears at the starting site and ending site.
tell me where is wrong in my code?
thanks in advance!