Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Moving Ellipse2D using keyboard events

$
0
0
Hello, I am trying to simply move a ball that I have drawn using keyboardEvents. I know this is very simple, but I cant seem to make it work. What am I missing?
public class Baller extends JPanel {
	
	int x_pos;
	int y_pos;
	
	Baller(){
		setSize(500,500);
		setVisible(true);
		x_pos = getWidth() / 2;
		y_pos = getHeight() / 2;
		
		addKeyListener(new KeyAdapter(){
			public void keyPressed(KeyEvent e){
				switch (e.getKeyCode()) {
					case KeyEvent.VK_DOWN: y_pos--;
					case KeyEvent.VK_UP: y_pos++;
					case KeyEvent.VK_LEFT: x_pos--;
					case KeyEvent.VK_RIGHT: x_pos++;
				
				}repaint();
			}
		});
		
	}
	
	protected void paintComponent(Graphics g){
		super.paintComponent(g);
		Graphics2D g2 = (Graphics2D) g;
		Ellipse2D el = new Ellipse2D.Double(x_pos, y_pos, 20, 20);
		g2.fill(el);
		repaint();
	}
	
	
	public static void main(String args[]){
		Baller balla = new Baller();
		JFrame f = new JFrame();
		f.setSize(600,600);
		f.setLocationRelativeTo(null);
		f.setResizable(true);
		f.add(balla);
		f.setVisible(true);
	}

}

Viewing all articles
Browse latest Browse all 51036

Trending Articles