On-Machine topic (beginner)-use an array to implement Notepad + cursor and delete (Java)

Source: Internet
Author: User
Tags clear screen



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&amp;&amp;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)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.