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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…