-
January 31st, 2012, 05:37 PM
#1
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(){
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
setTitle("Project");
setSize(600,600);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics g){
g.drawOval(x, y, 50, 50);
}
public static void main(String args[]){
new pro();
}
@Override
public void actionPerformed(ActionEvent e) {
repaint();
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) {
up();
}
if (code == KeyEvent.VK_DOWN) {
down();
}
if (code == KeyEvent.VK_RIGHT) {
right();
}
if (code == KeyEvent.VK_LEFT) {
left();
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
}
I based the code on this video
http://www.youtube.com/watch?v=p9Y-NBg8eto
Please tell me what i did wrong
Thank you for your help!
-Turtle
-
February 3rd, 2012, 10:02 AM
#2
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
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|