java记事本
本软件描述:
本软件是模拟Windows XP的记事本功能,还扩展了一些功能,如改变字体的颜色,加上了,背景颜色,和插入图片的功能等,此软件作品还有很多的不足之处,还各位高手指点迷津,互相学习.本人联系方式(QQ):631818332
功能描述:
1、在文件菜单里面实现了新建文本编辑器,打开文件,保存文件,另存为文件,退出文本编辑器.功能
2、在编辑菜单里面实现了撤销,恢复,剪切,复制,粘贴,删除,查找,查找下一个,替换,
全选,时间/日期.功能
3、在格式菜单上实现了插入图片,改变字体,改变字体颜色,背景颜色,视图风格,增加下划线功能
4、在查看菜单上实现了状态栏,字数统计功能
5、在帮助菜单中现了帮助主题,关干的功能.
一、 设计描述
类描述:
/*********************主类******************/
public class TextEditor{
/**main()方法*/
public static void main(String args[]) {
new Note(); //实例化一个Note类
}
}
Note类
是一个功能类
public Note(){} //构造方法
/**addToolBar()方法用来设置工具条***/
private void addToolBar(int num,String label,String icon,ActionListener listen){}
/** 内部类fileAction,用来处理文件菜单事件 **/
public class fileAction implements ActionListener {}
/** 内部类editAction,用来处理编辑菜单事件 **/
public class editAction implements ActionListener {}
/** 内部类formatAction,用来处理格式菜单事件 **/
public class formatAction implements ActionListener {}
/** 内部类viewAction,用来处理查看菜单事件 **/
public class viewAction implements ActionListener {}
/** 内部类helpAction,用来处理帮助菜单事件 **/
public class helpAction implements ActionListener { }
/** 内部类mouseAction,用来处理鼠标事件 **/
public class mouseAction extends MouseAdapter {}
/**内部类documentlis用来处理文档内容变化事件***/
public class documentlis implements DocumentListener{ }
public void insertIcon(File file) { } //插入图片的方法片
public void insertDoc(StyledDocument styledDoc, String content,String currentStyle){}//插入风格字体
public void createStyle(String style,StyledDocument doc,int size,boolean bold,boolean italic,Color color,String fontName){}//创建风格
public void openFile(){} //打开文件
public void saveAsFile() { } //另存为
public void saveFile(){ } //保存
public void exitText(){ } //退出文本的相关操作
其他类:
/*********用干文件过滤的外部类***********/
class JavaFileFilter extends FileFilter { }
class TxtFileFilter extends FileFilter {}
/**类FindDialog用来进行查找***/
public class FindDialog extends JDialog implements ActionListener{ }
/*******类setupFont用来设置字体*********/
public class FontDialog extends JDialog implements ActionListener { }
/**类HelpTheme用来设置帮助主题**/
public class HelpTheme extends JFrame implements ActionListener{ }
遇到的难题与解决方案:
1.、怎么样读取文件内容和保存文件内容,运用java 文件操作。运用JFileChooser,
先取得文件路径.然后就运用FileReader来进行读取文件的内容,运用FileWriter来保存文档里面的内容..
2、 如何改变所选择字体的颜色和大小?运用StyleDocument,来先建立风格,然后再插入风格字体,每次改变的时候先移除风格,再进行相应的操作.
3、 如何实现模糊查找与替换?利用正则表达式,用到Pattern 和Matcher来解决问题
4、 怎么样能够快速的初始化窗口?解决方法就是通过把重复的代码写进一个方法里面来实现,做到了代码重用。
5、 怎么样知道文本的内容是否改变?通过实现设置一个标记变量。然后用实现DocumentListener这一个接口,在里面的方法中把变量设置为true。这个样子就可以通过这一个标记变量来看文本的内容是否改变了。
6、 怎么样能够快速的得到多种颜色?利用到JColorChooser来取得。
二、 总结
做完这个作品做我学到了很多的知识,比如说的就是java的异常处理文件读取,保存、用到正则表达式来进行模糊查找要找的字符串、利用java中的swing包来手工制作图形用户界面与java中的事件处理、内部类和外部类的使用方法、代码重用的方法、菜单的使用方法和给菜单添加上快捷方式等。当做软件开发的时候就要不断的学习,从而获得更大的进步,在开发的过程中发现自己的不足,汲取别人的长处.多向别人请教.不要不懂装懂.
三、作者
桂林电子科技大学
06级 软件工程
陈剑龙
- package javadesign;
- import java.awt.*;
- import java.util.regex.*;
- import javax.swing.*;
- import javax.swing.event.DocumentEvent;
- import javax.swing.event.DocumentListener;
- import javax.swing.filechooser.FileFilter;
- import java.awt.event.*;
- import java.util.*;
- import java.io.*;
- import javax.swing.text.*;
- import javax.swing.undo.UndoManager;
- /*********************主类******************/
- public class TextEditor{
- /**main()方法*/
- public static void main(String args[]) {
- new Note();
- }
- }
- /*************************Note类******************/
- class Note {
- private File currentFile=null;
- private JFrame frame=new JFrame("无标题 - 文字编辑");
- private JMenuBar menuBar = new JMenuBar(); //菜单栏
- private JMenu fileMenu = new JMenu("文件(F)");
- private JMenu editMenu = new JMenu("编辑(E)");
- private JMenu formatMenu = new JMenu("格式(O)");
- private JMenu helpMenu = new JMenu("帮助(H)");
- private JMenu viewMenu = new JMenu("查看(V)");
- private JToolBar toolbar = new JToolBar(); //工具条
- private JMenuItem undoItem,redoItem,findItem, findnextItem;
- private JButton newButton,openButton,saveButton,deleteButton;
- private JButton undoButton,redoButton,copyButton,cutButton,pasteButton;
- private JRadioButtonMenuItem windows,metal,motif;
- private ButtonGroup group=new ButtonGroup();
- private StyledDocument styledDoc=new DefaultStyledDocument();
- public static JTextPane display; //JTextPane对象
- private JScrollPane scroll;
- private JPopupMenu popupmenu = new JPopupMenu(); //右键菜单
- private Color color;
- public static String font_name = "宋体";
- public static int font_size = 20, font_type = Font.PLAIN;
- public static int xp= 400, yp = 100;
- private Container container=frame.getContentPane(); //获得内容面板
- private Document doc ;
- /** 添加撤消管理器 */
- private UndoManager undomang=new UndoManager();
- private UIManager.LookAndFeelInfo looks[]= UIManager.getInstalledLookAndFeels(); //风格
- private JLabel statusbar=new JLabel();
- public static boolean selectflag=true;
- private boolean bold,italic,change,newflag,exitflag,windowflag;
- private boolean openflag;/
- public Note() {
- frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); //窗口关闭时不自动处理
- frame.setSize(500, 650); //设置窗口的大小
- frame.setIconImage(Toolkit.getDefaultToolkit().getImage("title.gif")); //给窗口加上图标
- frame.setLocation(400, 100); //设置窗口显示的位置
- statusbar.setHorizontalAlignment(JLabel.RIGHT); //设置状态栏在右边显示信息
- windows=new JRadioButtonMenuItem("系统风格",false); //风格按键初始化
- motif=new JRadioButtonMenuItem("MOTIF风格",false);
- metal=new JRadioButtonMenuItem("默认风格",true);
- group.add(windows); //这样能实现单选
- group.add(motif);
- group.add(metal);
- display= new JTextPane(styledDoc);
- styledDoc.addDocumentListener(new documentLis());//
- doc=display.getDocument();
- toolbar.setEnabled(false); //设置工具条为不要编辑
- doc.addUndoableEditListener(undomang); //添加事件监听
- frame.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- if(change) {
- windowflag=true;
- exitText();
- } else System.exit(0);
- }
- });
- fileMenu.setMnemonic(KeyEvent.VK_F);//添加相应的快捷方式
- editMenu.setMnemonic(KeyEvent.VK_E);
- formatMenu.setMnemonic(KeyEvent.VK_O);
- helpMenu.setMnemonic(KeyEvent.VK_H);
- viewMenu.setMnemonic(KeyEvent.VK_V);
- container.setLayout(new BorderLayout()); //设置布局
- container.add(display, "Center");
- container.add(toolbar,"North");
- container.add(statusbar,"South");
- display.setFont(new Font("宋体", Font.PLAIN, 20)); //设置字体
- scroll = new JScrollPane(display); //给文档加上滚动条
- container.add(scroll);
- frame.setJMenuBar(menuBar); //添加菜单栏
- /** 生成监听器实例对象*/
- ActionListener file = new fileAction();
- ActionListener edit = new editAction();
- ActionListener format = new formatAction();
- ActionListener help = new helpAction();
- MouseListener mouse = new mouseAction();
- ActionListener view = new viewAction();
- /**设置文件菜单*/
- addMenuItem(KeyEvent.VK_N,0, "文件", "新建(N)", 'N', file,fileMenu,true,"new.gif");
- addMenuItem(KeyEvent.VK_O,1, "文件", "打开(O)...", 'O', file,fileMenu,false,"open.gif");
- addMenuItem(KeyEvent.VK_S,2, "文件", "保存(S)", 'S', file ,fileMenu,false,"save.gif");
- addMenuItem(KeyEvent.VK_A,3, "文件", "另存为(A)...", '0', file,fileMenu,false,null);
- addMenuItem(KeyEvent.VK_X,4, "文件", "退出(X)", '0', file,fileMenu,false,null);
- /**设置编辑菜单*/
- addMenuItem(KeyEvent.VK_U,0, "编辑", "撤销(U)", 'Z', edit,editMenu,true,"undo.gif");
- addMenuItem(KeyEvent.VK_R,1, "编辑", "恢复(R)", 'Y', edit,editMenu,false,"redo.gif");
- addMenuItem(KeyEvent.VK_T,2, "编辑", "剪切(T)", 'X', edit,editMenu,false,"cut.gif");
- addMenuItem(KeyEvent.VK_C,3, "编辑", "复制(C)", 'C', edit,editMenu,false,"copy.gif");
- addMenuItem(KeyEvent.VK_P,4, "编辑", "粘贴(P)", 'V', edit,editMenu,false,"paste.gif");
- addMenuItem(KeyEvent.VK_L,5, "编辑", "删除(L)", '0', edit,editMenu,false,"delete.gif");
- addMenuItem(KeyEvent.VK_F,6, "编辑", "查找(F)", 'F', edit,editMenu,false,"find.gif");
- addMenuItem(KeyEvent.VK_N,7, "编辑", "查找下一个(N)", '0', edit,editMenu,false,null);
- addMenuItem(KeyEvent.VK_E,8, "编辑", "替换(E)", 'Q', edit,editMenu,false,"change.gif");
- addMenuItem(KeyEvent.VK_A,9,"编辑", "全选(A)", 'A', edit,editMenu,false,null);
- addMenuItem(KeyEvent.VK_D,10,"编辑", "时间/日期(D)", '0', edit,editMenu,false,null);
- /**设置格式菜单*/
- addMenuItem(KeyEvent.VK_W,0, "格式", "插入图片(W)", '0', format,formatMenu,true,null);
- addMenuItem(KeyEvent.VK_F,1, "格式", "字体(F)", '0', format,formatMenu,false,null);
- addMenuItem(KeyEvent.VK_C,2, "格式", "颜色(C)", '0', format,formatMenu,false,null);
- addMenuItem(KeyEvent.VK_S,3,"格式","视图风格(S)",'0',format,formatMenu,false,null);
- addMenuItem(KeyEvent.VK_U,4,"格式","下划线(U)",'0',format,formatMenu,false,null);
- /**设置查看菜单*/
- addMenuItem(KeyEvent.VK_W,1, "查看", "字数统计(W)", '0', view,viewMenu,true,null);
- /**设置帮助菜单*/
- addMenuItem(KeyEvent.VK_H,0, "帮助", "帮助主题(H)", '0', help,helpMenu,true,"help.gif");
- addMenuItem(KeyEvent.VK_A,1, "帮助", "关于(A)", '0', help,helpMenu,false,null);
- /**设置右键菜单*/
- addPopupMenu(KeyEvent.VK_U, "撤销(U)", mouse, edit);
- addPopupMenu(KeyEvent.VK_R, "恢复(R)", mouse, edit);
- addPopupMenu(KeyEvent.VK_T, "剪切(T)", mouse, edit);
- addPopupMenu(KeyEvent.VK_C, "复制(C)", mouse, edit);
- addPopupMenu(KeyEvent.VK_P, "粘贴(P)", mouse, edit);
- addPopupMenu(KeyEvent.VK_L, "删除(L)", mouse, edit);
- addPopupMenu(KeyEvent.VK_A, "全选(A)", mouse, edit);
- addPopupMenu(KeyEvent.VK_D, "时间/日期(D)", mouse, edit);
- /**设置工具条**/
- addToolBar(0,"新建","new.gif",file);
- addToolBar(1,"打开","open.gif",file);
- addToolBar(2,"保存","save.gif",file);
- addToolBar(3,"撤销","undo.gif",edit);
- addToolBar(4,"恢复","redo.gif",edit);
- addToolBar(5,"剪切","cut.gif",edit);
- addToolBar(6,"复制","copy.gif",edit);
- addToolBar(7,"粘贴","paste.gif",edit);
- addToolBar(8,"删除","delete.gif",edit);
- frame.setVisible(true);
- }
- /**addToolBar()方法用来设置工具条***/
- private void addToolBar(int num,String label,String icon,ActionListener listen) {
- JButton button=new JButton(new ImageIcon(icon));
- button.setToolTipText(label); //设置提示信息
- toolbar.add(button); //添加按键
- button.addActionListener(listen); //添加监听
- toolbar.addSeparator(); //添加分隔条
- switch(num){
- case 0:newButton=button;break;
- case 1:openButton=button;break;
- case 2:saveButton=button;break;
- case 3:undoButton=button;break;
- case 4:redoButton=button;break;
- case 5:cutButton=button;break;
- case 6:copyButton=button;break;
- case 7:pasteButton=button;break;
- case 8:deleteButton=button;break;
- }
- }
- /**addText()方法用来设置右键菜单*/
- private void addPopupMenu(int num, String label, MouseListener listen1,ActionListener listen2) {
- display.add(popupmenu);
- JMenuItem menuItem = new JMenuItem(label);
- menuItem.setMnemonic(num);
- if (label.equals("剪切(T)") || label.equals("全选(A)"))
- popupmenu.addSeparator(); //添加分隔条
- popupmenu.add(menuItem);
- display.addMouseListener(listen1);//注册监听器的接口MouseListener
- menuItem.addActionListener(listen2);//注册监听器的接口ActionListener
- }
- /**addMenuItem()方法用来设置菜单*/
- private void addMenuItem(int count,int num, String menulabel, String itemlabel,
- char shortlabel, ActionListener listen,JMenu menu,boolean bool,String icon) {
- JMenuItem menuItem;
- if(bool) menuBar.add(menu);
- if(icon!=null){
- menuItem = new JMenuItem(itemlabel,new ImageIcon(icon));
- }
- else menuItem=new JMenuItem(itemlabel);
- menuItem.setMnemonic(count); //添加快捷方式
- if (shortlabel != '0')
- menuItem.setAccelerator(KeyStroke.getKeyStroke(shortlabel,KeyEvent.CTRL_MASK));//添加组合快捷键的操作
- menuItem.addActionListener(listen);//注册监听器的接口ActionListener
- /*设置文件*/
- if (menulabel.equals("文件")) {
- fileMenu.add(menuItem);
- if(num==3) fileMenu.addSeparator();
- }
- /*设置编辑*/
- else if (menulabel.equals("编辑")) {
- editMenu.add(menuItem);
- switch (num) {
- case 0:undoItem = menuItem; //撤销
- undoItem.setEnabled(false);
- break;
- case 1: redoItem=menuItem; //恢复
- redoItem.setEnabled(false);
- editMenu.addSeparator();break;
- case 5: //删除
- menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0));
- editMenu.addSeparator(); break;
- case 6:findItem = menuItem;
- findItem.setEnabled(false);break;//查找
- case 7:findnextItem = menuItem; //查找下一个
- findnextItem.setEnabled(false);
- menuItem.setAccelerator(KeyStroke.getKeyStroke("F3"));break;
- case 10:menuItem.setAccelerator(KeyStroke.getKeyStroke("F5")); //时间/日期
- }
- }
- /*设置格式*/
- else if (menulabel.equals("格式")) {
- switch (num) {
- case 0:formatMenu.add(menuItem); //插入
- formatMenu.addSeparator(); break;
- case 1:formatMenu.add(menuItem);break; //字体
- case 2:JMenu colorMenu = new JMenu(itemlabel); //颜色
- formatMenu.add(colorMenu);
- JMenuItem backColor = new JMenuItem("背景颜色(B)");
- JMenuItem fontColor = new JMenuItem("字体颜色(F)");
- colorMenu.add(backColor);
- colorMenu.addSeparator();
- colorMenu.add(fontColor);
- colorMenu.setMnemonic(KeyEvent.VK_C);
- backColor.setMnemonic(KeyEvent.VK_B);
- fontColor.setMnemonic(KeyEvent.VK_F);
- backColor.addActionListener(listen);//注册监听器的接口ActionListener
- fontColor.addActionListener(listen);//注册监听器的接口ActionListener
- break;
- case 3: //视图风格
- JMenu styleMenu= new JMenu(itemlabel);
- styleMenu.setMnemonic(KeyEvent.VK_S);
- formatMenu.add(styleMenu);
- styleMenu.add(metal);
- styleMenu.add(windows);
- styleMenu.add(motif);
- metal.addActionListener(listen);
- windows.addActionListener(listen);
- motif.addActionListener(listen); break;
- case 4:formatMenu.add(menuItem);
- menuItem.setAction( new StyledEditorKit.UnderlineAction()); //添加加下划线侦听器
- menuItem.setText("下划线(U)");
- break;
- }
- }
- /*设置查看*/
- else if (menulabel.equals("查看")) {
- if(num==1)viewMenu.add(menuItem); //字数统计
- }
- /*设置帮助*/
- else if (menulabel.equals("帮助")) {
- helpMenu.add(menuItem);
- if (num==0)
- helpMenu.addSeparator(); //帮助主题
- }
- }
- /***************************************************************
- * Note类的内部类的相关操作
- **************************************************************/
- /** 内部类fileAction,用来处理文件菜单事件 **/
- public class fileAction implements ActionListener {
- //重写actionPerformed方法
- public void actionPerformed(ActionEvent e) {
- String command = e.getActionCommand();
- if (command == "新建(N)"||e.getSource()==newButton) {
- if(change) {
- newflag=true;
- exitText();
- newflag=false;
- } else {
- frame.dispose();
- new Note();
- }
- } else if (command == "打开(O)..."||e.getSource()==openButton)
- {
- if(change) {
- openflag=true;
- exitText();
- openflag=false;
- } else
- openFile();
- }
- else if (command == "保存(S)"||e.getSource()==saveButton)
- saveFile();
- else if (command == "另存为(A)...")
- saveAsFile();
- else if (command == "退出(X)"){
- if(change) {
- exitflag=true;
- exitText();
- exitflag=false;
- } else frame.dispose();
- }
- }
- }
- /** 内部类editAction,用来处理编辑菜单事件 **/
- public class editAction implements ActionListener {
- // 重写actionPerformed方法
- public void actionPerformed(ActionEvent e) {
- String command = e.getActionCommand();
- if (command == "撤销(U)"||e.getSource()==undoButton) {
- if(undomang.canUndo())
- undomang.undo();
- redoItem.setEnabled(true);
- }else if(command=="恢复(R)"||e.getSource()==redoButton){
- if (undomang.canRedo())
- undomang.redo();
- else
- redoItem.setEnabled(false);
- }else if (command == "剪切(T)"||e.getSource()==cutButton)
- display.cut(); //剪切所选的文本到剪贴板里
- else if (command == "复制(C)"||e.getSource()==copyButton)
- display.copy(); //复制所选的文本放到剪贴板里
- else if (command == "粘贴(P)"||e.getSource()==pasteButton)
- display.paste(); //取得剪贴板里的内容粘贴到display里
- else if (command == "删除(L)"||e.getSource()==deleteButton) //启动删除
- display.replaceSelection("");
- else if (command == "查找(F)") { //启动查找
- new FindDialog(frame,"查找",false);
- }else if (command == "查找下一个(N)") { //启动查找下一个
- if(selectflag)
- new FindDialog(frame,"查找",false);
- else if (FindDialog.matcher.find(Note.display.getCaretPosition())) //使用find()方法查找第一个匹配的对象
- display.select(FindDialog.matcher.start(), FindDialog.matcher.start()+FindDialog.findText.getText().length());
- else
- JOptionPane.showMessageDialog(null,"找不到 /""+FindDialog.findText.getText()+"/"","文本编辑器",JOptionPane.WARNING_MESSAGE);
- } else if (command == "替换(E)") //开启替换对话框
- new ChangeDialog(frame,"替换",false);
- else if (command == "全选(A)") //全选
- display.selectAll();
- else if (command == "时间/日期(D)") {
- Calendar now = Calendar.getInstance();//取得系统的时间
- int year = now.get(Calendar.YEAR);
- int month = now.get(Calendar.MONTH) + 1;
- int date = now.get(Calendar.DATE);
- int hour = now.get(Calendar.HOUR_OF_DAY);
- int minute = now.get(Calendar.MINUTE);
- display.replaceSelection(hour + ":" + minute + " " + year + "-" + month + "-"+ date);
- }
- }
- }
- /** 内部类formatAction,用来处理格式菜单事件 **/
- public class formatAction implements ActionListener {
- //重写actionPerformed方法
- public void actionPerformed(ActionEvent e) {
- String command = e.getActionCommand();
- if (command == "插入图片(W)") {
- JFileChooser open = new JFileChooser(); // 查找文件
- open.addChoosableFileFilter(new JpgFileFilter());
- open.addChoosableFileFilter(new GifFileFilter());
- int state=open.showOpenDialog(frame);
- File file=open.getSelectedFile();
- if(file!=null&&state==JFileChooser.APPROVE_OPTION)
- insertIcon(file); // 插入图片
- }else if (command == "字体(F)") {
- xp= frame.getX();
- yp = frame.getY();
- FontDialog font=new FontDialog(frame,"字体",true);
- if(!font.sure)
- return;
- if(font_type==0){bold=false;italic=false;}
- else if(font_type==1){ bold=true;italic=false;}
- else if(font_type==2){ bold=false;italic=true;}
- else {bold=true;italic=true;}
- if(display.getSelectedText()==null)
- display.setFont(font.myfont);
- else{
- createStyle("Style",styledDoc,font_size,bold,italic,display.getSelectedTextColor(),font_name);
- insertDoc(styledDoc,display.getSelectedText(),"Style");
- }
- }else if (command == "背景颜色(B)") {
- color = JColorChooser.showDialog(container, "请选择背景颜色", color);
- if (color == null)
- color = display.getBackground();
- display.setBackground(color);
- }else if (command == "字体颜色(F)") {
- color = JColorChooser.showDialog(container, "请选择字体颜色", color);
- if (color == null)
- color =Color.BLACK;
- if(display.getSelectedText()==null)
- display.setForeground(color);
- else{
- createStyle("style",styledDoc,font_size,bold,italic,color,font_name);
- insertDoc(styledDoc,display.getSelectedText(),"style");
- }
- } else if(command=="MOTIF风格"){
- try {
- UIManager.setLookAndFeel(looks[1].getClassName());
- SwingUtilities.updateComponentTreeUI( frame );
- }catch ( Exception ea ) {}
- }else if(command=="默认风格"){
- try {
- UIManager.setLookAndFeel(looks[0].getClassName());
- SwingUtilities.updateComponentTreeUI(frame);
- }catch ( Exception eb ) {}
- }else if(command=="系统风格"){
- try {
- UIManager.setLookAndFeel(looks[3].getClassName());
- SwingUtilities.updateComponentTreeUI( frame );
- }catch ( Exception ea ) {}
- }
- }
- }
- /** 内部类viewAction,用来处理查看菜单事件 **/
- public class viewAction implements ActionListener {
- public void actionPerformed(ActionEvent e) {
- String command = e.getActionCommand();
- int length=0,blank=0,row=0,columns=1;
- String space="",line="",text="",other=" ";
- if(command=="字数统计(W)"){
- if (display.getSelectedText() == null)
- text=display.getText();
- else text=display.getSelectedText();
- length=text.length();
- for(int i=0;i<length;i++)
- if(text.charAt(i)==' ') blank++; //比较字符是不是空格
- else if(String.valueOf(text.charAt(i)).equals("/n"))
- row++;
- for(int i=0;i<70;i++){
- space+=" ";
- if(i<50)
- line+="-";
- }
- String message="/n字数"+other+space+(length-2*row-blank)+
- "/n字符数"+space+(length-2*row)+
- "/n空格数"+space+blank+
- "/n行数"+other+space+(row+1);
- Object[] options = {"关闭"};
- JOptionPane.showOptionDialog(frame,"统计信息:"+line+message, "字数统计",
- JOptionPane.DEFAULT_OPTION,JOptionPane.CLOSED_OPTION,null, options,options[0]);
- }
- }
- }
- /** 内部类helpAction,用来处理帮助菜单事件 **/
- public class helpAction implements ActionListener {
- public void actionPerformed(ActionEvent e) {
- String command=e.getActionCommand();
- if(command=="关于(A)")
- new AboutDialog(frame,"关干 文本编辑器",true);
- else if(command=="帮助主题(H)")
- new HelpTheme();
- }
- }
- /** 内部类mouseAction,用来处理鼠标事件 **/
- public class mouseAction extends MouseAdapter {
- public void mouseReleased(MouseEvent e) {
- if (e.isPopupTrigger())
- popupmenu.show(display, e.getX(), e.getY());//显示右键菜单
- }
- }
- /**内部类documentlis用来处理文档内容变化事件***/
- public class documentLis implements DocumentListener{
- public void changedUpdate(DocumentEvent arg0) {
- change=true;
- }
- public void insertUpdate(DocumentEvent arg0) {
- change=true;
- undoItem.setEnabled(true);
- findItem.setEnabled(true);
- findnextItem.setEnabled(true);
- }
- public void removeUpdate(DocumentEvent arg0) {
- change=true;
- }
- }
- /***********************************************
- * Note类里面的方法操作
- * ****************************************************/
- public void insertIcon(File file) { //插入图片的方法
- display.setCaretPosition(styledDoc.getLength()); // 设置插入位置
- display.insertIcon(new ImageIcon(file.getPath())); // 插入图片
- }
- public void insertDoc(StyledDocument styledDoc, String content,String currentStyle) {
- try {
- int len=display.getSelectedText().length();
- styledDoc.insertString(display.getCaretPosition(),content,styledDoc.getStyle(currentStyle));
- display.replaceSelection("");
- display.select(display.getCaretPosition()-len,display.getCaretPosition());
- } catch (Exception e) {}
- }
- public void createStyle(String style,StyledDocument doc,int size,boolean bold,boolean italic,Color color,String fontName) {
- Style sys = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
- try {
- doc.removeStyle(style);
- } catch(Exception e) {} //先删除这种Style,假使他存在
- Style s = doc.addStyle(style,sys); // 加入
- StyleConstants.setFontSize(s,size); // 大小
- StyleConstants.setBold(s,bold); // 粗体
- StyleConstants.setItalic(s,italic); // 斜体
- StyleConstants.setForeground(s,color); // 颜色
- StyleConstants.setFontFamily(s,fontName); // 字体
- }
- public void openFile(){ //打开文件
- JFileChooser open= new JFileChooser();
- open.addChoosableFileFilter(new JavaFileFilter());
- open.addChoosableFileFilter(new TxtFileFilter());
- // 设置默认的文件管理器。如果不设置,则最后添加的文件过滤器为默认过滤器.这里设置为txtFilter
- int state = open.showOpenDialog(frame);// 弹出文件选择窗口,点击确定返回一个整数
- File file = open.getSelectedFile();
- /*JFileChooser.APPROVE_OPTION常量存储着确定按钮对应的整数*/
- if (file != null && state == JFileChooser.APPROVE_OPTION){
- currentFile=file;
- display.setText("");
- frame.setTitle(file.getName()+" - 文字编辑");
- try {
- FileReader readFile=new FileReader(file.getAbsolutePath());//文件的读取
- int len=(int)file.length();
- char []buffer=new char[len];
- readFile.read(buffer,0,len);
- display.setText(new String(buffer));
- readFile.close();
- } catch (Exception e) { }
- change=false; //打开一个文件之后把文档内容变化标记变量设为false
- }
- }
- public void saveAsFile() { //另存为
- JFileChooser save=new JFileChooser();
- save.addChoosableFileFilter(new JavaFileFilter());
- save.addChoosableFileFilter(new TxtFileFilter());
- save.setDialogTitle("另存为");
- int state = save.showSaveDialog(frame);
- File file=save.getSelectedFile();
- if (file != null && state == JFileChooser.APPROVE_OPTION){
- /**正则表达式用来查看输入的文件名是否有后缀名 */
- Pattern pattern=Pattern.compile("//.//w*",Pattern.CASE_INSENSITIVE);
- Matcher matcher = pattern.matcher(file.getAbsolutePath());
- if(!matcher.find()){
- file=new File(file.getAbsolutePath().concat(".txt"));
- }
- currentFile=file;
- try {
- FileWriter target = new FileWriter(currentFile.getAbsolutePath());
- target.write(display.getText());
- frame.setTitle(currentFile.getName()+ " - 文字编辑");
- target.close();
- } catch (Exception e) { }
- change=false;
- }
- }
- public void saveFile(){ //保存
- if (currentFile != null){
- try{
- FileWriter file = new FileWriter(currentFile);
- file.write(display.getText());
- file.close();
- }catch(Exception e){ }
- change=false;
- }else saveAsFile();
- }
- public void exitText(){ //退出文本的相关操作
- String path="无标题";
- if(currentFile!=null)
- path=currentFile.getAbsolutePath();
- int num =JOptionPane.showConfirmDialog(container,"文件 "+ path +" 的文字已经改变。想要保存文件吗?", "文字编辑",
- JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.WARNING_MESSAGE);
- if(num==0) saveFile();
- else if(num==1&&newflag){frame.dispose();new Note();}
- else if(num==1&&exitflag){frame.dispose();}
- else if(num==1&&windowflag){System.exit(0);}
- else if(num==1&&openflag) openFile();
- }
- }
- /*********用干文件过滤的外部类***********/
- class GifFileFilter extends FileFilter{
- public String getDescription(){
- return "gif源文件(*.gif)";
- }
- public boolean accept(File file) {
- return file.getName().toLowerCase().endsWith(".gif");
- }
- }
- class JpgFileFilter extends FileFilter{
- public String getDescription(){
- return "jpg源文件(*.jpg)";
- }
- public boolean accept(File file) {
- return file.getName().toLowerCase().endsWith(".jpg");
- }
- }
- class JavaFileFilter extends FileFilter {
- public String getDescription() {
- return "java源文件(*.java)";
- }
- public boolean accept(File file) {
- return file.getName().toLowerCase().endsWith(".java");
- }
- }
- class TxtFileFilter extends FileFilter {
- public String getDescription() {
- return "文本文档(*.txt)";
- }
- public boolean accept(File file) {
- return file.getName().toLowerCase().endsWith(".txt");
- }
- }
- package javadesign;
- import java.awt.*;
- import java.awt.event.*;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import javax.swing.*;
- import javax.swing.border.*;
- /*************************************************
- * 类FindDialog用来进行查找
- *
- ***********************************************/
- public class FindDialog extends JDialog implements ActionListener{
- private JLabel findLabel=new JLabel("输入要查找的内容:");
- public static JTextField findText = new JTextField(15);
- private JButton buttonNext = new JButton("查找下一个");
- private ButtonGroup group=new ButtonGroup();
- private JButton buttonCancel = new JButton("取消");
- private JRadioButton findUp=new JRadioButton("向上",false);
- private JRadioButton findDown=new JRadioButton("向下",true);
- private JCheckBox letter=new JCheckBox("区分大小写",false);
- private Container container=this.getContentPane();
- private JPanel findPanel=new JPanel();
- private JPanel buttonPanel=new JPanel();
- private JPanel aspectPanel=new JPanel();
- Pattern pattern ;
- // 用Pattern类的matcher()方法生成一个Matcher对象
- public static Matcher matcher ;
- boolean begin=true ,letterflag=true,updownflag=false;
- int judge=Pattern.CASE_INSENSITIVE; //区分大小写的值为1,不区别为2,此时judge=2
- int startp,len,count=1;
- public FindDialog(Frame frame,String title,boolean modal){
- super(frame,title,modal);
- this.setSize(380, 150);
- this.setResizable(false);
- setLocation(Note.xp+ 50, Note.yp+ 150);
- buttonNext.setEnabled(false);
- findText.addKeyListener(new KeyAdapter() {
- public void keyReleased(KeyEvent e) {
- if(findText.getText().length()!=0)
- buttonNext.setEnabled(true);
- else
- buttonNext.setEnabled(false);
- }
- });
- group.add(findUp);
- group.add(findDown);
- container.setLayout(null);
- findPanel.setLayout(new GridLayout(1,2));
- buttonPanel.setLayout(new GridLayout(2,1,0,5));
- aspectPanel.setLayout(new GridLayout(1,2));
- findPanel.add(findLabel);
- findPanel.add(findText);
- buttonPanel.add(buttonNext);
- buttonPanel.add(buttonCancel);
- aspectPanel.add(findUp);
- aspectPanel.add(findDown);
- findPanel.setBounds(10,10,250,25);
- buttonPanel.setBounds(265,10,100,50);
- letter.setBounds(10,70,100,20);
- aspectPanel.setBounds(120,50,140,50);
- //建立类型为凸起的边框
- Border border=BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
- //建立边框式为border,标题为"方向"的TitledBorder
- aspectPanel.setBorder(BorderFactory.createTitledBorder(border,"方向"));
- container.add(findPanel);
- container.add(buttonPanel);
- container.add(letter);
- container.add(aspectPanel);
- buttonNext.addActionListener(this);
- findUp.addActionListener(this);
- findDown.addActionListener(this);
- buttonCancel.addActionListener(this);
- findText.addActionListener(this);
- letter.addActionListener(this);
- this.setVisible(true);
- }
- public void actionPerformed(ActionEvent e) {
- if(e.getSource()==buttonNext||e.getSource()==findText) {
- Note.selectflag=false;
- switch(count) {
- case 0:String leave=Note.display.getText().substring(0,Note.display.getCaretPosition());
- if(leave.matches(findText.getText())||Note.display.getCaretPosition()-len<=0) {
- JOptionPane.showMessageDialog(null,"找不到 /""+findText.getText()+"/"","文本编辑器",JOptionPane.WARNING_MESSAGE);
- //Note.display.select(startp, startp+len);
- break;
- }
- Note.display.select(0, Note.display.getCaretPosition()-len);
- startp=Note.display.getSelectedText().lastIndexOf(findText.getText());
- len=findText.getText().length();
- Note.display.select(startp, startp+len);
- break;
- case 1:if(begin){
- try{
- Note.selectflag=false;
- //编译模式,参数findText.getText()表示输入的正则表达式,judge表示模式类型
- pattern=Pattern.compile(findText.getText(),judge);
- //获取匹配器,Note.display.getText()为待处理的字符串
- matcher = pattern.matcher(Note.display.getText()); //用Pattern类的matcher()方法生成一个Matcher对象
- begin=false;
- }catch(Exception ev){}
- }
- if (matcher.find(Note.display.getCaretPosition())) //从光标处开始匹配模式
- Note.display.select(matcher.start(), matcher.end());
- else
- JOptionPane.showMessageDialog(null,"找不到 /""+findText.getText()+"/"","文本编辑器",JOptionPane.WARNING_MESSAGE);
- break;
- }
- } else if(e.getSource()==findUp)
- count=0;
- else if(e.getSource()==findDown){
- begin=true;
- count=1;
- } else if(e.getSource()==buttonCancel)
- this.setVisible(false);
- else if(e.getSource()==letter) {
- if(letterflag){judge=1;letterflag=false;} else {judge=2;letterflag=true;}
- begin=true;
- }
- }
- }
- package javadesign;
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- public class AboutDialog extends JDialog {
- private JLabel iconLabel; //用来放图片
- private JTextArea word; //用来放说明
- private JPanel panel;
- private Container container;
- private Note note=new Note();
- public AboutDialog(Frame frame,String title, boolean modal){
- super(frame,title,modal);
- this.setSize(415,400);
- this.setLocation(Note.xp+50,Note.yp+150);
- this.setResizable(false);
- container=this.getContentPane();
- iconLabel=new JLabel(new ImageIcon("top.gif"));
- word=new JTextArea();
- panel=new JPanel(new BorderLayout());
- panel.add(iconLabel,"North");
- panel.add(word,"Center");
- container.setLayout(new BorderLayout());//设置布局
- container.add(panel,"Center");
- /**相关信息*/
- String wordString=" Java编写的作品--/n" +
- "/t实现Windows记事本大部分功能/n"+
- "/t扩展了部分功能/n/n"+
- " 关干文本编辑器的制作者/n"+
- "/t学校:桂林电子科技大学/n"+
- "/t学院: 计算机与控制学院/n"+
- "/t专业: 软件工程/n"+
- "/t姓名: 陈剑龙/n"+
- "/t联系方式(QQ): 631818332";
- Color backColor=new Color(200,255,255); //自定义颜色
- word.setFont(new Font("宋体",Font.BOLD|Font.ITALIC,20)); //设置字体
- word.setBackground(backColor); //设置背景色
- word.setForeground(Color.blue); //设置前景色
- word.setText(wordString); //把wordstring放入到word组件里
- word.setEditable(false);
- this.setVisible(true);
- }
- }
- package javadesign;
- import java.awt.*;
- import java.io.*;
- import javax.swing.*;
- import javax.swing.event.*;
- import javax.swing.tree.*;
- import java.awt.event.*;
- public class HelpTheme extends JFrame implements ActionListener{
- Container container=this.getContentPane();
- File currentFile;
- JPanel indexpanel=new JPanel(new BorderLayout());
- JPanel searchpanel=new JPanel(new BorderLayout());
- JPanel listpanel=new JPanel(new BorderLayout());
- JPanel rightpanel=new JPanel(new BorderLayout());
- int leftX=275,leftY=225;
- int rightpanelX=275,rightpanelY=225;
- JToolBar toolbar=new JToolBar();
- JButton indexshowbutton=new JButton("显示(D)");
- JButton searchshowbutton=new JButton("显示(D)");
- JButton searchthemebutton=new JButton("列出主题(L)");
- JButton button=new JButton("隐藏");
- JButton backbutton=new JButton("后退");
- JButton forebutton=new JButton("前进");
- JTextArea rightpanelarea=new JTextArea();
- JTextField searchfield=new JTextField();
- JTextField indexfield=new JTextField();
- JTextField index=new JTextField("键入要查找的关键字(W):");
- JTextField search=new JTextField("键入要查找的关键字(W):");
- JTextField searchnext=new JTextField("选择要显示的主题(T):");
- JList indexlist=new JList();
- JList searchlist=new JList();
- JScrollPane indexscroll=new JScrollPane(indexlist);
- JScrollPane searchscroll=new JScrollPane(searchlist);
- JSplitPane split;
- boolean flag=true;
- Box indexboxup=Box.createVerticalBox(); //创建列型盒
- Box indexboxdown=Box.createHorizontalBox();
- Box searchboxup=Box.createVerticalBox();
- Box searchboxcenter=Box.createHorizontalBox();
- Box searchboxdown=Box.createHorizontalBox();
- JTabbedPane lefttab=new JTabbedPane(JTabbedPane.TOP);
- /*建立JTabbedPane对象,索引卡显示位置为上方*/
- ///
- DefaultMutableTreeNode node1,node2,node3;
- DefaultMutableTreeNode root=new DefaultMutableTreeNode("文本编辑器");
- JTree tree;
- public HelpTheme() {
- this.setTitle("帮助主题");
- this.setLocation(400,200);
- indexboxup.add(Box.createVerticalStrut(8));
- index.setEditable(false);
- index.setFont(new Font("宋体",Font.BOLD,13));
- index.setBackground(new Color(238,238,238));
- indexboxup.add(index);
- indexboxup.add(indexfield);
- indexboxup.add(Box.createVerticalStrut(8));
- indexpanel.add(indexboxup,"North");
- indexpanel.add(indexscroll,"Center");
- indexboxdown.add(Box.createHorizontalStrut(leftX-113));
- indexboxdown.add(indexshowbutton);
- indexpanel.add(indexboxdown,"South");
- searchboxup.add(Box.createVerticalStrut(8));
- search.setEditable(false);
- search.setFont(new Font("宋体",Font.BOLD,13));
- search.setBackground(new Color(238,238,238));
- searchboxup.add(search);
- searchboxup.add(searchfield);
- searchboxup.add(Box.createVerticalStrut(8));
- searchboxcenter.add(Box.createHorizontalStrut(leftX-140));
- searchboxcenter.add(searchthemebutton);
- searchboxup.add(searchboxcenter);
- searchboxup.add(Box.createVerticalStrut(8));
- searchnext.setEditable(false);
- searchnext.setFont(new Font("宋体",Font.BOLD,13));
- searchnext.setBackground(new Color(238,238,238));
- searchboxup.add(searchnext);
- searchboxup.add(Box.createVerticalStrut(8));
- searchpanel.add(searchboxup,"North");
- searchpanel.add(searchscroll,"Center");
- searchboxdown.add(Box.createHorizontalStrut(leftX-113));
- searchboxdown.add(searchshowbutton);
- searchpanel.add(searchboxdown,"South");
- lefttab.add("目录(C)",listpanel);
- lefttab.add("索引(N)",indexpanel);
- lefttab.add("搜索(S)",searchpanel);
- addTree("/"文本编辑器/"概述");
- addTree("查找特定的字符或词");
- addTree("查找并替换特定的字或词");
- addTree("根据窗口大小换行");
- addTree("转到特定行");
- addTree("更改字形和大小");
- addTree("在文档中插入时间和日期");
- tree=new JTree(root); //建立JTree对象tree
- tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);//只能选取一个节点
- tree.addMouseListener(new mouseAction());
- listpanel.add(tree,"North");
- ///
- toolbar.add(button);
- toolbar.addSeparator();
- toolbar.addSeparator();
- rightpanel.add(rightpanelarea);
- String string="/"文本编辑器概述/""+
- " 在文件菜单里面实现了新建文本编辑器,打开文件,保存文件,另存为文件,退出文本编辑器.功能"+
- "在编辑菜单里面实现了撤销,恢复,剪切,复制,粘贴,删除,查找,查找下一个,替换,"+
- "全选,时间/日期.功能"+
- "在格式菜单上实现了插入图片,改变字体,改变字体颜色,背景颜色,视图风格,增加下划线功能"+
- "在查看菜单上实现了状态栏,字数统计功能"+
- "在帮助菜单中现了帮助主题,关干的功能.";
- rightpanelarea.setFont(new Font("楷体",Font.BOLD,25));
- rightpanelarea.setText(string);
- toolbar.setEnabled(false);
- rightpanelarea.setLineWrap(true);
- //rightpanelarea.setEditable(false);
- split=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,false,lefttab,rightpanel);
- /*设置split的分隔线位置,以像素为计算单位*/
- split.setDividerLocation(leftX-30);
- /*设置JSplitPane是否可以展开或收起(如同文件总管一般),设为true表示打开此功能。
- */
- //split.setOneTouchExpandable(true);
- split.setDividerSize(10); //设置分隔线宽度的大小,以像素为计算单位。
- container.add(split);
- container.add(toolbar,"North");
- this.setSize(leftX+rightpanelX,leftY+rightpanelY);
- this.setVisible(true);
- button.addActionListener(this);
- }
- public void addTree(String string) {
- DefaultMutableTreeNode node=new DefaultMutableTreeNode(string);
- root.add(node);
- }
- /
- class mouseAction extends MouseAdapter {
- public void mousePressed(MouseEvent e) {
- int selRow=tree.getRowForLocation(e.getX(),e.getY());
- System.out.println("选择了第几行"+selRow);
- switch(selRow) {
- case 1:break;
- case 2:break;
- case 3:break;
- case 4:break;
- case 5:break;
- case 6:break;
- case 7:break;
- case 8:break;
- case 9:break;
- case 12:break;
- }
- }
- }
- public void actionPerformed(ActionEvent e) {
- if(e.getSource()==button) {
- if(flag){
- split.setDividerSize(0);
- lefttab.setVisible(false);
- button.setText("显示");
- this.setSize(rightpanelX+30,leftY+rightpanelY);
- this.setLocation(this.getX()+leftX-30,this.getY());
- flag=false;
- } else {
- split.setDividerSize(10);
- lefttab.setVisible(true);
- button.setText("隐藏");
- split.setDividerLocation(leftX-30);
- this.setSize(leftX+rightpanelX,leftY+rightpanelY);
- this.setLocation(this.getX()-leftX+30,this.getY());
- flag=true;
- }
- }
- }
- }
- package javadesign;
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- import javax.swing.border.*;
- /****************************************************************
- *
- * 类FontDialog用来设置字体
- *
- ********************************************************/
- public class FontDialog extends JDialog implements ActionListener {
- private String font[];
- private JLabel fontLabel, fontTypeLabel, fontSizeLabel, fontShowLabel;
- private JList fontList, fontTypeList, fontSizeList;
- private JTextField fontField, fontTypeField, fontSizeField,fontShowField;
- private JScrollPane fontScroll, fontTypeScroll, fontSizeScroll;
- public static JButton sureButton, cancelButton;
- private JPanel panel = new JPanel();
- public static Font myfont;
- private Container container = getContentPane();
- public FontDialog(Frame frame,String title, boolean modal){
- super(frame,title,modal);
- container.setLayout(null);
- setLocation(Note.xp + 50, Note.yp + 150);
- setResizable(false);
- setSize(420, 300);
- fontLabel = new JLabel("字体(F):");
- fontField = new JTextField(Note.font_name);
- GraphicsEnvironment g = GraphicsEnvironment.getLocalGraphicsEnvironment();
- font = g.getAvailableFontFamilyNames();//获得系统支持的所有字体列表
- fontList = new JList(font);
- fontList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);// 设为单选模式
- fontScroll = new JScrollPane(fontList);
- ///
- fontTypeLabel = new JLabel("字形(Y):");
- String[] data = { "常规", "斜体", "粗体", "粗斜体" };
- fontTypeList = new JList(data);
- if (Note.font_type == 0)
- fontTypeField = new JTextField("常规");
- else if (Note.font_type == 1)
- fontTypeField = new JTextField("粗体");
- else if (Note.font_type == 2)
- fontTypeField = new JTextField("斜体");
- else fontTypeField = new JTextField("粗斜体");
- fontTypeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);// 设为单选模式
- fontTypeScroll = new JScrollPane(fontTypeList);
- ///
- fontSizeLabel = new JLabel("大小(S):");
- String size[] = new String[100];
- for (int i = 10; i <= 100; i++) {
- size[i - 10] = String.valueOf(i);
- }
- fontSizeList = new JList(size);
- fontSizeField = new JTextField(""+Note.font_size);
- fontSizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);// 设为单选模式
- fontSizeScroll = new JScrollPane(fontSizeList);
- /
- sureButton = new JButton("确定");
- cancelButton = new JButton("取消");
- fontShowLabel = new JLabel("示例");
- fontShowField = new JTextField("字体AaBbYy");
- Border inside = BorderFactory.createBevelBorder(BevelBorder.LOWERED);
- fontShowField.setBorder(BorderFactory.createTitledBorder(inside));
- fontShowField.setEditable(false);
- fontShowField.setHorizontalAlignment(fontShowField.CENTER);
- fontShowField.setFont(myfont);
- fontLabel.setBounds(10, 5, 162, 20);
- fontField.setBounds(10, 25, 162, 20);
- fontScroll.setBounds(10, 45, 162, 140);
- fontTypeLabel.setBounds(177, 5, 100, 20);
- fontTypeField.setBounds(177, 25, 100, 20);
- fontTypeScroll.setBounds(177, 45, 100, 140);
- fontSizeLabel.setBounds(282, 5, 50, 20);
- fontSizeField.setBounds(282, 25, 50, 20);
- fontSizeScroll.setBounds(282, 45, 50, 140);
- sureButton.setBounds(337, 25, 60, 20);
- cancelButton.setBounds(337, 50, 60, 20);
- fontShowLabel.setBounds(177, 195, 100, 20);
- fontShowField.setBounds(177, 215, 200, 45);
- /
- container.add(fontLabel);
- container.add(fontField);
- container.add(fontScroll);
- container.add(fontTypeLabel);
- container.add(fontTypeField);
- container.add(fontTypeScroll);
- container.add(fontSizeLabel);
- container.add(fontSizeField);
- container.add(fontSizeScroll);
- container.add(sureButton);
- container.add(cancelButton);
- container.add(fontShowLabel);
- container.add(fontShowField);
- MouseListener mouseListener = new MouseAdapter() {
- public void mouseClicked(MouseEvent e) {
- mouseClick(e);
- }
- };
- fontList.addMouseListener(mouseListener);
- fontTypeList.addMouseListener(mouseListener);
- fontSizeList.addMouseListener(mouseListener);
- sureButton.addActionListener(this);
- cancelButton.addActionListener(this);
- this.setVisible(true);
- }
- public void mouseClick(MouseEvent e) {
- if (e.getSource() == fontList) {
- Note.font_name = fontList.getSelectedValue().toString();
- fontField.setText(Note.font_name);
- } else if (e.getSource() == fontTypeList)
- fontTypeField.setText(fontTypeList.getSelectedValue() .toString());
- else if (e.getSource() == fontSizeList) {
- fontSizeField.setText(fontSizeList.getSelectedValue().toString());
- Note.font_size= Integer.parseInt(fontSizeField.getText());
- }
- show_Font();
- }
- public void actionPerformed(ActionEvent e) {
- if (e.getSource() == sureButton)
- // Note.display.setFont(myfont);
- setVisible(false);
- else if (e.getSource() == cancelButton)
- setVisible(false);
- }
- public void show_Font() {
- if (fontTypeField.getText().equals("常规"))
- Note.font_type = 0;
- else if (fontTypeField.getText().equals("斜体"))
- Note.font_type = 2;
- else if (fontTypeField.getText().equals("粗体"))
- Note.font_type = 1;
- else if (fontTypeField.getText().equals("粗斜体"))
- Note.font_type = 3;
- myfont = new Font(Note.font_name, Note.font_type, Note.font_size);
- fontShowField.setFont(myfont);
- }
- }
- package javadesign;
- import java.awt.*;
- import javax.swing.*;
- import java.awt.event.*;
- import java.util.regex.*;
- /*******************************************
- * 利用ChangeDialog来替换
- *******************************/
- public class ChangeDialog extends JDialog implements ActionListener{
- private JLabel findLabel,changeLabel;
- private JTextField findField,changeField;
- private JCheckBox letter=new JCheckBox("区分大小写",false);
- private JButton findButton,changeButton,changeAllButton,cancelButton;
- private JPanel buttonPanel,textPanel;
- private Container container=this.getContentPane(); //获得内容面板
- Pattern pattern;
- // 用Pattern类的matcher()方法生成一个Matcher对象
- Matcher matcher ;
- boolean start=true,letterflag=true;
- int judge=Pattern.CASE_INSENSITIVE; //区分大小写的值为1,不区别为2,此时judge=2
- public ChangeDialog(Frame frame,String title,boolean modal){
- super(frame,title,modal); //调用父类的构造方法
- this.setSize(390,180); //设置大小
- setLocation(Note.xp+ 50, Note.yp+ 150);//设置显示的位置
- this.setResizable(false); //设置为不可最大化
- findLabel=new JLabel("输入原始字符:");
- changeLabel=new JLabel("输入替换字符:");
- findField=new JTextField(10);
- changeField=new JTextField(10);
- findButton=new JButton("查找下一个");
- changeButton=new JButton("替换");
- changeAllButton=new JButton("全部替换");
- cancelButton=new JButton("取消");
- buttonPanel=new JPanel();
- textPanel=new JPanel();
- buttonPanel.setLayout(new GridLayout(4,1,5,5));
- textPanel.setLayout(new GridLayout(2,2,5,5));
- textPanel.add(findLabel);
- textPanel.add(findField);
- textPanel.add(changeLabel);
- textPanel.add(changeField);
- buttonPanel.add(findButton);
- buttonPanel.add(changeButton);
- buttonPanel.add(changeAllButton);
- buttonPanel.add(cancelButton);
- container.setLayout(null);
- textPanel.setBounds(10,10,250,50);
- buttonPanel.setBounds(270,10,100,100);
- letter.setBounds(10,90,100, 20);
- container.add(textPanel);
- container.add(buttonPanel);
- container.add(letter);
- findButton.setEnabled(false);
- changeButton.setEnabled(false);
- changeAllButton.setEnabled(false);
- findField.addKeyListener(new KeyAdapter() {
- public void keyReleased(KeyEvent e) {
- if(findField.getText().length()!=0) {
- findButton.setEnabled(true);
- changeButton.setEnabled(true);
- changeAllButton.setEnabled(true);
- } else {
- findButton.setEnabled(false);
- changeButton.setEnabled(false);
- changeAllButton.setEnabled(false);
- }
- }
- });
- findButton.addActionListener(this);
- cancelButton.addActionListener(this);
- findField.addActionListener(this);
- changeField.addActionListener(this);
- changeButton.addActionListener(this);
- changeAllButton.addActionListener(this);
- cancelButton.addActionListener(this);
- letter.addActionListener(this);
- this.setVisible(true);
- }
- public void findAndChange(){
- if(start){
- try{
- pattern = Pattern.compile(findField.getText(),judge);
- matcher = pattern.matcher(Note.display.getText()); //用Pattern类的matcher()方法生成一个Matcher对象
- start=false;
- }catch(Exception ev){}
- }
- if (matcher.find(Note.display.getCaretPosition())) //使用find()方法查找第一个匹配的对象
- Note.display.select(matcher.start(), matcher.end());
- else
- JOptionPane.showMessageDialog(null,"找不到 /""+findField.getText()+"/"","文本编辑器",JOptionPane.WARNING_MESSAGE);
- }
- public void actionPerformed(ActionEvent e) {
- if(e.getSource()==findButton||e.getSource()==findField) {
- findAndChange();
- }else if(e.getSource()==changeAllButton){
- Pattern pat = Pattern.compile(findField.getText(),judge);
- Matcher mat = pat.matcher(Note.display.getText()); //用Pattern类的matcher()方法生成一个Matcher对象
- Note.display.setText(mat.replaceAll(changeField.getText()));
- }else if(e.getSource()==cancelButton)
- this.setVisible(false);
- else if(e.getSource()==changeButton){
- if(Note.display.getSelectedText()!=null){
- Note.display.replaceSelection(changeField.getText());
- start=true;
- }
- findAndChange();
- }else if(e.getSource()==letter) {
- if(letterflag){judge=1;letterflag=false;} else {judge=2;letterflag=true;}
- start=true;
- }
- }
- }