Skip to content

Instantly share code, notes, and snippets.

@shonenada
Created December 12, 2012 10:54
Show Gist options
  • Save shonenada/4266895 to your computer and use it in GitHub Desktop.
Save shonenada/4266895 to your computer and use it in GitHub Desktop.
my notepad in java
package Notepad;
import java.awt.*;
import javax.swing.*;
import java.awt.Toolkit;
public abstract class DFrame extends JFrame{
/**
* 窗口尺寸参数
* WIN_HEIGHT integer 窗口高度
* WIN_WIDTH integer 窗口宽度
*/
protected int WIN_HEIGHT = 0;
protected int WIN_WIDTH = 0;
static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
DFrame(String title, int width, int height){
setTitle(title);
setWinWidth(width);
setWinHeight(height);
flushSize();
setMiddleLocation();
showWin();
InitLayout();
validate();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
int getWinWidth(){
return this.WIN_WIDTH;
}
int getWinHeight(){
return this.WIN_HEIGHT;
}
void setWinWidth(int width){
this.WIN_WIDTH = width;
flushSize();
}
void setWinHeight(int height){
this.WIN_HEIGHT = height;
flushSize();
}
void flushSize(){
setSize(this.WIN_WIDTH, this.WIN_HEIGHT);
}
void setMiddleLocation(){
setLocation(getMidHorizontal(this.WIN_WIDTH), getMidVertical(this.WIN_HEIGHT));
}
void showWin(){
setVisible(true);
}
void hideWin(){
setVisible(false);
}
void closeWin(){
this.hideWin();
this.dispose();
}
abstract void InitLayout();
static int getMidHorizontal(int width){
return (screenSize.width-width)/2;
}
static int getMidVertical(int height){
return (screenSize.height-height)/2;
}
static void print(String str){
System.out.println(str);
}
static void print(int s){
System.out.println(s);
}
}
package Notepad;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.*;
class Window extends DFrame implements ActionListener, KeyListener{
/**
* 菜单参数
* menubar JMenuBar 顶部菜单
* menu_file JMenu 文件菜单
* item_file JMenuItem[] 文件菜单项目
*/
JMenuBar menubar;
JLabel statuebar;
JMenu menu_file;
JMenu menu_edit;
JMenu menu_help;
JMenuItem[] item_file;
JMenuItem[] item_edit;
JMenuItem[] item_help;
String temp = "";
UndoWrapper undowrapper;
private String filename = "";
private boolean saved = false;
/**
* Editor JTextArea 编辑器
*/
JTextArea editor;
JScrollPane pane;
Window(String s){
super(s,800,600);
InitMenuBar();
InitPopup();
this.setBackground(new Color(255,255,255));
editor.addKeyListener(this);
undowrapper = new UndoWrapper(editor);
validate();
}
void setStatue(String s){
statuebar.setText(" "+s);
}
void InitMenuBar(){
item_file = new JMenuItem[5];
item_edit = new JMenuItem[9];
item_help = new JMenuItem[1];
menubar = new JMenuBar();
menu_file = new JMenu("文件");
item_file[0] = new JMenuItem("新建");
item_file[0].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));
item_file[0].addActionListener(this);
item_file[1] = new JMenuItem("打开");
item_file[1].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
item_file[1].addActionListener(this);
item_file[2] = new JMenuItem("保存");
item_file[2].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
item_file[2].addActionListener(this);
item_file[3] = new JMenuItem("另保存");
item_file[3].addActionListener(this);
item_file[4] = new JMenuItem("退出");
item_file[4].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, InputEvent.CTRL_MASK));
item_file[4].addActionListener(this);
menu_file.add(item_file[0]);
menu_file.addSeparator();
menu_file.add(item_file[1]);
menu_file.add(item_file[2]);
menu_file.add(item_file[3]);
menu_file.addSeparator();
menu_file.add(item_file[4]);
menu_edit = new JMenu("编辑");
item_edit[0] = new JMenuItem("撤销");
item_edit[0].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_MASK));
item_edit[0].addActionListener(this);
item_edit[1] = new JMenuItem("恢复");
item_edit[1].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_MASK));
item_edit[1].addActionListener(this);
item_edit[2] = new JMenuItem("剪切");
item_edit[2].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK));
item_edit[2].addActionListener(this);
item_edit[3] = new JMenuItem("复制");
item_edit[3].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK));
item_edit[3].addActionListener(this);
item_edit[4] = new JMenuItem("黏贴");
item_edit[4].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK));
item_edit[4].addActionListener(this);
item_edit[5] = new JMenuItem("全选");
item_edit[5].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK));
item_edit[5].addActionListener(this);
item_edit[6] = new JMenuItem("删除");
item_edit[6].addActionListener(this);
item_edit[7] = new JMenuItem("查找与替换");
item_edit[7].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_MASK));
item_edit[7].addActionListener(this);
menu_edit.add(item_edit[0]);
menu_edit.add(item_edit[1]);
menu_edit.addSeparator();
menu_edit.add(item_edit[2]);
menu_edit.add(item_edit[3]);
menu_edit.add(item_edit[4]);
menu_edit.add(item_edit[5]);
menu_edit.add(item_edit[6]);
menu_edit.addSeparator();
menu_edit.add(item_edit[7]);
menu_help = new JMenu("帮助");
item_help[0] = new JMenuItem("关于");
item_help[0].setAccelerator(KeyStroke.getKeyStroke("F1"));
item_help[0].addActionListener(this);
menu_help.add(item_help[0]);
menubar.add(menu_file);
menubar.add(menu_edit);
menubar.add(menu_help);
setJMenuBar(menubar);
}
JPopupMenu menu;
JMenuItem itemCopy, itemCut, itemPaste, itemSelect, itemDelete;
void InitPopup(){
menu = new JPopupMenu();
itemCopy = new JMenuItem("复制");
itemCut = new JMenuItem("剪切");
itemPaste = new JMenuItem("粘帖");
itemSelect = new JMenuItem("全选");
itemDelete = new JMenuItem("删除");
menu.add(itemCopy);
menu.add(itemCut);
menu.add(itemPaste);
menu.add(itemSelect);
menu.add(itemDelete);
editor.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
if (e.getModifiers() == InputEvent.BUTTON3_MASK)
menu.show(editor, e.getX(), e.getY());
}
});
itemCopy.addActionListener(this);
itemCut.addActionListener(this);
itemPaste.addActionListener(this);
itemSelect.addActionListener(this);
itemDelete.addActionListener(this);
}
void InitLayout(){
statuebar = new JLabel(" ");
editor = new JTextArea("");
editor.setBackground(new Color(255,255,255));
editor.setLineWrap(true);
statuebar.setBackground(new Color(200,200,200));
add(statuebar, BorderLayout.SOUTH);
pane = new JScrollPane(editor);
add(pane, BorderLayout.CENTER);
setStatue("欢迎使用");
}
public void actionPerformed(ActionEvent e) {
// 退出
if(e.getSource() == item_file[4]){
this.hideWin();
this.dispose();
}
// 撤销
if( e.getSource() == item_edit[0] ){
undowrapper.getUndoAction().actionPerformed(null);
}
// 回复
if ( e.getSource() == item_edit[1] ) {
undowrapper.getRedoAction().actionPerformed(null);
}
// 剪切
if( e.getSource() == item_edit[2] ){
editor.cut();
}
// 复制
if ( e.getSource() == item_edit[3] ){
editor.copy();
}
// 黏贴
if ( e.getSource() == item_edit[4] ){
editor.paste();
}
// 全选
if ( e.getSource() == item_edit[5] ){
editor.selectAll();
}
// 删除
if ( e.getSource() == item_edit[6] ){
int start = editor.getSelectionStart();
int end = editor.getSelectionEnd();
String txt = editor.getText();
String str = txt.substring(0, start) + txt.substring(end, txt.length());
editor.setText(str);
}
// 查找与替换
if ( e.getSource() == item_edit[7] ){
FindWin win_find = new FindWin();
win_find.showWin();
win_find.setJTextArea(this.editor);
}
// 关于
if(e.getSource() == item_help[0]){
AboutWin win_about = new AboutWin();
win_about.showWin();
}
if (e.getSource() == itemCopy){
editor.copy();
}
if (e.getSource() == itemCut){
editor.cut();
}
if (e.getSource() == itemPaste){
editor.paste();
}
if (e.getSource() == itemDelete){
int start = editor.getSelectionStart();
int end = editor.getSelectionEnd();
String txt = editor.getText();
String str = txt.substring(0, start) + txt.substring(end, txt.length());
editor.setText(str);
}
if (e.getSource() == itemSelect){
editor.selectAll();
}
if ( e.getSource() == item_file[0] ){
if(!this.saved && editor.getText().length() != 0 ){
int click = JOptionPane.showConfirmDialog(null, "当前文件未保存,是否保存?", "记事本", JOptionPane.YES_NO_CANCEL_OPTION);
if (click == JOptionPane.YES_OPTION){
this.saveAs();
}
else if (click == JOptionPane.NO_OPTION){
this.newfile();
}
else if(click == JOptionPane.CANCEL_OPTION){
return ;
}
}else{
this.newfile();
}
}
if ( e.getSource() == item_file[1] ){
JFileChooser chooser = new JFileChooser(filename);
FileNameExtensionFilter filter = new FileNameExtensionFilter("文本文档(*.txt)","txt");
chooser.setFileFilter(filter);
int chval = chooser.showOpenDialog(this);
if(chval == JFileChooser.APPROVE_OPTION){
filename=chooser.getSelectedFile().getAbsolutePath();
try{
File file=new File(filename);
FileInputStream in=new FileInputStream(file);
byte b[]=new byte[(int)file.length()];
in.read(b);
in.close();
editor.setText(new String(b));
setTitle(filename);
this.setSaved();
}
catch(IOException ep){
JOptionPane.showMessageDialog(null, "打开文件失败");
}
}
}
if ( e.getSource() == item_file[2] ){
File file = new File(filename);
if (file.exists()){
try{
FileOutputStream in = new FileOutputStream(filename);
in.write(editor.getText().getBytes());
in.close();
this.setSaved();
}
catch(IOException ex){
ex.getStackTrace();
}
}
else{
this.saveAs();
}
}
if ( e.getSource() == item_file[3] ){
this.saveAs();
}
}
@Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
if ( arg0.getSource() == editor ){
this.setUnSaved();
}
}
@Override
public void keyReleased(KeyEvent k) {
// 使用空间太多
if ( k.getSource() == editor ){
}
}
@Override
public void keyTyped(KeyEvent k) {
}
boolean isAllowInput(int input){
if ( (input>=32 && input<=126) || input==8 || input==13 || input == 127 ){
return true;
}else{
return false;
}
}
void saveAs(){
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("文本文档(*.txt)","txt");
chooser.setFileFilter(filter);
int chval = chooser.showSaveDialog(this);
if (chval == JFileChooser.APPROVE_OPTION){
String temp = filename;
filename = chooser.getSelectedFile().getAbsolutePath();
File file = new File(filename);
if (file.exists()){
int click = JOptionPane.showConfirmDialog(null, "文件已存在,是否替换?","记事本",JOptionPane.YES_NO_OPTION);
if (click == JOptionPane.YES_OPTION){
this.saveFile();
}
else if(click == JOptionPane.NO_OPTION){
filename = temp;
return ;
}
}else{
this.saveFile();
}
}
}
void saveFile(){
FileOutputStream in;
try {
in = new FileOutputStream(filename);
in.write(editor.getText().getBytes());
in.close();
this.setSaved();
} catch (IOException e) {
e.printStackTrace();
}
}
void newfile(){
filename = "";
editor.setText("");
}
void setSaved(){
this.saved = true;
setStatue("已保存");
}
void setUnSaved(){
this.saved = false;
setStatue("未保存");
}
}
class AboutWin extends DFrame implements ActionListener{
JLabel Label_title;
JLabel Label_author;
JLabel Label_infor;
JButton Btn_close;
AboutWin(){
super("关于",300,200);
InitLayout();
}
void InitLayout(){
setLayout(null);
Label_title = new JLabel("<html><font size=+2>关于</font></html>", JLabel.CENTER);
Label_author = new JLabel("作者: Lyd.", JLabel.LEFT);
Label_infor = new JLabel("<html><p>Copyright by Lyd</p></html>", JLabel.LEFT);
Btn_close = new JButton("关闭");
add(Label_title);
add(Label_author);
add(Label_infor);
add(Btn_close);
Label_title.setBounds(90,5,100,40);
Label_title.setVerticalAlignment(JLabel.TOP);
Label_author.setBounds(5,50,300,25);
Label_author.setVerticalAlignment(JLabel.TOP);
Label_infor.setBounds(5,85,300,25);
Label_infor.setVerticalAlignment(JLabel.TOP);
Btn_close.setBounds(100,120,80,30);
Btn_close.setVerticalAlignment(JButton.TOP);
Btn_close.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
// if( e.getSource() == Btn_close ){
this.hideWin();
this.dispose();
// }
}
}
class FindWin extends DFrame implements ActionListener{
JTextField subStr;
JTextField replaceStr;
JButton findBtn;
JButton replaceBtn;
JButton findAndReplaceBtn;
JButton replaceAllBtn;
JButton cancelBtn;
FindWin(){
super("查找", 300, 300);
}
void InitLayout(){
setLayout(null);
JLabel findLabel = new JLabel("查找:");
JLabel replaceLabel = new JLabel("替换:");
subStr = new JTextField();
replaceStr = new JTextField();
findBtn = new JButton("查找");
replaceBtn = new JButton("替换");
replaceAllBtn = new JButton("替换所有");
cancelBtn = new JButton("取消");
findBtn.addActionListener(this);
replaceBtn.addActionListener(this);
replaceAllBtn.addActionListener(this);
cancelBtn.addActionListener(this);
getRootPane().setDefaultButton(findBtn);
add(findLabel);
add(replaceLabel);
add(subStr);
add(replaceStr);
add(findBtn);
add(replaceBtn);
add(replaceAllBtn);
add(cancelBtn);
findLabel.setBounds(20, 20, 50, 30);
replaceLabel.setBounds(20, 70, 50, 30);
subStr.setBounds(80, 20, 150, 30);
replaceStr.setBounds(80, 70, 150, 30);
findBtn.setBounds(55, 120, 80, 30);
replaceBtn.setBounds(145, 120, 80, 30);
replaceAllBtn.setBounds(30, 170, 120, 30);
cancelBtn.setBounds(160, 170, 80, 30);
}
// ******************** 按钮动作 ********************************* //
String pattern; //替换的模式
String str; // 原文
String re; //替换字符串
JTextArea text;
int index = -1;
boolean flag = false;
@Override
public void actionPerformed(ActionEvent e) {
// 关闭
if (e.getSource() == cancelBtn){
this.closeWin();
}
// 查找
if (e.getSource() == findBtn){
this.find();
}
// 替换
if ( e.getSource() == replaceBtn ){
this.replace();
}
// 替换全部
if ( e.getSource() == replaceAllBtn ){
getFullText();
if(!pattern.equals("")){
str = str.replace(pattern, re);
text.setText(str);
}
}
}
void getFullText(){
pattern = subStr.getText();
str = text.getText();
re = replaceStr.getText();
}
void find(){
String pattern = subStr.getText();
index = KMP.findSub(text.getText(), pattern, this.index+1);
if (index != -1){
text.select(index, index + pattern.length());
flag = false;
}else{
text.select(0,0);
if ( !flag ){
flag = true;
this.index = -1;
find();
}else{
JOptionPane.showMessageDialog(null, "找不到字符串");
}
}
}
void replace(){
getFullText();
if(pattern.equals("")||str.equals("")||re.equals("")){
return ;
}
if(this.index != -1){
int find_len = pattern.length();
int str_len = str.length();
String lastStr = str.substring(0, index) + re + str.substring(index + find_len, str_len);
text.setText(lastStr);
this.find();
}else{
find();
}
}
void setJTextArea(JTextArea s){
text = s;
}
}
package Notepad;
public class KMP {
static int[] getNext(String p){
int i=1,j=0;
int[] next = new int[p.length()+2];
char[] pattern = p.toCharArray();
next[0] = -1;
next[1] = 0;
while(i<p.length()-1){
if(pattern[i] == pattern[j]){
i++;
j++;
next[i] = next[j];
}
else if(j == 0){
next[i+1] = 0;
i++;
}
else{
j = next[j];
}
}
return next;
}
static int findKMPSub(String str, String p,int start, int next[]){
char[] string = str.toCharArray();
char[] pattern = p.toCharArray();
int i = start;
int j=0,v;
while(i<str.length() && j<p.length()){
if(j == -1 || string[i] == pattern[j]){
i++;
j++;
}
else{
j = next[j];
}
}
if ( j == p.length()){
v = i - p.length();
}else{
v = -1;
}
return v;
}
static int findSub(String str, String p, int start){
int m = p.length();
int[] next = new int[m];
next = getNext(p);
int v = findKMPSub(str,p,start,next);
return v;
}
}
package Notepad;
public class Notepad {
public static void main(String args[]){
Window w = new Window("记事本");
}
}
package Notepad;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JEditorPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.JTextComponent;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
public class UndoWrapper implements UndoableEditListener
{
private UndoManager undoManager;
private UndoAction undoAction;
private RedoAction redoAction;
private JTextArea textComponent;
/**
* Creates a new instance of UndoWrapper
*/
public UndoWrapper( JTextArea aComponent )
{
textComponent = aComponent;
undoManager = new UndoManager();
undoAction = new UndoAction();
redoAction = new RedoAction();
textComponent.getDocument().addUndoableEditListener( this );
textComponent.getInputMap().put( (KeyStroke) undoAction.getValue(
Action.ACCELERATOR_KEY), "undo" );
textComponent.getInputMap().put( (KeyStroke) redoAction.getValue(
Action.ACCELERATOR_KEY), "redo" );
textComponent.getActionMap().put( "undo", undoAction );
textComponent.getActionMap().put( "redo", redoAction );
}
public void undoableEditHappened(UndoableEditEvent e)
{
undoManager.addEdit( e.getEdit() );
undoAction.updateUndoState();
redoAction.updateRedoState();
}
/**
* UndoAction is the Action responsible for handling the undo operation.
*/
class UndoAction
extends AbstractAction
{
public UndoAction()
{
super( "Cannot undo" ); // TODO: I18N
setEnabled( false );
// putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("ctrl Z") );
}
public void actionPerformed(ActionEvent e)
{
try
{
undoManager.undo();
}
catch( CannotUndoException cue )
{
// TODO: Use logging?
cue.printStackTrace( System.err );
}
updateUndoState();
redoAction.updateRedoState();
}
void updateUndoState()
{
if ( undoManager.canUndo() )
{
setEnabled( true );
putValue( Action.NAME, "Undo" ); // TODO I18N
}
else
{
setEnabled( false );
putValue( Action.NAME, "Cannot undo" ); // TODO I18N
}
}
}
/**
* RedoAction is the Action responsible for handling the redo operation.
*/
class RedoAction
extends AbstractAction
{
public RedoAction()
{
super( "Cannot redo" ); // TODO I18N
setEnabled( false );
// putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("ctrl Y") );
}
public void actionPerformed(ActionEvent e)
{
try
{
undoManager.redo();
}
catch( CannotRedoException cre )
{
// TODO: Use logging?
cre.printStackTrace( System.err );
}
updateRedoState();
undoAction.updateUndoState();
}
void updateRedoState()
{
if ( undoManager.canRedo() )
{
setEnabled( true );
putValue( Action.NAME, "Redo" ); // TODO I18N
}
else
{
setEnabled( false );
putValue( Action.NAME, "Cannot redo" ); // TODO I18N
}
}
}
UndoAction getUndoAction()
{
return undoAction;
}
RedoAction getRedoAction()
{
return redoAction;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment