Java课设——文本编辑器

Java课设——文本编辑器一、需求编程实现一个文本编辑器,使其具有新建、打开、保存,编辑(查找、替换、大小写转换等)、统计(字数、行数、字符数等)、格式(字体设置、字体大小、字体颜色、背景颜色等)等功能。要求:基于JFrame窗体设计、使用菜单进行功能选择。二、工程目录三、项目代码TestGui类packageT_1029;importjava.awt.*;importjava.awt.event…

来自:https://blog.csdn.net/qq_39169598/article/details/84726959

原创不易,转载请加上作者

一、需求

编程实现一个文本编辑器,使其具有新建、打开、保存,编辑(查找、替换、大小写转换等)、统计(字数、行数、字符数等)、格式(字体设置、字体大小、字体颜色、背景颜色等)等功能。
要求:基于JFrame窗体设计、使用菜单进行功能选择。

二、工程目录

工程目录图

三、项目代码

TestGui类

package T_1029;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class TestGui extends JFrame { 
   
	
	private static final long serialVersionUID = 1L;
	private int flagFile=0;
	public TestGui() { 
   
		JFrame f = new JFrame("文本编辑器");
        f.setSize(800, 600);
        f.setLocation(200, 200);
 
        JMenuBar mb = new JMenuBar();
        //菜单栏
        JMenu mFile = new JMenu("文件 (F)");
        mFile.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        JMenu mEdit = new JMenu("编辑 (E)");
        mEdit.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        JMenu mForm = new JMenu("格式 (O)");
        mForm.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        JMenu mHelp = new JMenu("帮助 (H)");
        mHelp.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        
        // 菜单项
        JMenuItem NewFile =new JMenuItem("新建(N)");
        NewFile.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        mFile.add(NewFile);
        
        JMenuItem OpenFile=new JMenuItem("打开(O)");
        OpenFile.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        mFile.add(OpenFile);
        
        JMenuItem SaveFile=new JMenuItem("保存(S)");
        SaveFile.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        mFile.add(SaveFile);
        
        JMenuItem Search=new JMenuItem("查找(F)");
        Search.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        mEdit.add(Search);
        
        JMenuItem Replace=new JMenuItem("替换(G)");
        Replace.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        mEdit.add(Replace);
        
        JCheckBoxMenuItem FontChange=new JCheckBoxMenuItem("大小写转换(R)");
        FontChange.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        mEdit.add(FontChange);
        
        JMenuItem FontCount=new JMenuItem("统计(C)");
        FontCount.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        mEdit.add(FontCount);
        
        JMenuItem SetFont=new JMenuItem("字体设置");
        SetFont.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        mForm.add(SetFont);
        
        JMenuItem SetBackColor=new JMenuItem("设置背景颜色");
        SetBackColor.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        mForm.add(SetBackColor);
        
        JMenuItem About=new JMenuItem("关于文本编辑器");
        About.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        mHelp.add(About);
        
        JTextArea textArea = new JTextArea();
        //文本框自动换行
        textArea.setLineWrap(true);
      	//设置文本框字体
      	textArea.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 26));
        JPanel panel = new JPanel(new BorderLayout());//使用边界布局
        JLabel label=new JLabel(" ");
		label.setHorizontalAlignment(label.RIGHT);//右对齐
		panel.add(label,BorderLayout.SOUTH);//向窗口添加状态栏标签
		//实例化滚动面板
        JScrollPane scrollPane = new JScrollPane();
        //显示垂直滚动条
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        //文本框填入滚动面板
		scrollPane.setViewportView(textArea);
		//动态面板添加入窗口
		f.getContentPane().add(scrollPane);
		panel.add(scrollPane,BorderLayout.CENTER);
		f.setContentPane(panel);
		f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		
		//设置文本框内容改变的监听器
		textArea.getDocument().addDocumentListener(new DocumentListener() { 
   
			@Override
			public void removeUpdate(DocumentEvent e) { 
   
				flagFile=1;
			}
			@Override
			public void insertUpdate(DocumentEvent e) { 
   
				flagFile=1;
			}
			@Override
			public void changedUpdate(DocumentEvent e) { 
   
				// TODO 自动生成的方法存根
			}
		});
		
		//查找的监听器
		Search.addActionListener(new ActionListener() { 
   
			public void actionPerformed(ActionEvent e) { 
   
				new HSearchText(f,textArea);
			}
		});
		
		//替换的监听器
		Replace.addActionListener(new ActionListener() { 
   
			public void actionPerformed(ActionEvent e) { 
   
				new HReplaceText(f,textArea);
			}
		});
		
		
		//新建文件的监听器
		NewFile.addActionListener(new ActionListener() { 
   
			@Override
			public void actionPerformed(ActionEvent e) { 
   
				HFile hFile=new HFile();
				if(flagFile==1){ 
   
		            int result=JOptionPane.showConfirmDialog(f, 
		            		"是否保存更改?", 
		            		"记事本", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
		            if(result==JOptionPane.OK_OPTION){ 
   
		            	hFile.saveFile(f, textArea);//另存为 
		            	
		            }else if(result==JOptionPane.NO_OPTION){ 
   
		                textArea.setText("");
		            }
		            flagFile=0;
				}
				else { 
   
					textArea.setText("");
					f.setTitle("新建记事本");
				}
			}
		});
		
		//打开文件的监听器
		OpenFile.addActionListener(new ActionListener() { 
   
			@Override
			public void actionPerformed(ActionEvent e) { 
   
				HFile hFile=new HFile();
				if(flagFile==1) { 
   
					int result=JOptionPane.showConfirmDialog(f, 
		            		"是否保存更改?", 
		            		"记事本-保存", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
		            if(result==JOptionPane.OK_OPTION){ 
   
		            	hFile.saveFile(f, textArea);
		            	flagFile=0;
		            }
		            else if(result==JOptionPane.NO_OPTION)	
		            	flagFile=0;
				}
				else if(flagFile==0) { 
   
					hFile.openFile(f, textArea);
				}
					
			}
		});
		//保存文件的监听器
		SaveFile.addActionListener(new ActionListener() { 
   
            @Override
            public void actionPerformed(ActionEvent e) { 
   
            	new HFile().saveFile(f, textArea);
            	flagFile=0;
            }
        });
		//统计的监听器
		FontCount.addActionListener(new ActionListener() { 
   
			@Override
			public void actionPerformed(ActionEvent e) { 
   
				new HFontCount(textArea);	
			}
		});
		
		//字体设置的监听器
		SetFont.addActionListener(new ActionListener() { 
   
			@Override
			public void actionPerformed(ActionEvent e) { 
   
				new HSetFont(f,textArea);
			}
		});
		//大小写转换的监听器
		FontChange.addChangeListener(new ChangeListener() { 
   
            @Override
            public void stateChanged(ChangeEvent e) { 
   
            	if(FontChange.isSelected()) { 
   
            		String string=textArea.getText();
            		char[] chars = string.toCharArray();
                    for (int i = 0, length = chars.length; i < length; i++) { 
   
                        char c = chars[i];
                        //判断字母是不是大写,如果是大写变为小写
                        if (Character.isUpperCase(c)){ 
   
                            chars[i] = Character.toLowerCase(c);
                            continue;
                        }
                        //如果为小写,变为大写
                        chars[i] = Character.toUpperCase(c);
                    }
                    String str1 = new String(chars);
                	textArea.setText(str1);
            	}
            }
        });
		
        //设置背景颜色的监听器
        SetBackColor.addActionListener(new ActionListener() { 
   
			@Override
			public void actionPerformed(ActionEvent e) { 
   
				Color color = JColorChooser.showDialog(f, "选取颜色", null);
				// 如果用户取消或关闭窗口, 则返回的 color 为 null
				if (color == null) { 
   
					return;
				}
				textArea.setBackground(color);
			}
		});
        
        //关于文本编辑器的监听器
        About.addActionListener(new ActionListener() { 
   
			@Override
			public void actionPerformed(ActionEvent e) { 
   
				JFrame f = new JFrame("关于文本编辑器");
				//弹出无提示图片的消息窗口
                JOptionPane.showMessageDialog(
                        f,
                        "JAVA课设\nMake By d幻月b",
                        "文本编辑器",
                        JOptionPane.PLAIN_MESSAGE
                );
			}
		});
        
        //窗口关闭的监听器,提示保存
        f.addWindowListener(new WindowAdapter() { 
   
			@Override
			public void windowOpened(WindowEvent e) { 
   
				// TODO 自动生成的方法存根
			}
			@Override
			public void windowIconified(WindowEvent e) { 
   
				// TODO 自动生成的方法存根
			}
			@Override
			public void windowDeiconified(WindowEvent e) { 
   
				// TODO 自动生成的方法存根
			}
			@Override
			public void windowDeactivated(WindowEvent e) { 
   
				// TODO 自动生成的方法存根
			}
			@Override
			public void windowClosing(WindowEvent e) { 
   
				HFile hFile=new HFile();
				if(flagFile==1){ 
   
		            int result=JOptionPane.showConfirmDialog(f, 
		            		"是否将更改保存到新建记事本?", 
		            		"记事本", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
		            if(result==JOptionPane.OK_OPTION){ 
   
		            	hFile.saveFile(f, textArea);//另存为 
		            	flagFile=0;
		            }
				}
			}
			@Override
			public void windowClosed(WindowEvent e) { 
   
				
			}
			@Override
			public void windowActivated(WindowEvent e) { 
   
				// TODO 自动生成的方法存根
			}
		});
        
        textArea.addKeyListener(new KeyAdapter() { 
   
        //按下某键
        	public void keyPressed(KeyEvent e) { 
   
        		int row = 0;
        		int col = 0;
        		int pos = textArea.getCaretPosition(); //获得光标位置 
        		try { 
   
        			row = textArea.getLineOfOffset(pos) + 1; //返回行从0算起,要+1
        			col = pos-textArea.getLineStartOffset(row-1)+1; 
        		}catch(Exception exception) { 
   
            	
        		}
        		label.setText("第" + row+"行," +"第"+col+"列 " ); 
        }
        
        	// 释放某键
        	public void keyReleased(KeyEvent e) { 
   
        		int row = 0;
        		int col = 0;
        		int pos = textArea.getCaretPosition(); //获得光标位置 
        		try { 
   
        			row = textArea.getLineOfOffset(pos) + 1; //返回行从0算起,要+1
        			col = pos-textArea.getLineStartOffset(row-1)+1; 
        		}catch(Exception exception) { 
   
        			
        		}
        		label.setText("第" + row+"行," +"第"+col+"列 " ); 
        		}
        });
        
        //新建文件的快捷键
        NewFile.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N,
                java.awt.Event.CTRL_MASK));
        NewFile.setMnemonic('N');
        //打开文件的快捷键
        OpenFile.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O,
                java.awt.Event.CTRL_MASK));
        OpenFile.setMnemonic('O');
        //保存文件的快捷键
        SaveFile.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S,
                java.awt.Event.CTRL_MASK));
        SaveFile.setMnemonic('S');
        //统计字数的快捷键
        FontCount.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, 
        		java.awt.Event.ALT_MASK));
        FontCount.setMnemonic('C');
        //查找的快捷键
        Search.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F,
                java.awt.Event.CTRL_MASK));
        Search.setMnemonic('F');
        //替换的快捷键
        Replace.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G,
                java.awt.Event.CTRL_MASK));
        Replace.setMnemonic('G');
        //大小写转换的快捷键
        FontChange.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R,
                java.awt.Event.CTRL_MASK));
        FontChange.setMnemonic('R');
        
        //载入4个一级菜单
        mb.add(mFile);
        mb.add(mEdit);
        mb.add(mForm);
        mb.add(mHelp);
        
        f.setJMenuBar(mb);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
	
    public static void main(String[] args) { 
   
    	new TestGui();
    }
}


HFile类

package T_1029;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

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

public class HFile { 
   
	
	public void openFile(JFrame f,JTextArea textArea) { 
   
		// 创建一个默认的文件选取器
        JFileChooser fileChooser = new JFileChooser();
        // 设置默认显示的文件夹为当前文件夹
        fileChooser.setCurrentDirectory(new File("."));
        // 设置文件选择的模式(只选文件、只选文件夹、文件和文件均可选)
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        // 设置是否允许多选
        fileChooser.setMultiSelectionEnabled(false);
        // 设置默认使用的文件过滤器
        fileChooser.setFileFilter(new FileNameExtensionFilter("txt(*.txt)", "txt"));
        // 打开文件选择框
        int result = fileChooser.showOpenDialog(f);
        if(result==1)
        	return ;
        if (result == JFileChooser.APPROVE_OPTION) { 
   
        	try { 
     
        		textArea.setText("");
        		File file = fileChooser.getSelectedFile();
        		FileInputStream fis=new FileInputStream(file);
                try{ 
   
                    //读取数据,并将读取到的数据存储到数组中
                    byte[] data = new byte[1024]; //数据存储的数组
                    int i = fis.read(data);
                    //解析数据
                    String s = new String(data,0,i);
                    textArea.append(s);
                }catch(Exception e){ 
   
                    e.printStackTrace();
                }finally{ 
   
                    try{ 
   
                        fis.close();
                    }catch(Exception e){ 
   }
                }
                f.setTitle(file.getName()+" - 文本编辑器");
        	} catch (IOException e) { 
   
				e.printStackTrace();
			}
        }
	}

	public void saveFile(JFrame f,JTextArea textArea) { 
   
		// 创建一个默认的文件选取器
        JFileChooser fileChooser = new JFileChooser();
        // 设置默认显示的文件夹为当前文件夹
        fileChooser.setCurrentDirectory(new File("."));
        // 设置打开文件选择框后默认输入的文件名
        fileChooser.setSelectedFile(new File("新建记事本.txt"));
        // 打开文件选择框
        int select = fileChooser.showSaveDialog(f);
        if (select == JFileChooser.APPROVE_OPTION) { 
   
            // 保存文本内容
            File file = fileChooser.getSelectedFile();
            try { 
   
            	//覆盖文件式写入
            	OutputStream outToFileEnd = new FileOutputStream(file);
                String string = textArea.getText();
                byte[] bs = string.getBytes();
                outToFileEnd.write(bs);
                outToFileEnd.close();
                f.setTitle(file.getName()+" - 文本编辑器");
            } catch (Exception e1) { 
   
                e1.printStackTrace();
            }
        }
	}
}

HFontCount类

package T_1029;
import java.awt.Font;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class HFontCount { 
   
	public HFontCount(JTextArea textArea){ 
   
		String line=textArea.getText();
		JFrame f = new JFrame("统计");
		//弹出无提示图片的消息窗口
		JOptionPane.showMessageDialog(
                f,
                "字数:"+countChinese(line)+"\n字符数:"+line.length()+"\n行数:"+textArea.getLineCount(),
                "统计",
                JOptionPane.PLAIN_MESSAGE
        );
	}
	public static int countChinese(String str) { 
   
        int count = 0;
        //正则表达式匹配汉字|全角符号|数字|。|英文字母
        Pattern p = Pattern.compile("[\\u4e00-\\u9fa5]|[\\uFE30-\\uFFA0]|[0-9]|[\\u3001-\\u3002]|[a-zA-Z]");
        Matcher m = p.matcher(str);
        while(m.find()){ 
   
            count++;
        }
        return count;
    } 
}

HReplaceText类

package T_1029;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class HReplaceText { 
   
	public HReplaceText(JFrame f,JTextArea textArea) { 
   
		JDialog jdlg = new JDialog(f, "替换", true);
        jdlg.setSize(453, 200);
        jdlg.setLocationRelativeTo(null);
        jdlg.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        
        JPanel panel=new JPanel();
        panel.setLayout(null);
        JLabel label=new JLabel("查找内容:");
        JLabel label2=new JLabel("替换为:");
        JLabel count=new JLabel("找到0个");
        JTextArea ftext=new JTextArea();
        JTextArea rtext=new JTextArea();
        JButton findnext=new JButton("查找下一个");
        JButton replace=new JButton("替换");
        JButton allreplace=new JButton("全部替换");
        JButton no=new JButton("取消");
        JCheckBox matchcase=new JCheckBox("区分大小写");
        //创建两个单选按钮
        JRadioButton up = new JRadioButton("向上替换");
        JRadioButton down = new JRadioButton("向下替换");
        //创建按钮组,把两个单选按钮添加到该组
        ButtonGroup btnGroup = new ButtonGroup();
        btnGroup.add(up);
        btnGroup.add(down);
        // 设置第一个单选按钮选中
        up.setSelected(true);
        
        label.setBounds(20,20,93,22);
        label2.setBounds(20,45,93,22);
        count.setBounds(20, 55, 80, 85);
        ftext.setBounds(100,20,200,22);
        rtext.setBounds(100,48,200,22);
        findnext.setBounds(320, 18, 105, 32);
        replace.setBounds(320, 55, 105, 32);
        allreplace.setBounds(320, 92, 105, 32);
        no.setBounds(320, 128, 105, 32);
        matchcase.setBounds(15, 120, 100, 55);
        up.setBounds(130, 120, 80, 55);
        down.setBounds(230, 120, 80, 55);
        
        //初始化按键状态
        findnext.setEnabled(false);
        replace.setEnabled(false);
        allreplace.setEnabled(false);
        
        //查找文本框的监听器,改变按钮状态
        ftext.getDocument().addDocumentListener(new DocumentListener() { 
   
			@Override
			public void removeUpdate(DocumentEvent e) { 
   
				if(ftext.getText().equals("")) { 
   
		        	findnext.setEnabled(false);
		        	replace.setEnabled(false);
		            allreplace.setEnabled(false);
				}
				
			}
			@Override
			public void insertUpdate(DocumentEvent e) { 
   
				findnext.setEnabled(true);
				replace.setEnabled(true);
		        allreplace.setEnabled(true);
			}
			@Override
			public void changedUpdate(DocumentEvent e) { 
   
				// TODO 自动生成的方法存根
			}
		});
        //查找下一个的监听器
        findnext.addActionListener(new ActionListener() { 
   
			@Override
			public void actionPerformed(ActionEvent e) { 
   
				int c=0;
				int a = 0, b = 0;
				int FindStartPos = textArea.getCaretPosition();
                String strA,strB;
                // 选中区分大小写,大小写转换
                if (matchcase.isSelected()) { 
   
                    strA = textArea.getText();
                    strB = ftext.getText();
                } else { 
   
                    strA = textArea.getText().toLowerCase();
                    strB = ftext.getText().toLowerCase();
                }
                //向上查找,否则向下查找
                if (up.isSelected()) { 
   
                	a = strA.lastIndexOf(strB, FindStartPos - ftext.getText().length() - 1);
                } else if (down.isSelected()) { 
   
                	a = strA.indexOf(strB, FindStartPos - ftext.getText().length() + 1);
                }
                //查找到边界
                if (a > -1) { 
   
            		if (up.isSelected()) { 
   
            	  		textArea.setCaretPosition(a);
            	  		b = ftext.getText().length();
            	  		textArea.select(a, a + b);
            	  	} else if (down.isSelected()) { 
   
            	  		textArea.setCaretPosition(a);
            	  		b = ftext.getText().length();
            	  		textArea.select(a, a + b);
            		}
            	} else { 
   
            	  		JOptionPane.showMessageDialog(null, "找不到查找的内容", 
            	  				"查找", JOptionPane.INFORMATION_MESSAGE);
            	}
                //显示关键字的总数量
				Pattern p=Pattern.compile(ftext.getText());
				Matcher m=p.matcher(textArea.getText());
				while(m.find()) { 
   
					c++;
				}
				count.setText("找到"+c+"个");
			}
		});
        
        //替换的监听器
        replace.addActionListener(new ActionListener() { 
   
			@Override
			public void actionPerformed(ActionEvent e) { 
   
				if (rtext.getText().length() == 0 && textArea.getSelectedText() != null) { 
   
					textArea.replaceSelection("");
				}
				if (rtext.getText().length() > 0 && textArea.getSelectedText() != null) { 
   
					textArea.replaceSelection(rtext.getText());
				}
			}
		});
        //替换全部的监听器
        allreplace.addActionListener(new ActionListener() { 
   
			@Override
			public void actionPerformed(ActionEvent e) { 
   
				//显示关键字的总数量
				int c=0;
				Pattern p=Pattern.compile(ftext.getText());
				Matcher m=p.matcher(textArea.getText());
				while(m.find()) { 
   
					c++;
				}
				count.setText("替换"+c+"个");
				//替换全部关键字
				String str=textArea.getText();
				str=str.replace(ftext.getText(), rtext.getText());
				textArea.setText(str);
				
			}
		});
        
        //取消的监听器
        no.addActionListener(new ActionListener() { 
   
			public void actionPerformed(ActionEvent e) { 
   
				jdlg.setVisible(false);
			}
		});
        
        label.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        label2.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        count.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        ftext.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        rtext.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        findnext.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 13));
        replace.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 13));
        allreplace.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 13));
        no.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 13));
        
        panel.add(label);
        panel.add(label2);
        panel.add(count);
        panel.add(ftext);
        panel.add(rtext);
        panel.add(findnext);
        panel.add(no);
        panel.add(replace);
        panel.add(allreplace);
        panel.add(matchcase);
        panel.add(up);
        panel.add(down);
        
        jdlg.setResizable(false);
        jdlg.setContentPane(panel);
        jdlg.setVisible(true);
	}
}

HSearchText类

package T_1029;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class HSearchText { 
   
	public HSearchText(JFrame f,JTextArea textArea) { 
   
		JDialog jdlg = new JDialog(f, "查找", true);
        jdlg.setSize(453, 150);
        jdlg.setLocationRelativeTo(null);
        jdlg.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        
        JPanel panel=new JPanel();
        panel.setLayout(null);
        JLabel label=new JLabel("查找内容:");
        JLabel count=new JLabel("找到0个");
        JTextArea ftext=new JTextArea();
        JButton findnext=new JButton("查找下一个");
        JButton no=new JButton("取消");
        JCheckBox matchcase=new JCheckBox("区分大小写");
        //创建两个单选按钮
        JRadioButton up = new JRadioButton("向上查找");
        JRadioButton down = new JRadioButton("向下查找");
        //创建按钮组,把两个单选按钮添加到该组
        ButtonGroup btnGroup = new ButtonGroup();
        btnGroup.add(up);
        btnGroup.add(down);
        // 设置第一个单选按钮选中
        up.setSelected(true);
        
        label.setBounds(20,20,93,22);
        count.setBounds(20, 55, 80, 35);
        ftext.setBounds(100,20,200,22);
        findnext.setBounds(320, 18, 105, 32);
        no.setBounds(320, 53, 105, 32);
        matchcase.setBounds(15, 90, 100, 25);
        up.setBounds(130, 90, 80, 25);
        down.setBounds(230, 90, 80, 25);
        
        //初始化查找按键
        findnext.setEnabled(false);
        //设置文本框和按钮的状态
        ftext.getDocument().addDocumentListener(new DocumentListener() { 
   
			@Override
			public void removeUpdate(DocumentEvent e) { 
   
				if(ftext.getText().equals(""))
		        	findnext.setEnabled(false);
			}
			@Override
			public void insertUpdate(DocumentEvent e) { 
   
				findnext.setEnabled(true);
			}
			@Override
			public void changedUpdate(DocumentEvent e) { 
   
				// TODO 自动生成的方法存根
			}
		});
		//查找下一个的监听器
        findnext.addActionListener(new ActionListener() { 
   
			public void actionPerformed(ActionEvent e) { 
   
				int c=0;
				int a = 0, b = 0;
				int FindStartPos = textArea.getCaretPosition();
                String strA,strB;
                // 选中区分大小写,大小写转换
                if (matchcase.isSelected()) { 
   
                    strA = textArea.getText();
                    strB = ftext.getText();
                } else { 
   
                    strA = textArea.getText().toLowerCase();
                    strB = ftext.getText().toLowerCase();
                }
                //向上查找,否则向下查找
                if (up.isSelected()) { 
   
                	a = strA.lastIndexOf(strB, FindStartPos - ftext.getText().length() - 1);
                } else if (down.isSelected()) { 
   
                	a = strA.indexOf(strB, FindStartPos - ftext.getText().length() + 1);
                }
                //查找到边界
                if (a > -1) { 
   
            		if (up.isSelected()) { 
   
            	  		textArea.setCaretPosition(a);
            	  		b = ftext.getText().length();
            	  		textArea.select(a, a + b);
            	  	} else if (down.isSelected()) { 
   
            	  		textArea.setCaretPosition(a);
            	  		b = ftext.getText().length();
            	  		textArea.select(a, a + b);
            		}
            	} else { 
   
            	  		JOptionPane.showMessageDialog(null, "找不到查找的内容", 
            	  				"查找", JOptionPane.INFORMATION_MESSAGE);
            	}
                //显示关键字的总数量
				Pattern p=Pattern.compile(ftext.getText());
				Matcher m=p.matcher(textArea.getText());
				while(m.find()) { 
   
					c++;
				}
				count.setText("找到"+c+"个");
			}
		});
        //取消的监听器
        no.addActionListener(new ActionListener() { 
   
			public void actionPerformed(ActionEvent e) { 
   
				jdlg.setVisible(false);
			}
		});
        
        label.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        count.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        ftext.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        findnext.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 13));
        no.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 13));
        
        panel.add(label);
        panel.add(count);
        panel.add(ftext);
        panel.add(findnext);
        panel.add(no);
        panel.add(matchcase);
        panel.add(up);
        panel.add(down);
        
        jdlg.setResizable(false);
        jdlg.setContentPane(panel);
        jdlg.setVisible(true);
	}
}

HSetFont类

package T_1029;

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

public class HSetFont extends JDialog{ 
   
	public HSetFont(JFrame f,JTextArea textArea) { 
   
		
		//获取系统字体库
    	GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fontNames = e.getAvailableFontFamilyNames();
        String[] fontStyle=new String[]{ 
   "常规","粗体","斜体","粗斜体"};
        Integer[] fontsize=new Integer[] { 
   8,9,10,11,12,13,14,16,18,20,22,24,26,28,30,32,36,48,72};
        
        JDialog jdlg = new JDialog(f, "字体设置", true);
        jdlg.setSize(453, 325);
        jdlg.setLocationRelativeTo(null);
        jdlg.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        
        
        JPanel panel=new JPanel();
        panel.setLayout(null);
        
        JButton yes=new JButton("确定");
        JButton no=new JButton("取消");
        JButton setfontcolor=new JButton("字体颜色");
        JLabel fonts=new JLabel("字体:");
        JLabel style=new JLabel("样式:");
        JLabel size=new JLabel("大小:");
        JLabel cg=new JLabel("AaBbCc");
        
        // 创建下拉列表框
        final JComboBox<String> comboBox = new JComboBox<String>(fontNames);
        final JComboBox<String> comboBox2=new JComboBox<String>(fontStyle);
        final JComboBox<Integer> comboBox3=new JComboBox<Integer>(fontsize);

        
        
        // 添加条目选中状态改变的监听器
        comboBox.addItemListener(new ItemListener() { 
   
            @Override
            public void itemStateChanged(ItemEvent e) { 
   
                // 只处理选中的状态
                if (e.getStateChange() == ItemEvent.SELECTED) { 
   
                    cg.setFont(new Font((String) comboBox.getSelectedItem(), 
                    		cg.getFont().getStyle(), cg.getFont().getSize()));
                }
            }
        });
        comboBox2.addItemListener(new ItemListener() { 
   
			public void itemStateChanged(ItemEvent e) { 
   
				if(e.getStateChange()==ItemEvent.SELECTED) { 
   
					if(comboBox2.getSelectedItem().equals("常规")) { 
   
						cg.setFont(new Font(cg.getFont().getName(), Font.PLAIN, 
								cg.getFont().getSize()));
					}
					else if(comboBox2.getSelectedItem().equals("粗体")){ 
   
						cg.setFont(new Font(cg.getFont().getName(), Font.BOLD, 
								cg.getFont().getSize()));
					}
					else if(comboBox2.getSelectedItem().equals("斜体")){ 
   
						cg.setFont(new Font(cg.getFont().getName(), Font.ITALIC, 
								cg.getFont().getSize()));
					}
					else if(comboBox2.getSelectedItem().equals("粗斜体")) { 
   
						cg.setFont(new Font(cg.getFont().getName(), Font.BOLD+ Font.ITALIC, 
								cg.getFont().getSize()));
					}
				}
			}
		});
        comboBox3.addItemListener(new ItemListener() { 
   
			public void itemStateChanged(ItemEvent e) { 
   
				if(e.getStateChange()==ItemEvent.SELECTED) { 
   
					cg.setFont(new Font(cg.getFont().getName(), cg.getFont().getStyle(), 
							(int) comboBox3.getSelectedItem()));
					
				}
			}
		});
        
        setfontcolor.addActionListener(new ActionListener() { 
   
			@Override
			public void actionPerformed(ActionEvent e) { 
   
				Color color = JColorChooser.showDialog(f, "选取颜色", null);
				// 如果用户取消或关闭窗口, 则返回的 color 为 null
				if (color == null) { 
   
					return;
				}
				textArea.setForeground(color);
			}
		});
        
        yes.addActionListener(new ActionListener() { 
   
			public void actionPerformed(ActionEvent e) { 
   
				textArea.setFont(cg.getFont());
				jdlg.setVisible(false);
			}
        });
        
        no.addActionListener(new ActionListener() { 
   
			public void actionPerformed(ActionEvent e) { 
   
				jdlg.setVisible(false);
			}
		});
        
        //设置元件位置和宽高
        fonts.setBounds(20,20,45,18);
        style.setBounds(190,20,45,18);
        size.setBounds(313,20,45,18);
        comboBox.setBounds(20,42,170,22);
        comboBox2.setBounds(190,42,119,22);
        comboBox3.setBounds(309, 42, 119, 22);
        cg.setBounds(30,89,378,137);
        setfontcolor.setBounds(20,249,102,30);
        yes.setBounds(300,249,62,30);
        no.setBounds(366,249,62,30);
        
        fonts.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        style.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        size.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        cg.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 12));
        setfontcolor.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 12));
        yes.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 13));
        no.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 13));
        comboBox.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        comboBox2.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        comboBox3.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
 
        // 设置字体下拉框为文本框的字体样式
        comboBox.setSelectedItem(textArea.getFont().getFontName());
        comboBox3.setSelectedItem(textArea.getFont().getSize());
        comboBox2.setSelectedIndex(textArea.getFont().getStyle());
        // 添加到内容面板
        panel.add(fonts);
        panel.add(style);
        panel.add(size);
        panel.add(comboBox);
        panel.add(comboBox2);
        panel.add(comboBox3);
        panel.add(setfontcolor);
        panel.add(yes);
        panel.add(no);
        panel.add(cg);
             
        jdlg.setResizable(false);
        jdlg.setContentPane(panel);
        jdlg.setVisible(true);    
    }
}

四、效果展示

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

今天的文章Java课设——文本编辑器分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/29309.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注