上一節實現了記錄字符的功能,本節將實現光標和鍵盤左右鍵刪除功能。代碼如下:
package com.java.test; import java.awt.Graphics; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JFrame; import javax.swing.JPanel; public class Book { public static void main(String[] args) { JFrame jFrame=new JFrame(); jFrame.setSize(300, 500); MyPanel myPanel=new MyPanel(); jFrame.add(myPanel); jFrame.addKeyListener(myPanel); myPanel.addKeyListener(myPanel); jFrame.show(); } } class MyPanel extends JPanel implements KeyListener{ char[] chars=new char[1000]; int size=0; @Override public void paint(Graphics g) { super.paint(g);//清除屏幕 for (int i = 0; i < size; i++) { g.drawString(chars[i]+"", 10+8*i, 10); } g.drawLine(10+size*8, 0, 10+size*8, 10);//加入光標 } @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode()>=KeyEvent.VK_A&&e.getKeyCode()<=KeyEvent.VK_Z){ chars[size]=e.getKeyChar(); size++; }if(e.getKeyCode()==KeyEvent.VK_LEFT){ if(size>0){ size--; } }if(e.getKeyCode()==KeyEvent.VK_RIGHT){ if(size<1000){ size++; } } repaint(); } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } }
這個功能還蠻有意思,按左鍵刪除,按右鍵被刪除的字符會重現。