Leitwerk
Leitwerk

Reputation: 37

Java Key Eventlistener

at the moment I'm learning Java, and I'm stuck at a problem.

I try to catch KeyEvent, but it doesn't work.

Maybe one of you got a solution?

package test;

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

public class SpielFenster extends JFrame implements KeyListener {
    int posX = 100;
    int posY = 100;
    SpielFenster(){
        this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 
        this.setSize( 400, 600 );
        this.setTitle( "Hindi Bones - Lost in Labyrinth" );

        this.setVisible( true );
    }
    public void paint(Graphics g) { 
        super.paint(g);
        g.setColor(Color.ORANGE);
        g.fillOval(posX, posY, 20, 20); 
    }

    public void keyPressed(KeyEvent e) {
        test("test");
    }

    public void keyReleased(KeyEvent e) { test("test");}
    public void keyTyped(KeyEvent e) { test("test");}
    public void test(String x){
        System.out.println(x);
    }

    public static void main(String[] args){
        SpielFenster fenster = new SpielFenster();
        fenster.test("yoo");

    }
}

Thanks in advance! :)

Upvotes: 0

Views: 73

Answers (2)

Filippo Cardano
Filippo Cardano

Reputation: 26

You forgot to add the keylistener to any of the JComponents that you have... The only one you have is the JFrame so do it on the JFrame, in the constructor : this.addKeyListener(this);

Here it is inside your application:

package alltests;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SpielFenster extends JFrame implements KeyListener{
    int posX = 100;
    int posY = 100;

    SpielFenster(){
        this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 
        this.setSize( 400, 600 );
        this.setTitle( "Hindi Bones - Lost in Labyrinth" );
        this.addKeyListener(this);//here <<<<<
        this.setVisible( true );
    }
    public void paint(Graphics g) { 
        super.paint(g);
        g.setColor(Color.ORANGE);
        g.fillOval(posX, posY, 20, 20); 
    }

    public static void main(String[] args){
        SpielFenster fenster = new SpielFenster();
    }

    @Override
    public void keyPressed(KeyEvent e) {
        test("test");
    }

    @Override
    public void keyReleased(KeyEvent e) {
        test("test");           
    }

    @Override
    public void keyTyped(KeyEvent e) {
        test("test");           
    }
    public void test(String x){
        System.out.println(x);
    }
}

Hope it helps

Upvotes: 1

Eng.Fouad
Eng.Fouad

Reputation: 117685

Because you didn't register the listener on any swing component:

someComponent.addKeyListener(this);

See: How to Write a Key Listener

Upvotes: 2

Related Questions