代码中需要注意的是,由于JPanel需要监听按键,所以需要将JPanel进行聚焦,否则无法监听按键。
1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 5 public class Test_16_11 extends JFrame{ 6 7 public Test_16_11(){ 8 JP jp1 = new JP(); 9 add(jp1); 10 jp1.setFocusable(true);//必须给予焦点,否则KeyListener无法工作 11 } 12 public static void main(String[] args) { 13 // TODO Auto-generated method stub 14 Test_16_11 t1 = new Test_16_11(); 15 t1.setSize(300,300); 16 t1.setTitle("Test_16_11"); 17 t1.setLocationRelativeTo(null); 18 t1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 19 t1.setVisible(true); 20 } 21 22 static class JP extends JPanel{ 23 private String str = "A"; 24 private int x,y; 25 public JP(){ 26 addKeyListener(new KeyAdapter(){ 27 public void keyTyped(KeyEvent e){ 28 str = e.getKeyChar()+""; 29 } 30 }); 31 addMouseListener(new MouseAdapter(){ 32 public void mousePressed(MouseEvent e){ 33 x = e.getX(); 34 y = e.getY(); 35 System.out.println("mouse"); 36 repaint(); 37 } 38 }); 39 } 40 41 protected void paintComponent(Graphics g){ 42 super.paintComponent(g); 43 g.drawString(str, x, y); 44 } 45 } 46 }
Test_16_11.java
效果图:
时间: 2024-10-12 13:09:35