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.

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..

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

This article has been dead for over six months. Start a new discussion instead.