链表编辑器
分类:Java
可以用数组或者链表实现一个编辑器的功能,各自有各自的优缺点。
这里只实现了单行的输入、删除、左移、右移功能,可以加入换行符实现多行文本编辑功能(但是链表实现这个不是很好设计,十字链表?这个最好还是使用数组),还可以加入文件的读取和存储实现编辑器的打开和保存功能,还可以加入网络连接实现编辑器的网络同步和备份功能。
//ZJSNote.java:
package com.zhuojiaoshou; import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; /** * Created by JiajieZhuo on 2017/3/5. */ public class ZJSNote { public static void main(String[] args) { JFrame jFrame = new JFrame(); jFrame.setSize(300, 400); MyPanel mp = new MyPanel(); jFrame.add(mp); jFrame.addKeyListener(mp); mp.addKeyListener(mp); jFrame.setVisible(true); } } class Node { public char value = ' '; public Node next = null; } class MyPanel extends JPanel implements KeyListener { Node firstNode = new Node(); Node nowNode = firstNode; int cursor = 0; @Override public void paint(Graphics g) { // clear screen super.paint(g); Node tmpNode = firstNode; int x = 0; // word while (tmpNode.next != null) { g.drawString("" + tmpNode.next.value, 10 + x * 8, 10); x++; tmpNode = tmpNode.next; } // cursor g.drawLine(10 + cursor * 8, 0, 10 + cursor * 8, 10); } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() >= KeyEvent.VK_A && e.getKeyCode() <= KeyEvent.VK_Z) { if (nowNode.next == null) { Node newNode = new Node(); newNode.value = e.getKeyChar(); nowNode.next = newNode; nowNode = newNode; cursor++; } else { Node newNode = new Node(); newNode.value = e.getKeyChar(); newNode.next = nowNode.next; nowNode.next = newNode; nowNode = newNode; cursor++; } } if (e.getKeyCode() == KeyEvent.VK_DELETE) { if (nowNode.next != null) { nowNode.next = nowNode.next.next; cursor--; } } if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) { if (cursor > 0) { Node tmpNode = firstNode; while (tmpNode.next != nowNode) { tmpNode = tmpNode.next; } tmpNode.next = nowNode.next; nowNode = tmpNode; cursor--; } } if (e.getKeyCode() == KeyEvent.VK_LEFT) { if (cursor > 0) { cursor--; Node tmpNode = firstNode; while (tmpNode.next != nowNode) { tmpNode = tmpNode.next; } nowNode = tmpNode; } } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { if (nowNode.next != null) { cursor++; nowNode = nowNode.next; } } repaint(); } @Override public void keyReleased(KeyEvent e) { } }
如果有收获,可以请我喝杯咖啡!