Java – mouselistener / keylistener does not work (JPanel)
I'm working on a small project involving the mouse and key listeners in JPanel Unfortunately, when I use the mouse / keyboard, no method is called I have used jpanels / JFrame / JApplet and jcomponents before The code snippet is as follows:
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,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"); } }
Turn off topic: I've been receiving errors. Your post seems to contain code that is not formatted correctly Use the code toolbar button or the CTRL K keyboard shortcut to indent all code 4 spaces For more editing help, click [?] Toolbar icon I don't know how to solve it Sometimes I put everything in code, but it still doesn't commit
Solution
Check out Java keylistener for JFrame is being unresponsive
You need to register keylistener and mouselistener for each JComponent you want to listen on:
public Hello() { addKeyListener(this); addMouseListener(this); panel.addKeyListener(this); panel.addMouseListener(this); frame.addKeyListener(this); frame.addMouseListener(this); }
Edit: key and mouse events are triggered only from the JComponent with focus at that time Therefore, there seems to be a consensus that keybindings may be beneficial to keylisteners However, both have their applications, so there are no hard and fast rules here You will understand this by reading 'how to write a key listener' and 'how to write a key binding'