Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to create first java game?

807588Jun 18 2009 — edited Jun 18 2009
So I'm trying my hand at my first java platform game and having some troubles. I think i'm on the right track, but when I try to paint my character on the screen and add a KeyListener and KeyAdapter for arrow key controls, the character isn't on the screen. Here is my code

public class Goku_Game extends JFrame{
Controls controls = new Controls();
public Goku_Game(){
add(controls);
controls.setFocusable(true);
}

public static void main(String[] args){
Goku_Game frame = new Goku_Game();
frame.setSize(600, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

static class Controls extends JPanel{
/*Head Construction
* Rest of the body is centered around these two values
*/
int xHeadCenter = getWidth()/5;
int yHeadCenter = (int)(getHeight()*.6);
int radius = (int)(Math.min(getWidth(), getHeight()) * 0.05);
int x = xHeadCenter - radius;
int y = yHeadCenter - radius;
//body
int xbod1 = xHeadCenter;
int xbod2 = xbod1;
int ybod1 = yHeadCenter + radius;
int ybod2 = ybod1 + radius*3;
//arms
int left = x/2 - radius/2;
int right = (int)((xHeadCenter+radius)*1.5);
int yarms = ybod1 + (int)(radius * 0.3);
int yarms2 = ybod1 + (int)(radius * 0.3);
//legs
int leftleg = x;
int lefty = (int)(ybod2 * 1.25);
int rightleg = xHeadCenter + radius;
int righty = (int)(ybod2 * 1.25);

protected void paintComponent(Graphics g){
super.paintComponent(g);
//fill in head
g.fillArc(x, y, 2*radius, 2*radius, 0, 360);
//draw body
g.drawLine(xbod1, ybod1, xbod2, ybod2);
//draw left arm
g.drawLine(left, yarms, xbod1, yarms);
//draw right arm
g.drawLine(xbod1, yarms, right, yarms2);
//left leg
g.drawLine(xbod2, ybod2, leftleg, lefty);
//right leg
g.drawLine(xbod2, ybod2, rightleg, righty);
}

public Controls(){
addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
switch(e.getKeyCode()){
case KeyEvent.VK_RIGHT : xHeadCenter += 10; break;
case KeyEvent.VK_LEFT : xHeadCenter -= 10; break;
case KeyEvent.VK_UP : yarms2 += 2; right -= 1; break;
case KeyEvent.VK_DOWN : yarms2 -= 2; right += 1; break;

}
repaint();
}
});

}

}
}

I've been trying to figure it out because the paintComponent should shouldn't have to be invoked and the repaint() should update the window and display the character, but the screen comes up blank.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 16 2009
Added on Jun 18 2009
5 comments
188 views