功能
查找、替换、重做、撤销、字体变换、保存、新建、打开文件
示意图
代码
main.java
public class Main {
public static void main(String[] args) {
Solution.main(args);
}
}
solution.java
import javax.swing.*;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import javax.swing.undo.UndoManager;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;
public class Solution extends Frame implements ActionListener, DocumentListener {
private String strFont="consolas";//记录字体,以便换字体
private int Fontsize=30;//字体大小
private JTextArea jt2;//文本域
private JLabel status;
private JFrame jf;//窗口
private String path="";//记录路径,以便保存
private String filename="";//记录文件名,以便保存
private JPanel optionsPanel;
private JButton ctrlA, ctrlX, ctrlC, ctrlV, ctrlY, ctrlZ;
private UndoManager und;
private Document document;
private Solution(){//搭建基础框架
jt2=new JTextArea();//new一个文本区
und = new UndoManager();
jt2.getDocument().addUndoableEditListener(und);
status=new JLabel();
jt2.setCaretColor(Color.RED);
jt2.setSelectedTextColor(Color.CYAN);
jt2.setSelectionColor(Color.lightGray);
jt2.setWrapStyleWord(true);
jt2.setLineWrap(true);//自动换行
jt2.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent e) {
JTextArea editArea = (JTextArea)e.getSource();
int linenum = 1;
int columnnum = 1;
try {
int caretpos = editArea.getCaretPosition();
linenum = editArea.getLineOfOffset(caretpos);
columnnum = caretpos - editArea.getLineStartOffset(linenum);
linenum += 1;
}
catch(Exception ex) { }
updateStatus(linenum, columnnum);
}
});
document = jt2.getDocument();
document.addDocumentListener(this);
String title = "java记事本";
jf=new JFrame(title);
optionsPanel = new JPanel();
optionsPanel.setLayout(new GridLayout(4, 1, 0, 70));
ctrlA = new JButton("全选");
ctrlX = new JButton("剪切");
ctrlC = new JButton("复制");
ctrlV = new JButton("粘贴");
ctrlZ = new JButton("撤销");
ctrlY = new JButton("恢复");
optionsPanel.add(ctrlA);
optionsPanel.add(ctrlX);
optionsPanel.add(ctrlC);
optionsPanel.add(ctrlV);
optionsPanel.add(ctrlZ);
optionsPanel.add(ctrlY);
ctrlA.addActionListener(this);
ctrlX.addActionListener(this);
ctrlC.addActionListener(this);
ctrlV.addActionListener(this);
ctrlZ.addActionListener(this);
ctrlY.addActionListener(this);
this.setLayout(new BorderLayout()); // 设置组件布局
//add(scrollPane, BorderLayout.CENTER); // 文本区域的可滚动面板
add(optionsPanel, BorderLayout.EAST); // 功能按钮
MenuBar mb=new MenuBar();//新建一个菜单栏
// mb.add();
FileMenu fileMenu=new FileMenu(this);//搭建两个Menu
mb.add(fileMenu);
FontMenu fontMenu=new FontMenu(this);
mb.add(fontMenu);
Function find=new Function(this);
mb.add(find);
jf.setMenuBar(mb);//菜单栏放上去
// jf.add(optionsPanel);
jf.setVisible(true);//窗体可见
jf.setSize(600, 400);//窗体大小
jf.setLayout(new BorderLayout());//边界布局
jf.add(status, BorderLayout.SOUTH);
jf.add(BorderLayout.EAST,optionsPanel);
jf.add(BorderLayout.CENTER,jt2);//文本框边界中间放置
jt2.setBackground(Color.white);
jt2.setFont(new Font(strFont,Font.PLAIN,Fontsize));
}
public void SaveAsAction(){//Save动作的处理
FileDialog fd = new FileDialog(jf, "Save as", FileDialog.SAVE);
fd.setVisible(true);
path = fd.getDirectory();//获取路径
filename = fd.getFile();//获取文件名
try {
FileOutputStream out = new FileOutputStream(path + filename, false);
String s = jt2.getText();//输出到文件
byte[] b = s.getBytes();
out.write(b);
out.close();
} catch (IOException ex) {
System.out.println(ex);
}
}
public void SaveAction(){//保存的处理
if (path.length() != 0) {
try {
FileOutputStream out = new FileOutputStream(path + filename, false);//这里flase是覆盖,否则是加到原文件末尾
String s = jt2.getText();
byte[] b = s.getBytes();
out.write(b);
out.close();
} catch (IOException ex) {
System.out.println(ex);
}
} else {
JOptionPane jo = new JOptionPane();
jo.showMessageDialog(null, "还没有将其保存到文件,请选择Save as将内容保存到文件");
}
}
public void OpenAction(){//打开的处理
FileDialog fd = new FileDialog(jf, "Open", FileDialog.LOAD);
fd.setVisible(true);
path = fd.getDirectory();
filename = fd.getFile();
if (path == null || filename == null) return;
jt2.setText("");//清空当前的内容
try {
BufferedReader re = new BufferedReader(new FileReader(path + filename));//读取文件
String s = null;
while ((s = re.readLine()) != null) { //写入文本域
jt2.append(s + "\r\n");//对于不同操作系统的回车处理
}
re.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
public void actionPerformed(ActionEvent e){
Object source = e.getSource();
// TextArea对象的方法中有全选,剪切,复制,粘贴等操作。
if (source == ctrlA) {
jt2.selectAll();
} else if (source == ctrlX) {
jt2.cut();
} else if (source == ctrlC) {
jt2.copy();
} else if (source == ctrlV) {
jt2.paste();
} else if (source==ctrlZ) {
if (und.canUndo())
und.undo();
} else if (source==ctrlY) {
if (und.canRedo())
und.redo();
}
String arg=e.getActionCommand();
switch (arg) {
case "Exit": //退出
System.exit(0);
case "Comic Sans MS": //三个if换字体
strFont = "Comic Sans MS";
break;
case "TimesRoman":
strFont = "TimesRoman";
break;
case "consolas":
strFont = "consolas";
break;
case "Increase font size": //改变字体大小
Fontsize = Fontsize + 2;
break;
case "Decrease font size":
Fontsize = Fontsize - 2;
break;
case "New":{String s = "";jt2.setText(s); break;}
case "Save as": { SaveAsAction();break; }//另存为,把文件内容导出存放
case "Save": { SaveAction();break; }//保存文件内容,和另存为相似
case "Open": { OpenAction();break; }//打开文件
case "Find":{
JFrame frame = new JFrame();
frame.setSize(500,500);
frame.setLayout(new GridLayout(2, 2));
TextField text=new TextField();
String[] str1 = new String[1];
int cur[]=new int[2];
int a[][]=new int[20][2];
JButton buttonO=new JButton("OK");
buttonO.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
str1[0] =text.getText();
String str2=jt2.getText();
// System.out.print(str2.length()-str1[0].length());
for(int i=0;i<=(str2.length()-str1[0].length());i++){
boolean ok=false; int time=0; int j;
for(j=0;j<str1[0].length();j++){
if(str1[0].charAt(j)==str2.charAt(i+j)){
time++;
}
}
if(time==str1[0].length()){
int t=i+str1[0].length();
a[cur[0]][0]=i;
a[cur[0]][1]=t;
cur[0]++;
// jt2.select(0,3);
System.out.println("文本中:第"+i+"到"+"第"+t+"匹配");
}
}
}
});
cur[1]=0;
JButton buttonB=new JButton("Before");
buttonB.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if(cur[1]>0){
cur[1]--;
}
else{
cur[1]=cur[0];
}
}
});
JButton buttonN=new JButton("Next");
buttonN.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if(cur[1]<cur[0]){
cur[1]++;
}
else{
cur[1]=0;
}
jt2.select(a[cur[1]][0],a[cur[1]][1]);
}
});
frame.add(text);
frame.add(buttonO);
frame.add(buttonB);
frame.add(buttonN);
frame.setVisible(true);
frame.invalidate();
frame.validate();
frame.repaint();
break;
}
case "Replace":{
JFrame frame = new JFrame();
frame.setSize(500,500);
frame.setLayout(new GridLayout(3, 3));
JLabel label1=new JLabel("要替换的文本");
JLabel label2=new JLabel("替换后的文本");
JLabel label3=new JLabel();
JLabel label4=new JLabel();
TextField text1=new TextField();
TextField text2=new TextField();
int cur[]=new int[1];
int [][]t=new int[20][2];//设最多有20个替换的,记录起始位置和结束位置
String str1[]=new String[1];
String str2[]=new String[1];
String str3[]=new String[1];
JButton buttonO=new JButton("OK");
buttonO.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// System.out.print(str2.length()-str1.length());
cur[0]=0;//值改变
str1[0]=text1.getText();
str2[0]=jt2.getText();
str3[0]=text2.getText();
for(int i=0;i<=(str2[0].length()-str1[0].length());i++){
boolean ok=false; int time=0; int j;
for(j=0;j<str1[0].length();j++){
if(str1[0].charAt(j)==str2[0].charAt(i+j)){
time++;
}
}
if(time==str1[0].length()){
t[cur[0]][0]=i;
t[cur[0]][1]=i+str1[0].length();
cur[0]++;
}
}
}
});
int now[]=new int[1];
now[0]=1;
JButton buttonN = new JButton("Next");
buttonN.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
String s=new String();
for(int i=0;i<now[0];i++){
if(i==0)
s+=str2[0].substring(0,t[i][0]);
else
s+=str2[0].substring(t[i-1][1],t[i][0]);
s+=str3[0];
}
s+=str2[0].substring(t[now[0]-1][1],str2[0].length());
System.out.print(s);
jt2.setText(s);
now[0]++;
if(now[0]>cur[0]){
buttonN.setEnabled(false);//灰度控制
}
}
});
JButton buttonA=new JButton("ALL");
buttonA.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
String s=new String();
for(int i=0;i<cur[0];i++){
if(i==0)
s+=str2[0].substring(0,t[i][0]);
else
s+=str2[0].substring(t[i-1][1],t[i][0]);
s+=str3[0];
}
s+=str2[0].substring(t[cur[0]-1][1],str2[0].length());
System.out.print(s);
jt2.setText(s);
}
});
frame.add(label1);
frame.add(label2);
frame.add(label3);
frame.add(text1);
frame.add(text2);
frame.add(label4);
frame.add(buttonO);
frame.add(buttonN);
frame.add(buttonA);
frame.setVisible(true);
frame.invalidate();
frame.validate();
frame.repaint();
break;
}
}
jt2.setFont(new Font(strFont,Font.PLAIN,Fontsize));
System.out.println(arg);
}
public void paint(Graphics g){
g.setFont(new Font(strFont,Font.BOLD,Fontsize));
g.drawString("",50,150);
}
public static void main(String[] args){
new Solution();
}
private void updateStatus(int linenumber, int columnnumber) {
status.setText("Line: " + linenumber + " Column: " + columnnumber);
}
@Override
public void insertUpdate(DocumentEvent e) {
if (und.canUndo())
ctrlZ.setEnabled(true);
else{
ctrlZ.setEnabled(false);
}
if (und.canRedo())
ctrlY.setEnabled(true);
else{
ctrlY.setEnabled(false);
}
}
@Override
public void removeUpdate(DocumentEvent e) {
if (und.canUndo())
ctrlZ.setEnabled(true);
else{
ctrlZ.setEnabled(false);
}
if (und.canRedo())
ctrlY.setEnabled(true);
else{
ctrlY.setEnabled(false);
}
}
@Override
public void changedUpdate(DocumentEvent e) {
if (und.canUndo())
ctrlZ.setEnabled(true);
else{
ctrlZ.setEnabled(false);
}
if (und.canRedo())
ctrlY.setEnabled(true);
else{
ctrlY.setEnabled(false);
}
}
}
filemenu.java
import java.awt.*;
import java.awt.event.ActionListener;
class FileMenu extends Menu{//FileMenu的内容
public FileMenu(ActionListener action){
super("File");
MenuItem mi0,mi1,mi2,mi3,mi4;
mi0=(new MenuItem("New"));
mi1=(new MenuItem("Save as"));
mi2=(new MenuItem("Save"));
mi3=(new MenuItem("Open"));
mi4=(new MenuItem("Exit"));
mi0.addActionListener(action);//添加监听,点击的时候才能捕捉到
mi1.addActionListener(action);
mi2.addActionListener(action);
mi3.addActionListener(action);
mi4.addActionListener(action);
add(mi0);add(mi1);add(mi2);add(mi3);
addSeparator();
add(mi4);
}
}
fontmenu.java
import java.awt.*;
import java.awt.event.ActionListener;
class FontMenu extends Menu{//FontMenu的内容
public FontMenu(ActionListener action){
super("Font");
MenuItem mi1,mi2,mi3,mi4,mi5;
mi1=new MenuItem("TimesRoman");
mi2=new MenuItem("Comic Sans MS");
mi3=new MenuItem("consolas");
mi4=new MenuItem("Increase font size");
mi5=new MenuItem("Decrease font size");
mi1.addActionListener(action);//添加监听
mi2.addActionListener(action);
mi3.addActionListener(action);
mi4.addActionListener(action);
mi5.addActionListener(action);
add(mi1);
add(mi2);
add(mi3);
addSeparator();
add(mi4);
add(mi5);
}
}
function.java
import java.awt.*;
import java.awt.event.ActionListener;
public class Function extends Menu {
public Function(ActionListener action){
super("Function");
MenuItem mi1,mi2;
mi1=new MenuItem("Find");
mi2=new MenuItem("Replace");
super.addActionListener(action);
add(mi1);add(mi2);
addSeparator();
}
}