The previous section implements the function of recording characters, this section will implement the cursor and keyboard key delete function. The code is as follows:
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); / / clear screen
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); / / add cursor
}
@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) {
}
}
Run the following example:
This feature is quite interesting, left-click Delete, right-click on the deleted characters will be reproduced.
On-Machine topic (beginner)-use an array to implement Notepad + cursor and delete (Java)