5

I'm doing a little project that involves the mouse and key listeners in JPanel. Unfortunately, none of the methods are called when I use the mouse/keyboard. I have worked with JPanels/JFrame/JApplet and JComponents before. The code snippets are shown below:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.util.Scanner;

public class Hello extends JPanel implements KeyListener, MouseListener{
    JPanel panel = new JPanel();
    JFrame frame = new JFrame();
    public Hello(){
        addKeyListener(this);
        addMouseListener(this);
    }
    public static void main(String [] args){
        Hello play = new Hello();
        play.setPanel();
    }
    public void setPanel(){
        panel.setLayout(null);
        frame.add(panel);
        frame.setLayout(null);
        panel.setBounds(0,0,100,100);
        frame.setVisible(true);
        panel.setVisible(true);
        panel.setFocusable(true);
        frame.setSize(100,100);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public void keyTyped(KeyEvent evt){
        System.out.println("keytyped");
    }
    public void keyPressed(KeyEvent evt){
        System.out.print("keypressed");
    }
    public void keyReleased(KeyEvent evt){
        System.out.println("keyreleased");
    }
    public void mousePressed(MouseEvent evt){
        System.out.println("mousepressed");
    }
    public void mouseReleased(MouseEvent evt){
        System.out.println("mousereleased");
    }
    public void mouseClicked(MouseEvent evt){
        System.out.println("mouseclicked");
    }
    public void mouseEntered(MouseEvent evt){
        System.out.println("mousenentered");
    }
    public void mouseExited(MouseEvent evt){
        System.out.println("mouseexited");
    }
}

Off topic: I keep getting the error Your post appears to contain code that is not properly formatted as code. Please indent all code by 4 spaces using the code toolbar button or the CTRL+K keyboard shortcut. For more editing help, click the [?] toolbar icon. I have no idea how to fix it. Sometimes I put everything in code and it still won't submit.

GoldenLyfe
  • 49
  • 1
  • 1
  • 4

3 Answers3

12

Have a look at Java KeyListener for JFrame is being unresponsive?.

You need to register your KeyListener and MouseListener for every JComponent you want to listen to:

public Hello() {
    addKeyListener(this);
    addMouseListener(this);
    panel.addKeyListener(this);
    panel.addMouseListener(this);
    frame.addKeyListener(this);
    frame.addMouseListener(this);
}

Edit:
Key and mouse events are only fired from the JComponent which has focus at the time. Because of this there seems to be a consensus that KeyBindings may be favorable to KeyListeners. The two have their applications, however, and so there is no hard and fast rule here. Have a read of 'How to Write a Key Listener' and 'How to Write a Key Binding' and you'll get the gist.

Community
  • 1
  • 1
Sean Connolly
  • 5,692
  • 7
  • 37
  • 74
  • Thanks. Does this apply to JComponents also? Like every JLabel, JTextField, etc.? Or will they all work if I add them to the panel? Will be voted in 5 minutes. – GoldenLyfe Dec 29 '12 at 20:54
  • 2
    Yup, the only `JComponent` that will be firing events is the one with `focus` at the time. [How to Write a Key Listener](http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html) and [How to Write a Key Binding](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) break down the differences between the two; which are very subtle but worth grasping before writing code you'll chuck later. – Sean Connolly Dec 29 '12 at 21:00
  • @SeanConnolly please make that comment part of your answer. KeyListeners should be avoid (in part for this reason) in favour of KeyBindings – MadProgrammer Dec 29 '12 at 21:12
2

Better to avoid using KeyListeners with JPanel, use KeyBindings instead. JPanel cannot gain focus so cannot interact with KeyEvents. Using KeyBindings, you can map an Action to a KeyStroke even when a component doesn't have focus.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

Try this instead:

 panel.addKeyListener(this);
 panel.addMouseListener(this);

You have to add the listeners to every component you want to listen to.

aly
  • 523
  • 2
  • 7
  • 1
    Thank you for contributing. Giving a solution is good, explaining why it works is better ( http://stackoverflow.com/questions/how-to-answer ). – ARRG Dec 29 '12 at 20:54