这几天新写了一个记事本的源码。很多地方没有注释,先放上来吧

来源:互联网 发布:智多星水利软件 编辑:程序博客网 时间:2024/05/01 19:37


/*这段时间一直在CSDN上面学习东西很有收获,个人觉得很有必要成为一名优秀的程序员,而不是码农,更加觉得代码的质量很重要,就应该从学习的时候注意养成好习惯,看到别人的优秀之处要好好学习,更应该想办法找到自己的缺点,毕竟阻碍自己提升的人是自己,而不是客观上的其他*/


// ++++++++++MainClass.java

package com.test.MyTextEditor;


/**
 * @author 程
 *这是主函数
 */
public class MainClass {
public static void main(String[] args) {
new MYtext("文本编辑器");
}

}

//+++++++++MYtext.java

package com.test.MyTextEditor;


import java.awt.event.*;
import javax.swing.*;
import javax.swing.JToolBar.Separator;


public class MYtext extends JFrame implements ActionListener {


/**
* @author  阿程
*  请勿肆意修改
*  代码零乱,望指正!
*/

static JTextArea mytextPane; // 文本编辑区域
private JMenuBar menuBar1; // 菜单栏
private JToolBar toolBar1; // 工具栏
private JMenu menuFile, menuEdit, menuForm, menuHelp; // 菜单栏下拉菜单
private JMenuItem itemSaveOther, itemExit, itemNew, itemOpean, itemPageSet,
itemPrint, itemAbout; // “文件”子菜单
private JMenuItem itemRemove, itemCut, itemCopy, itemPaste, itemDel,
itemFound, itemFoundNext, itemReplace, itemGo, itemCheckAll,
itemTime; // “编辑”子菜单
private JMenuItem itemTextFont;
private JPopupMenu popupMenu; // 文本区域右键菜单
private JMenuItem popupMenu_Undo, popupMenu_Cut, popupMenu_Copy,
popupMenu_Paste, popupMenu_Delete, popupMenu_SelectAll; // 右键菜单的菜单项目
private JButton buttonOpean, buttonSave, buttonOtherSave; // 工具栏按钮
private JScrollPane JSPanel;
public static int x, y; // 获取本窗口的横纵坐标,以便设置后面的窗口居于本窗口的中部
static  String FilePath=null;


public MYtext(String s) {
super(s);


menuBar1 = new JMenuBar(); // 初始化菜单栏
toolBar1 = new JToolBar(); // 初始化工具栏


menuFile = new JMenu("文件<F>");
menuEdit = new JMenu("编辑<E>");
menuForm = new JMenu("格式<O>");
menuHelp = new JMenu("帮助<H>");


itemNew = new JMenuItem("新建<N>");
itemOpean = new JMenuItem("打开<O>... ");
itemSaveOther = new JMenuItem("另存为<S>...");
itemPageSet = new JMenuItem("页面设置");
itemPrint = new JMenuItem("打印");
itemExit = new JMenuItem("退出<I>");
itemAbout = new JMenuItem("关于");


itemRemove = new JMenuItem("撤销");
itemCut = new JMenuItem("剪切");
itemCopy = new JMenuItem("复制");
itemPaste = new JMenuItem("粘贴");
itemDel = new JMenuItem("删除");
itemFound = new JMenuItem("查找");
itemFoundNext = new JMenuItem("查找下一个");
itemReplace = new JMenuItem("替换");
itemGo = new JMenuItem("转到");
itemCheckAll = new JMenuItem("选择全部");
itemTime = new JMenuItem("日期 / 时间");
itemTextFont = new JMenuItem("字体格式");


buttonOpean = new JButton("打开");
buttonSave = new JButton("保存");
buttonOtherSave = new JButton("另存为");
mytextPane = new JTextArea();
JSPanel = new JScrollPane(mytextPane);
// 实例化右键菜单
popupMenu = new JPopupMenu();
popupMenu_Undo = new JMenuItem("撤消(U)", 'U');
popupMenu_Cut = new JMenuItem("剪切(T)", 'T');
popupMenu_Copy = new JMenuItem("复制(C)", 'C');
popupMenu_Paste = new JMenuItem("粘贴(P)", 'P');
popupMenu_Delete = new JMenuItem("删除(D)", 'D');
popupMenu_SelectAll = new JMenuItem("全选(A)", 'A');


// 添加热键
menuFile.setMnemonic('F');
menuEdit.setMnemonic('E');
menuForm.setMnemonic('O');
menuHelp.setMnemonic('H');
itemSaveOther.setMnemonic('S');
itemExit.setMnemonic('I');


// 添加快捷键
itemSaveOther.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
InputEvent.CTRL_MASK));
itemCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
InputEvent.CTRL_MASK));
itemCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,
InputEvent.CTRL_MASK));
itemPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,
InputEvent.CTRL_MASK));
itemDel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));


// 添加事件监听器
// 如果要在这里封装事件的话,按钮为按钮事件buttonAction,菜单项为itemAction
B_M_Actions OtherSaveAction = new B_M_Actions("othersave"); // 此处为对 另存为
// 的封装
B_M_Actions exitAction = new B_M_Actions("exit"); // 对 退出 菜单项目的封装
B_M_Actions opeanAction = new B_M_Actions("opeanfile"); // 对 打开 的封装
B_M_Actions cutAction = new B_M_Actions("textcut");
B_M_Actions copyAction = new B_M_Actions("textcopy");
B_M_Actions pasteAction = new B_M_Actions("textpaste");
B_M_Actions delAction = new B_M_Actions("textdel");
B_M_Actions checkallaction = new B_M_Actions("textall");
B_M_Actions timeaction = new B_M_Actions("time");


itemOpean.addActionListener(opeanAction);
itemSaveOther.addActionListener(OtherSaveAction);
itemCut.addActionListener(cutAction);
itemCopy.addActionListener(copyAction);
itemPaste.addActionListener(pasteAction);
itemDel.addActionListener(delAction);
itemCheckAll.addActionListener(checkallaction);
itemTime.addActionListener(timeaction);
itemExit.addActionListener(exitAction);
itemAbout.addActionListener(this);
buttonOpean.addActionListener(opeanAction);
// buttonSave.addActionListener(this);
buttonOtherSave.addActionListener(OtherSaveAction);
// 添加文本区域的键盘事件,重写Tab键 无效!
// mytextPane.addKeyListener(new KeyAdapter() {
// @Override
// public void keyPressed(KeyEvent e) {
// if (e.getKeyCode() == KeyEvent.VK_TAB) {
// mytextPane.requestFocus();
// String text ="  ";
// MYtext.mytextPane.insert(text,
// MYtext.mytextPane.getCaretPosition());
// }
// }
// });


// 将右键菜单封装
// popupMenu_Undo.addActionListener(this);
popupMenu_Cut.addActionListener(cutAction);
popupMenu_Copy.addActionListener(copyAction);
popupMenu_Paste.addActionListener(pasteAction);
popupMenu_Delete.addActionListener(delAction);
popupMenu_SelectAll.addActionListener(checkallaction);


mytextPane.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
checkForTriggerEvent(e);
}


@Override
public void mouseReleased(MouseEvent e) {
checkForTriggerEvent(e);
}


private void checkForTriggerEvent(MouseEvent e) {
if (e.isPopupTrigger())
popupMenu.show(e.getComponent(), e.getX(), e.getY());// 在组件调用者的坐标空间中的位置
// X、Y
// 显示弹出菜单。
else {
// statusLabel3.setText("当前光标所在行数: " + getlineNumber());
}
mytextPane.requestFocus(); // 编辑区获取焦点
}
});
// 添加各类组件
menuFile.add(itemNew);
menuFile.add(itemOpean);
menuFile.add(itemSaveOther);
menuFile.add(new Separator());
menuFile.add(itemPageSet);
menuFile.add(itemPrint);
menuFile.add(new Separator());
menuFile.add(itemExit);
menuEdit.add(itemRemove);
menuEdit.add(itemCut);
menuEdit.add(itemCopy);
menuEdit.add(itemPaste);
menuEdit.add(itemDel);
menuEdit.add(new Separator());
menuEdit.add(itemFound);
menuEdit.add(itemFoundNext);
menuEdit.add(itemReplace);
menuEdit.add(itemGo);
menuEdit.add(new Separator());
menuEdit.add(itemCheckAll);
menuEdit.add(itemTime);
menuForm.add(itemTextFont);
menuHelp.add(itemAbout);
menuBar1.add(menuFile);
menuBar1.add(menuEdit);
menuBar1.add(menuForm);
menuBar1.add(menuHelp);
popupMenu.add(popupMenu_Undo);
popupMenu.addSeparator();
popupMenu.add(popupMenu_Cut);
popupMenu.add(popupMenu_Copy);
popupMenu.add(popupMenu_Paste);
popupMenu.add(popupMenu_Delete);
popupMenu.addSeparator();
popupMenu.add(popupMenu_SelectAll);
toolBar1.add(buttonOpean);
toolBar1.add(new Separator());
toolBar1.add(buttonSave);
toolBar1.add(new Separator());
toolBar1.add(buttonOtherSave);


// 实现窗口布局

setJMenuBar(menuBar1);
this.add("North", toolBar1);
this.add(JSPanel);
JSPanel.requestFocus();//为什么不能获取到焦点,为什么焦点总是在工具栏的按钮上
setSize(500, 500);
setLocationRelativeTo(null);
x = this.getX() + 250;
y = this.getY() + 250;
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);


}


@Override
public void actionPerformed(ActionEvent e) // 实现事件接口方法
{
// if (e.getSource() == itemOpean || e.getSource() == buttonOpean) {
// OpeanFile file = new OpeanFile();
//
// }


// if(e.getSource()==itemSaveOther || e.getSource()==buttonOtherSave)
// { //另存为
// fd=new FileDialog(this,"文件另存为",FileDialog.SAVE);
// fd.setVisible(true);
// try{
// File f=new File(fd.getDirectory(),fd.getFile());
// FileOutputStream fos=new FileOutputStream(f);
// fos.write(mytextPane.getText().getBytes());
// fos.close();
// }catch(Exception ecp){}
// }
// if (e.getSource() == itemExit){
// System.exit(0);
// }


if (e.getSource() == itemAbout) {
MyAbout myDialog = new MyAbout(this, "我擦记事本\t____BY____阿程!", true);
myDialog.setVisible(true);
}

// 实现事件,这里不封装是为了于后面的封装进行对比
}

}

//+++++++B_M_Actions.java

package com.test.MyTextEditor;


import java.awt.FileDialog;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


//本类是按钮和菜单项的事件封装的实现


public class B_M_Actions implements ActionListener {


private String Actions;
private FileDialog fd; // 另存为对话框
// ---------------系统剪贴板
Toolkit toolKit = Toolkit.getDefaultToolkit();
Clipboard clipBoard = toolKit.getSystemClipboard();


public B_M_Actions(String Actions) {
this.Actions = Actions;
}


@Override
public void actionPerformed(ActionEvent arg0) {


if (Actions.equals("othersave")) {
fd = new FileDialog(this.fd, "文件另存为", FileDialog.SAVE);
fd.setBounds(MYtext.x - 150, MYtext.y - 150, 300, 300);
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if (name.endsWith("TXT")) {
return true;
}
return false;
}
};
fd.setFilenameFilter(filter);
fd.setVisible(true);
try {
File f = new File(fd.getDirectory(), fd.getFile());//实例化
FileOutputStream fos = new FileOutputStream(f);//文件内容输出流
fos.write(MYtext.mytextPane.getText().getBytes());
fos.close(); //关闭输出流
} catch (Exception ecp) {
}
}


if (Actions.equals("exit")) {
System.exit(0);
}


if (Actions.equals("opeanfile")) {
try {
OpeanFile file = new OpeanFile();
MYtext.FilePath = file.getFilepath();//获取到文件路径
} catch (IOException e) {
// TODO 自动生成的 catch 块
MYtext.mytextPane.setText("文件不存在!!!error!!!");
MYtext.mytextPane.setToolTipText("文件不存在");
MYtext.mytextPane.enable(false);
MYtext.mytextPane.setToolTipText("错误!!!文件不存在");
}

}


if (Actions.equals("textcut")) {
MYtext.mytextPane.requestFocus();
String text = MYtext.mytextPane.getSelectedText();
StringSelection selection = new StringSelection(text);
clipBoard.setContents(selection, null);
(MYtext.mytextPane).replaceRange("",
MYtext.mytextPane.getSelectionStart(),
MYtext.mytextPane.getSelectionEnd());


}


if (Actions.equals("textcopy")) {
MYtext.mytextPane.requestFocus();
String text = MYtext.mytextPane.getSelectedText();
StringSelection selection = new StringSelection(text);
clipBoard.setContents(selection, null);
}


if (Actions.equals("textpaste")) {
MYtext.mytextPane.requestFocus();
Transferable contents = clipBoard.getContents(this);
if (contents == null)
return;
String text;
text = "";
try {
text = (String) contents
.getTransferData(DataFlavor.stringFlavor);
} catch (Exception exception) {
}
MYtext.mytextPane.replaceRange(text,
MYtext.mytextPane.getSelectionStart(),
MYtext.mytextPane.getSelectionEnd());
}


if (Actions.equals("textdel")) {
MYtext.mytextPane.requestFocus();
MYtext.mytextPane.replaceRange("",
MYtext.mytextPane.getSelectionStart(),
MYtext.mytextPane.getSelectionEnd());
}


if (Actions.equals("textall")) {
MYtext.mytextPane.selectAll();
}


if (Actions.equals("time")) {
MYtext.mytextPane.requestFocus();
SimpleDateFormat currentDateTime = new SimpleDateFormat(
"HH:mm yyyy-MM-dd\n");
MYtext.mytextPane.insert(currentDateTime.format(new Date()),
MYtext.mytextPane.getCaretPosition());
}
}

}

//++++++OpeanFile.java

package com.test.MyTextEditor;


import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;


import java.io.File;
import java.io.FileReader;
import java.io.IOException;

//本class是实现了打开文件的文件选择器
public class OpeanFile extends JFileChooser {


public String filepath = null;
public File file=null;


public OpeanFile() throws IOException {

JFileChooser MyCh = new JFileChooser();
FileNameExtensionFilter fileFilter = new FileNameExtensionFilter(
"记事本文件(TXT)", "txt");
MyCh.setFileFilter(fileFilter);
MyCh.setBounds(MYtext.x-150, MYtext.y-150, 300, 300);
MyCh.setFileSelectionMode(JFileChooser.FILES_ONLY);
int i = MyCh.showOpenDialog(MyCh);
if (i == JFileChooser.APPROVE_OPTION) {
filepath = MyCh.getSelectedFile().getAbsolutePath();
if (filepath != null) {
file = new File(filepath);
FileReader fileReader = new FileReader(file);
int filesize = (int) file.length();//====》获取文件长度
// System.err.println(filesize);//验证长度是否变化
char[] byt = new char[filesize];//====》动态设置数组长度
int len = fileReader.read(byt);
MYtext.mytextPane.setText(new String(byt, 0, len));
MYtext.mytextPane.setToolTipText(filepath);
fileReader.close();
}
}
}

//下面的get方法是为了取出文件路径,最重要的是静态变量不安全!个人觉得没有必要不应该大量出现静态变量
public String getFilepath() {
return filepath;
}
}

//++++++package com.test.MyTextEditor;


import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
/**
 * @author 程
 *这是关于菜单的实现
 */


class MyAbout extends JDialog implements ActionListener{   //实现关于的弹窗


private JButton iAbout;
private JTextArea doNotArea;
public MyAbout (JFrame owner, String title, boolean modal){
super(owner, title, modal);
iAbout = new JButton("确定");


doNotArea = new JTextArea("未实现的功能:\n    查找相关的功能,文件保存,退出检测文件修改,\n自动换行功能,自动识别编码功能,打印功能,字体设置功能");
iAbout.addActionListener(this);

doNotArea.setEditable(false);
setLayout(new FlowLayout());
add(doNotArea);
add(iAbout);
setResizable(false);
setBounds(MYtext.x-225, MYtext.y-50, 450, 100);
validate(); //确保窗口布局有效,去掉这段代码也没有影响
}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == iAbout)
this.setVisible(false);

}

}



0 0