我正在做一个涉及 JPanel 中的鼠标和键侦听器的小项目。不幸的是,当我使用鼠标/键盘时,没有调用任何方法。我以前使用过 JPanels/JFrame/JApplet 和 JComponents。代码片段如下所示:
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");
}
}
题外话:我不断收到错误您的帖子似乎包含未正确格式化为代码的代码。请使用代码工具栏按钮或 CTRL+K 键盘快捷键将所有代码缩进 4 个空格。如需更多编辑帮助,请单击 [?] 工具栏图标。我不知道如何解决它。有时我把所有东西都放在代码中,它仍然不会提交。