用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) { } }這裡用了一個字符數組來記錄所有按下的字符,運行實例如下:
記事的功能實現了,下一節來實現光標和刪除功能。