用java实现一个记事本程序,记录记下的按键,代码例如以下:
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); } } @Override public void keyPressed(KeyEvent e) { chars[size]=e.getKeyChar(); size++; repaint(); } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } }这里用了一个字符数组来记录全部按下的字符。执行实比例如以下:
记事的功能实现了。下一节来实现光标和删除功能。