How do I fix the KeyListener

Amit

why isnt this working the JFrame is made and the paint is working but I can't get the keylistener to work. Ive tried to print something inside the keylistener but it did not show when left arrow was pressed.

import java.awt.event.KeyEvent;


public class movingsquare extends runpaintgui{
    public void key(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_LEFT){

            x = x - 5;
            repaint(); 
            System.out.println( x);
        }

    }
}

other class

import java.awt.Graphics;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;

public class runpaintgui extends JFrame{    
int x = 30;
    public static void main(String[] args){
        runpaintgui frame = new runpaintgui();
        frame.setSize(1275, 775);
        frame.setResizable(false);
        frame.setTitle("game");
        frame.setVisible(true);    

    }
     public void paint(Graphics g){
            super.paint(g);

            g.fill3DRect(x, 30, 60, 60, true);


        }    


        }
Jens

Change your code this way:

package de.swisslife.muellerj.test;

import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;

    public class runpaintgui  extends JFrame implements KeyListener{

      public runpaintgui(){

        this.setSize(1275, 775);
        this.setResizable(false);
        this.setTitle("game");
        this.setVisible(true);    
        this.addKeyListener(this);
        this.setVisible(true);;
      }
        int x = 30;
        public static void main(String[] args){
          runpaintgui runpaintgui = new runpaintgui();

        }
         public void paint(Graphics g){
                super.paint(g);

                g.fill3DRect(x, 30, 60, 60, true);


            }    

        public void keyTyped(KeyEvent e) {
          // TODO Auto-generated method stub

        }
        public void keyPressed(KeyEvent e) {
          if (e.getKeyCode() == KeyEvent.VK_LEFT){

            x = x - 5;
            repaint(); 
            System.out.println( x);
        }

        }
        public void keyReleased(KeyEvent e) {
          // TODO Auto-generated method stub

        }
    }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related