Skip to main content
gamedev.net
🔒 Locked

[java] KeyListener Query

Started by Esqulax 3 replies 950+ views
Original Post
Esqulax
Esqulax
Im trying to make a "Breakout" style game as my first dabble into games making, and, ill be honest, the key/mouselistener stuff is confusing me. and some of the graphics stuff. Anyhoo.. heres my code so far:


package app1;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;

public class MainClass extends JFrame {
 final int WIDE = 900, HIGH = 650;
 int paddle_x = ((WIDE/2)-40);

 //Class to create the GUI and Add stuff
public MainClass() {
 this.setSize(WIDE, HIGH);
 this.setTitle("Awesome");
 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 this.setResizable(false);
 this.setLocationRelativeTo(null);


 this.add(new DrawIt());



 this.setVisible(true);
}


//Class to draw my paddle
public class DrawIt extends JComponent{
    
       public void paintComponent(Graphics g){

        Graphics2D g2 = (Graphics2D)g;

        Shape s = new RoundRectangle2D.Float(paddle_x,HIGH-100,80,10,10,10);

        g2.setColor(Color.BLACK);
        g2.draw(s);
        g2.setColor(Color.RED);
        g2.fill(s);
        
        }
    

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


Ok, my question is this: do i "implements keylistener" on the DrawIt class, and put the keylistener stuff in there? If so, where do i start the keylistener (i.e make it start listening) Lastly, where to i put repaint in all of this? (I understand i'd need a while loop while the game is running.. does this go around the the whole of the main class, or just inside the DrawIt Class?) any advice or help on any of this would be greatly appreciated! [Edited by - Esqulax on December 1, 2008 6:45:00 AM]
Java_newbie
Java_newbie
Yes, you could do

public class DrawIt extends JComponent implements KeyListener { ... }

but you would have to include all of the methods in KeyListener, even if you are not using them, since it is an interface. Additionally, you would have to add a KeyListener to the DrawIt class by using addKeyListener(this) (assuming you are using the method inside of the DrawIt class). Alternatively, you could use

this.addKeyListener(new KeyAdapter( ) {
// Place only the methods which you would like to use here:
});

in one of the methods in DrawIt. That way, you don't have to use the "implements KeyListener" on the class header, and only need to include the methods which you want to use. If you want to make the game stable, you need to call the repaint( ) method from a timer so that the canvas operates at a steady FPS. Otherwise, it'll run at different speeds on different computers. Although there are much better ways to do this, you could use a javax.swing.Timer to coordinate the repaints( ) at somewhat steady intervals for now, and change over to a more stable method after the game works. Here is a tutorial from Sun on how to use them:

http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html

A better way to do this would be to detect and adjust the time between consecutive frames using System.nanoTime( ) and Thread.sleep( ). I hope this helped =).
Esqulax
Esqulax
Thanks Java_Newbie, Its starting to make sense now! I'll continue to play!
Esqulax
Esqulax
being a pain again, but hey :p

[source lang="javaj"package app1;import javax.swing.*;import java.awt.*;import java.awt.geom.*;import java.awt.event.*;public class MainClass extends JFrame {    final int WIDE = 900, HIGH = 650;    int paddle_x = ((WIDE/2)-40);    boolean On = true;//Class to create the GUI and Add stuffpublic MainClass() { this.setSize(WIDE, HIGH); this.setTitle("Awesome"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setResizable(false); this.setLocationRelativeTo(null); this.add(new DrawIt()); this.setVisible(true); }//Class to draw my paddlepublic class DrawIt extends JComponent{       public void paintComponent(Graphics g){        Graphics2D g2 = (Graphics2D)g;        Shape s = new RoundRectangle2D.Float(paddle_x,HIGH-100,80,10,10,10);        g2.setColor(Color.BLACK);        g2.draw(s);        g2.setColor(Color.RED);        g2.fill(s);        this.addKeyListener(new KeyAdapter() {            public void keyPressed(KeyEvent e)            {             if (e.getKeyChar() == 'a') {                 paddle_x = paddle_x - 10;             }            if (e.getKeyChar() == 'd'){                paddle_x = paddle_x + 10;                }            }});        }}    public static void main(String[] args)    {    new MainClass();    }}



Mostly the same as before, but ive added the Keylistener to change the x coords of the paddle.
this time im having trouble repainting the screen.

Im confused as to where i repaint it, i tried popping it after the detected keyPress, but no avail

In my head i can see that i want to detect the keypress, + or - 10 from the paddle_x coords, then repaint the paddle.
Whenever i put a while loop around "this.add(new DrawIt());" i get an out of memory error
the user above mentioed the use of a timer. would i code that directly into the MainClass?

OR as another one.. would it be more plausable to make a seperate class/method for the paddle, then when a key is pressed, call paddle(); repaint();?

Thanks again people!
Glass_Knife
Glass_Knife
Esqulax,

I wrote two simple tutorials about this kind of stuff. It might help with all the questions you're having. The first one is about drawing the stuff on the screen, but I use active rendereing because I never liked overriding paint() to do stuff.

The second tutorial is a Keyboard And Mouse tutorial. It is not perfect, because it is polling for the keys, so if the frame rate drops really low, you miss input, but it should give you some more ideas.

I hope the help.

Java Games: Active Rendering
Java Games: Keyboard and Mouse

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.