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
		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) {
		jbtRight.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
	//main method
	public static void main(String[] args){
		JFrame frame = new controlBall();
		frame.setTitle("Control Ball");
		frame.setSize(200, 200);
	public static class BallCanvas extends JPanel{
		private int yCoordinate = 25;
		private int xCoordinate;
		public void moveRight(){
			xCoordinate += 10;
		public void moveLeft(){
			xCoordinate -= 10;
		protected void paintComponent(Graphics 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.

Recommended Answers

All 4 Replies

Take a closer look at line 56 and note which method you are calling. It may not be the one you want.

I took it off and it works the same.. another thing is that when I drag the mouse to enlarge the size of the windows the other images are gone and is like is working fine.. so I don't know if is just my java compiler or the code itself..

I didn't say remove it - I said it may be the wrong one. Spelling counts.

OMG...!!!! Dude you are awesome thank you!!! thank you!! very much ^^ program works fine now :D...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.