Help making me move an oval using Java?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums
Results 1 to 2 of 2

Thread: Help making me move an oval using Java?

Hybrid View

  1. #1
    Join Date
    Jan 2012

    Unhappy Help making me move an oval using Java?

    Hello my name is turtle. I am having trouble trying to get an oval to move(any direction) using a visual game like window in java. The problem is is after all my work the ball doesn't move nomatter what. Here is the code:

    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.util.Timer;
    import javax.swing.JFrame;

    public class pro extends JFrame implements KeyListener, ActionListener{
    Timer t = new Timer();
    int x = 0, y = 0, velx = 0, vely = 0;

    public pro(){


    public void paint(Graphics g){
    g.drawOval(x, y, 50, 50);

    public static void main(String args[]){
    new pro();

    public void actionPerformed(ActionEvent e) {
    x += velx;
    y += vely;
    public void up(){
    vely = -1;
    velx = 0;
    public void down(){
    vely = 1;
    velx = 0;
    public void left(){
    vely = 0;
    velx = -1;
    public void right(){
    vely = 0;
    velx = 1;
    public void keyPressed(KeyEvent e) {
    int code = e.getKeyCode();
    if (code == KeyEvent.VK_UP) {
    if (code == KeyEvent.VK_DOWN) {
    if (code == KeyEvent.VK_RIGHT) {
    if (code == KeyEvent.VK_LEFT) {

    public void keyReleased(KeyEvent e) {}
    public void keyTyped(KeyEvent e) {}

    I based the code on this video
    Please tell me what i did wrong
    Thank you for your help!


  2. #2
    Join Date
    May 2006

    Re: Help making me move an oval using Java?

    Please tell me what i did wrong
    • To start with you didn't post the code in code tags so it's now difficult to read which means I won't do anything other than give it a cursory glance.
    • You shouldn't be trying to draw on, add KeyListeners to etc a JFrame, you should be using a JComponent such as a JPanel, which you add to the JFrame.
    • When handling the drawing yourself you shouldn't override the paint method, you should override the paintComponent method instead - read the Java tutorial on 2D graphics
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

This is a survey!

HTML5 Development Center