import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class controlBall extends JFrame {
private JButton jbtRight = new JButton("Right");
private JButton jbtLeft = new JButton("Left");
private BallCanvas canvas = new BallCanvas();
public controlBall(){
JPanel panel = new JPanel();//use the panel to group buttons
panel.add(jbtLeft);
panel.add(jbtRight);
this.add(canvas, BorderLayout.CENTER);//add canvas to the center
this.add(panel, BorderLayout.SOUTH);///add buttons to the frame
jbtLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
canvas.moveLeft();
}
});
jbtRight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
canvas.moveRight();
}
});
}
//main method
public static void main(String[] args){
JFrame frame = new controlBall();
frame.setTitle("Control Ball");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
public static class BallCanvas extends JPanel{
private int yCoordinate = 25;
private int xCoordinate;
public void moveRight(){
xCoordinate += 10;
repaint();
}
public void moveLeft(){
xCoordinate -= 10;
repaint();
}
protected void paintComponent(Graphics g){
super.paintComponents(g);
g.drawOval(xCoordinate, yCoordinate, 10, 10);
}
}
}
it does run but after pressing the button for right or left the position in which the ball was before doesn't erase.. any idea why? thanks.