您的位置:首页 > 编程语言 > Java开发

Java学了几个月,写的记事本,从网上借鉴了一部分,可能有些不足的地方,分享一下~~

2014-07-13 12:23 375 查看


(可拖读,有c++,Java、html等模板(路径默认为D:\Documents\Desktop,所以可能要改一下),能查找替换,更换字体和背景色,显示当前时间,光标所在行列,总字数等。)

package myeditor;

import java.awt.*;

import java.awt.datatransfer.Clipboard;

import java.awt.datatransfer.DataFlavor;

import java.awt.datatransfer.StringSelection;

import java.awt.datatransfer.Transferable;

import java.awt.dnd.DnDConstants;

import java.awt.dnd.DropTarget;

import java.awt.dnd.DropTargetAdapter;

import java.awt.dnd.DropTargetDropEvent;

import java.awt.event.*;

import java.io.*;

import java.util.Date;

import java.util.Iterator;

import java.util.List;

import java.util.Timer;

import java.util.TimerTask;

import java.text.SimpleDateFormat;

import javax.swing.*;

import javax.swing.event.CaretEvent;

import javax.swing.event.CaretListener;

import javax.swing.filechooser.FileNameExtensionFilter;

public class MyEditor

{

private JFrame f,f_font,f_close;

private JMenuBar mb;

private JPopupMenu rightmenu;

private JMenu mf,ms,help,sub_newcreate,tool;

private JMenuItem copyIt,pasteIt,selectAllIt,cutIt,clearIt,searchandreplace;

private JMenuItem closeItem,subIt_c,subIt_java,subIt_perl,subIt_html,subIt_standard,about,font,chara_color,back_color,open,save,saveas;

private Container con,container;

private JToolBar toolBar;

private JPanel pcom_lab,pcom,picta,pclose,pclosebut;

private JTextArea ta;

private TextArea tabout;

private JTextField jf1,jf2;

private JFileChooser opendia,savedia;

private JDialog dsear_rep,fabout;

private File file;

private JCheckBox capscheck;

private int[] filenum=new int[]{1,1,1,1,1};

private JLabel labtest,labtime,lablincol,labclose,searchcontent,replaceas,labcharactersum;

private int num=1,line=1,col=1,start,end,fostyle=Font.PLAIN,fosize=16,position,startposition,endposition,totalindex,startindex,charactersum;

private JComboBox<String> jcbfont,jcbsize,jcbstyle;

private JButton okbut,canbut,abbut,closeyesbut,closenobut,closecanbut,searnextbut,replacenextbut,replaceallbut,sear_repcanbut,searpreviousbut;

private String fontFont[]={"Serif","Sanserif","Monospace","Dialog","DialogInput"};

private String fontStyle[]={"PLAIN","BOLD","ITALIC","BOLD+ITALIC"};

private String fontSize[]={"10","12","14","16","18","20","22","24","26","48","72"};

private String filetype="txt",tempstr,fofont="Serif",styletemp,filePath="D:\\Documents\\Desktop\\新建文档("+num+").txt";

private String strabout,jf1str,jf2str,substr,template,codetype;

private Font tafont,labfont;

private ImageIcon imgcon,closewarcon;

private Image imglogo;

private SimpleDateFormat sdf;

private Clipboard clipboard;

private StringSelection strsect;

private StringBuffer sufr;

private boolean isinit=true,isstart=true;

private BufferedInputStream bin;

MyEditor(){

init();

}

public void init()

{

f=new JFrame("<my-editor>"+filePath);

imglogo=Toolkit.getDefaultToolkit().getImage("C:/javaworkspace/xx/src/xx/pic/bridge.jpg");

f.setIconImage(imglogo);

f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

f.setBounds(300,100,500,600);

//设置菜单

mb=new JMenuBar();

mf=new JMenu("文件");

sub_newcreate=new JMenu("新建");

subIt_standard=new JMenuItem("标准文本");

subIt_c=new JMenuItem("c++");

subIt_java=new JMenuItem("java");

subIt_html=new JMenuItem("html");

subIt_perl=new JMenuItem("perl");

sub_newcreate.add(subIt_standard);

sub_newcreate.add(subIt_c);

sub_newcreate.add(subIt_java);

sub_newcreate.add(subIt_html);

sub_newcreate.add(subIt_perl);

open=new JMenuItem("打开");

save=new JMenuItem("保存");

saveas=new JMenuItem("另存为");

closeItem=new JMenuItem("退出");

mf.add(sub_newcreate);

mf.add(open);

mf.add(save);

mf.add(saveas);

mf.add(closeItem);

//设置菜单项

ms=new JMenu("设置");

font=new JMenuItem("文字字体");

chara_color=new JMenuItem("文字颜色");

back_color=new JMenuItem("背景颜色");

ms.add(font);

ms.add(chara_color);

ms.add(back_color);

//工具菜单项

tool=new JMenu("工具");

searchandreplace=new JMenuItem("查找&替换");

tool.add(searchandreplace);

help=new JMenu("帮助");

about=new JMenuItem("关于");

help.add(about);

mb.add(mf);

mb.add(ms);

mb.add(tool);

mb.add(help);

//打开和保存触发的文件对话框

opendia=new JFileChooser();

savedia=new JFileChooser();

opendia.setFileSelectionMode(JFileChooser.OPEN_DIALOG);

//savedia.setFileSelectionMode(JFileChooser.SAVE_DIALOG);//!!!!!这里不能显示,否则不能给文件默认初始化命名

//设置文字设置选择框

f_font=new JFrame("文字设置");

pcom_lab=new JPanel(new GridLayout(2,1));

pcom=new JPanel();

jcbfont=new JComboBox<String>(fontFont);

jcbfont.setBorder(BorderFactory.createTitledBorder("字体"));

jcbstyle=new JComboBox<String>(fontStyle);

jcbstyle.setBorder(BorderFactory.createTitledBorder("粗细"));

jcbsize=new JComboBox<String>(fontSize);

jcbsize.setBorder(BorderFactory.createTitledBorder("大小"));

labtest=new JLabel("示例:ABCabcxyzXYZ",JLabel.CENTER);

pcom.add(jcbfont);

pcom.add(jcbstyle);

pcom.add(jcbsize);

pcom_lab.add(pcom);

pcom_lab.add(labtest);

okbut=new JButton("确定");

canbut=new JButton("取消");

f_font.setLayout(new FlowLayout());

f_font.add(pcom_lab);

f_font.add(okbut);

f_font.add(canbut);

f_font.setBounds(200, 300, 360, 300);

f_font.setResizable(false);

f_font.setVisible(false);

//查找框

dsear_rep=new JDialog(f);

dsear_rep.setBounds(450, 450, 500, 212);

container=dsear_rep.getContentPane();

container.setLayout(null);

searchcontent= new JLabel("查找内容:");

searchcontent.setBounds(26, 27, 71, 24);

container.add(searchcontent);

replaceas = new JLabel("替换为:");

replaceas.setBounds(26, 70, 71, 24);

container.add(replaceas);

jf1 = new JTextField();

jf1.setBounds(123, 24, 196, 30);

container.add(jf1);

jf1.setColumns(10);

jf2 = new JTextField();

jf2.setBounds(123, 70, 196, 30);

dsear_rep.getContentPane().add(jf2);

jf2.setColumns(10);

searpreviousbut = new JButton("查找上一个");

searpreviousbut.setBounds(353, 10, 103, 23);

container.add(searpreviousbut);

searnextbut = new JButton("查找下一个");

searnextbut.setBounds(353, 38, 103, 23);

container.add(searnextbut);

replacenextbut = new JButton("替换");

replacenextbut.setBounds(353, 70, 103, 23);

container.add(replacenextbut);

replaceallbut = new JButton("替换全部");

replaceallbut.setBounds(353, 98, 103, 23);

container.add(replaceallbut);

capscheck = new JCheckBox("区分大小写");

capscheck.setBounds(94, 127, 124, 30);

container.add(capscheck);

sear_repcanbut = new JButton("取消");

sear_repcanbut.setBounds(266, 131, 93, 26);

container.add(sear_repcanbut);

dsear_rep.setVisible(false);

//about框

fabout=new JDialog(f,"关于my-editor");

fabout.setLayout(new FlowLayout());

picta=new JPanel(new GridLayout(1,2));

sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

strabout="my-editor\r\n@沧洱\r\n@2014年7月\r\n联系我们:\r\nwww.my-editor.com"

+"\r\n时间:"+sdf.format(new Date())+"\r\n^v^谢谢您的使用!";

imgcon=new ImageIcon("C:/javaworkspace/xx/src/xx/pic/bridge.jpg");

tabout=new TextArea(strabout,4,20,TextArea.SCROLLBARS_VERTICAL_ONLY);

tabout.setBackground(Color.LIGHT_GRAY);

tabout.setEditable(false);

abbut=new JButton("确定");

picta.add(new JLabel(imgcon));

picta.add(tabout);

fabout.add(picta);

fabout.add(abbut);

fabout.setBounds(400, 400, 380, 210);

//fabout.setResizable(false);

fabout.setVisible(false);

//工具栏

con=f.getContentPane();

toolBar=new JToolBar();

labtime=new JLabel("当前时间:"+sdf.format(new Date()));

new Timer().scheduleAtFixedRate(new TimerTask(){public void run(){labtime.setText("当前时间:"+sdf.format(new Date()));}},new Date(),1000);

lablincol=new JLabel("行:"+line+" 列:"+col);

labcharactersum=new JLabel("总字数:"+charactersum);

toolBar.add(labtime);

toolBar.addSeparator(new Dimension(65,5));

toolBar.add(labcharactersum);

toolBar.addSeparator(new Dimension(65,5));

toolBar.add(lablincol);

clipboard = f.getToolkit().getSystemClipboard();//剪贴板

ta=new JTextArea("",36,71);//编辑区

ta.setLineWrap(true); //自动换行

tafont=new Font(fofont,fostyle,fosize);//编辑区字体

ta.setFont(tafont);

//ta.setBackground(Color.getHSBColor(0.5f, 0.3f, 0.7f));

f.setJMenuBar(mb);

con.add(toolBar,BorderLayout.SOUTH);

con.add(new JScrollPane(ta,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER));

//设置关闭弹出窗口

f_close=new JFrame("MyEditor");

f_close.setBounds(400, 400, 450, 156);

f_close.setLayout(new FlowLayout());

pclose=new JPanel();

closewarcon=new ImageIcon("C:\\javaworkspace\\Myeditor\\src\\myeditor\\pic\\warning.jpg");

labclose=new JLabel();//<br>标签换行

pclose.add(new JLabel(closewarcon));

pclose.add(labclose);

pclosebut=new JPanel(new GridLayout(1,3,30,30));

closeyesbut=new JButton("是");

closenobut=new JButton("否");

closecanbut=new JButton("取消");

pclosebut.add(closeyesbut);

pclosebut.add(closenobut);

pclosebut.add(closecanbut);

f_close.add(pclose);

f_close.add(pclosebut);

f_close.setVisible(false);

//右键菜单

rightmenu=new JPopupMenu();

copyIt=new JMenuItem("复制");

pasteIt=new JMenuItem("粘贴");

cutIt=new JMenuItem("剪切");

clearIt=new JMenuItem("清除");

selectAllIt=new JMenuItem("全选");

rightmenu.add(copyIt);

rightmenu.add(pasteIt);

rightmenu.add(cutIt);

rightmenu.add(clearIt);

rightmenu.add(selectAllIt);

ta.add(rightmenu);

f.setVisible(true);

try{

myEvent();

}

catch (Exception e){

e.printStackTrace();

}

}

//监听

private void myEvent()throws Exception{

f.addWindowListener(new WindowAdapter(){//关闭时判断

public void windowClosing(WindowEvent e){

if("".equals(ta.getText())){

System.exit(0);

}else{

labclose.setText("<html>文件 "+filePath+"的文字已经改变。<br>想保存文件吗?</html>");

f_close.setVisible(true);

}

}

});

closeyesbut.addActionListener(new ActionListener(){//关闭时保存文件

public void actionPerformed(ActionEvent e){

f_close.setVisible(false);

savedia.setVisible(true);

FileNameExtensionFilter typefilter=new FileNameExtensionFilter(filetype+"文件",filetype,filetype.toUpperCase());

savedia.setFileFilter(typefilter);

//savedia.setCurrentDirectory(new File("c:/"));

savedia.setSelectedFile(new File("."+filetype));

int result = savedia.showSaveDialog(f);

if(result==JFileChooser.APPROVE_OPTION){

file=savedia.getSelectedFile();

filePath=file.getAbsolutePath();

}

if(result == JFileChooser.CANCEL_OPTION){

savedia.setVisible(false);

}

file=new File(filePath);

try{

BufferedWriter buwr=new BufferedWriter(new FileWriter(file));

String text=ta.getText();

buwr.write(text);

buwr.close();

f.setVisible(false);

}

catch (IOException e5){

throw new RuntimeException("写入失败.");

}

}

});

closenobut.addActionListener(new ActionListener(){//关闭退出

public void actionPerformed(ActionEvent e){

System.exit(0);

}

});

closecanbut.addActionListener(new ActionListener(){//关闭退出

public void actionPerformed(ActionEvent e){

f_close.setVisible(false);

}

});

//拖读操作

DropTargetAdapter dtg=new DropTargetAdapter(){

@SuppressWarnings("unchecked")

public void drop(DropTargetDropEvent e){

try{

Transferable tf=e.getTransferable();

if(tf.isDataFlavorSupported(DataFlavor.javaFileListFlavor)){//返回一个指示指定的 DataFlavor 是否受支持 boolean 值

e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);

List<File> lt=(List<File>)tf.getTransferData(DataFlavor.javaFileListFlavor);

Iterator<File> itor=lt.iterator();

while(itor.hasNext()){

File file=(File)itor.next();

filePath=file.getAbsolutePath();

f.setTitle(filePath);

ta.setText("");

try{

codetype=codeString(filePath);//utf-8 "UTF-8" "Unicode" "UTF-16BE" "ASCII" "GBK"

FileInputStream fis=new FileInputStream(filePath);

BufferedReader bufr=new BufferedReader(new InputStreamReader((fis),codetype));

StringBuilder sb=new StringBuilder();

String line=null;

while((line=bufr.readLine())!=null){

sb.append(line);

sb.append("\r\n");

}

bufr.close();

fis.close();

ta.setText(sb.toString());

e.dropComplete(true);

}catch(IOException e1){

throw new RuntimeException("读取失败.");

}

catch(Exception e2){}

}

}else{

e.rejectDrop();

}

}catch(Exception e1){

e1.printStackTrace();

}

}};

new DropTarget(ta,DnDConstants.ACTION_COPY_OR_MOVE,dtg);//在f上设置dtg监听器(拖读操作)

f_font.addWindowListener(new WindowAdapter(){//字体设置对话框

public void windowClosing(WindowEvent e){

f_font.setVisible(false);

}

});

ta.addCaretListener(new CaretListener() { //获取光标行列数

public void caretUpdate(CaretEvent e) {

try {

position=ta.getCaretPosition();

line=ta.getLineOfOffset(position)+1; //获取行数

col=position-ta.getLineStartOffset(line-1)+1; //获取列数

lablincol.setText("行:"+line+" 列:"+col);

charactersum=ta.getText().length();

labcharactersum.setText("总字数:"+charactersum);

} catch(Exception ex) {

lablincol.setText( "无法获得当前光标位置 ");

}

}

});

ta.addMouseListener(new MouseAdapter(){//右键操作

public void mouseClicked(MouseEvent e){

int c=e.getButton();

if(c==MouseEvent.BUTTON3){//当是右键显示菜单

rightmenu.setVisible(true);

rightmenu.show(e.getComponent(),e.getX(),e.getY());

}

}

});

copyIt.addActionListener(new ActionListener(){//右键复制

public void actionPerformed(ActionEvent e){

tempstr=ta.getSelectedText();

strsect=new StringSelection(tempstr);

clipboard.setContents(strsect,null);

}

});

pasteIt.addActionListener(new ActionListener(){//右键粘贴

public void actionPerformed(ActionEvent e){

Transferable contents=clipboard.getContents(this);

DataFlavor flavor= DataFlavor.stringFlavor;

if( contents.isDataFlavorSupported(flavor))

try{ String str;

str=(String)contents.getTransferData(flavor);

ta.append(str);

}

catch(Exception ee){}

}

});

cutIt.addActionListener(new ActionListener(){//右键剪切

public void actionPerformed(ActionEvent e){

tempstr=ta.getSelectedText();

strsect=new StringSelection(tempstr);

clipboard.setContents(strsect,null);

start=ta.getSelectionStart();

end=ta.getSelectionEnd();

ta.replaceRange("",start,end); // 用指定替换文本替换指定开始位置与结束位置之间的文本

}

});

clearIt.addActionListener(new ActionListener(){//右键清除

public void actionPerformed(ActionEvent e){

start=ta.getSelectionStart();

end =ta.getSelectionEnd();

ta.replaceRange("",start,end) ;

}

});

selectAllIt.addActionListener(new ActionListener(){//右键全选

public void actionPerformed(ActionEvent e){

ta.selectAll();

}

});

closeItem.addActionListener(new ActionListener(){//关闭退出

public void actionPerformed(ActionEvent e){

System.exit(0);

}

});

subIt_standard.addActionListener(new ActionListener(){//创建标准文本

public void actionPerformed(ActionEvent e){

filetype="txt";

template="";

template(filetype,template);

}

});

subIt_c.addActionListener(new ActionListener(){//创建c++文件

public void actionPerformed(ActionEvent e){

filetype="cpp";

template="#include <stdio.h>\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n\tprintf(\"Hello, world\\n\");\r\n\r\n\treturn 0;\r\n}";

template(filetype,template);

}

});

subIt_java.addActionListener(new ActionListener(){//创建Java文件

public void actionPerformed(ActionEvent e){

filetype="java";

template="class\r\n{\r\n\tpublic static void main(String[] args) \r\n\t{\r\n\t\tSystem.out.println(\"Hello World!\");\r\n\t}\r\n}";

template(filetype,template);

}

});

subIt_html.addActionListener(new ActionListener(){//创建html文件

public void actionPerformed(ActionEvent e){

filetype="html";

template="<!doctype html>\r\n<html lang=\"en\">\r\n <head>\r\n <meta charset=\"UTF-8\">\r\n "+

"<meta name=\"Author\" content=\"\">\r\n <meta name=\"Keywords\" content=\"\">\r\n <meta name=\"Description\" "+

"content=\"\">\r\n<title>Document</title>\r\n </head>\r\n <body>\r\n\r\n </body>\r\n</html>\r\n";

template(filetype,template);

}

});

subIt_perl.addActionListener(new ActionListener(){//创建perl文件

public void actionPerformed(ActionEvent e){

filetype="perl";

template="#!/usr/bin/perl\r\nuse strict;\r\nuse warnings;\r\n\r\nprint \"Hello, World...\";\r\n\r\n";

template(filetype,template);

}

});

open.addActionListener(new ActionListener(){//打开文件

public void actionPerformed(ActionEvent e){

opendia.setVisible(true);

if(opendia.showOpenDialog(null)==JFileChooser.APPROVE_OPTION){

file=opendia.getSelectedFile();

filePath=file.getAbsolutePath();

}

ta.setText("");

file=new File(filePath);

filePath=file.getAbsolutePath();

filetype=filePath.substring(filePath.indexOf(".")+1,filePath.length());

f.setTitle(filePath);

try{

codetype=codeString(filePath);//utf-8 "UTF-8" "Unicode" "UTF-16BE" "ASCII" "GBK"

FileInputStream fis=new FileInputStream(filePath);

BufferedReader bufr=new BufferedReader(new InputStreamReader((fis),codetype));

String line=null;

while((line=bufr.readLine())!=null){

ta.append(line+"\r\n");

}

bufr.close();

fis.close();

}

catch (IOException e4){

throw new RuntimeException("读取失败.");

}catch(Exception ex){}

}

});

saveas.addActionListener(new ActionListener(){//另存为

public void actionPerformed(ActionEvent e){

savedia.setVisible(true);

FileNameExtensionFilter typefilter=new FileNameExtensionFilter(filetype+"文件",filetype,filetype.toUpperCase());

savedia.setFileFilter(typefilter);

//savedia.setCurrentDirectory(new File("c:/"));

savedia.setSelectedFile(new File("."+filetype));

//int result = savedia.showSaveDialog(null);

if(savedia.showSaveDialog(null)==JFileChooser.APPROVE_OPTION){

file=savedia.getSelectedFile();

filePath=file.getAbsolutePath();

}

//if(result == JFileChooser.CANCEL_OPTION){

// //JOptionPane.showMessageDialog(null, "没有选择任何文件", "保存", JOptionPane.ERROR_MESSAGE);

// savedia.setVisible(false);

//}

file=new File(filePath);

try{

BufferedWriter buwr=new BufferedWriter(new FileWriter(file));

String text=ta.getText();

buwr.write(text);

buwr.close();

}

catch (IOException e5){

throw new RuntimeException("写入失败.");

}

}

});

//System.out.println(System.getProperty("user.dir")); 获取当前路径

save.addActionListener(new ActionListener(){//保存文件

public void actionPerformed(ActionEvent e){

save();

}

});

font.addActionListener(new ActionListener(){//字体设置弹出

public void actionPerformed(ActionEvent e){

f_font.setVisible(true);

}

});

jcbfont.addItemListener(new ItemListener(){//字体下拉框

@SuppressWarnings("unchecked")

public void itemStateChanged(ItemEvent e){

if(e.getStateChange()==ItemEvent.SELECTED){

jcbfont=(JComboBox<String>)e.getSource();

fofont=(String)jcbfont.getSelectedItem();

labfont=new Font(fofont,fostyle,fosize);

labtest.setFont(labfont);

}

}

});

jcbstyle.addItemListener(new ItemListener(){//样式下拉框

@SuppressWarnings("unchecked")

public void itemStateChanged(ItemEvent e){

if(e.getStateChange()==ItemEvent.SELECTED){

jcbstyle=(JComboBox<String>)e.getSource();

styletemp=(String)jcbstyle.getSelectedItem();

if("PLAIN".equals(styletemp))fostyle=Font.PLAIN;

else if("BOLD".equals(styletemp))fostyle=Font.BOLD;

else if("ITALIC".equals(styletemp))fostyle=Font.ITALIC;

else if("BOLD+ITALIC".equals(styletemp))fostyle=Font.BOLD+Font.ITALIC;

labfont=new Font(fofont,fostyle,fosize);

labtest.setFont(labfont);

}

}

});

jcbsize.addItemListener(new ItemListener(){//大小下拉框

@SuppressWarnings("unchecked")

public void itemStateChanged(ItemEvent e){

if(e.getStateChange()==ItemEvent.SELECTED){

jcbsize=(JComboBox<String>)e.getSource();

fosize=Integer.parseInt((String)jcbsize.getSelectedItem());

labfont=new Font(fofont,fostyle,fosize);

labtest.setFont(labfont);

}

}

});

chara_color.addActionListener(new ActionListener(){//字体设置弹出

public void actionPerformed(ActionEvent e){

Color c1=JColorChooser.showDialog(f,"请选择文字颜色",Color.cyan);

if(c1!=null){

ta.setForeground(c1);

}

else

ta.setForeground(ta.getForeground());

}

});

back_color.addActionListener(new ActionListener(){//字体设置弹出

public void actionPerformed(ActionEvent e){

Color c2=JColorChooser.showDialog(f,"请选择背景颜色",Color.cyan);

if(c2!=null){

ta.setBackground(c2);

}

else

ta.setBackground(ta.getBackground());

}

});

okbut.addActionListener(new ActionListener(){//文字设置中确定按键

public void actionPerformed(ActionEvent e){

Font font=new Font(fofont,fostyle,fosize);

ta.setFont(font);

f_font.setVisible(false);

}

});

canbut.addKeyListener(new KeyAdapter(){//文字设置中取消按键

public void keyPressed(KeyEvent e){

f_font.setVisible(false);

}

});

searchandreplace.addActionListener(new ActionListener(){//查找弹出框

public void actionPerformed(ActionEvent e){

dsear_rep.setVisible(true);

}

});

searnextbut.addActionListener(new ActionListener(){//查找下一个

public void actionPerformed(ActionEvent e){

if(jf1str==null || (jf1str!=null && !(jf1str.equals(jf1.getText())))){

isinit=true;

}

jf1str=jf1.getText();

if(isinit){

totalindex=startposition=0;

substr=ta.getText().substring(startposition);

isinit=false;

}

if(capscheck.isSelected()){//不区分大小写

startposition=substr.indexOf(jf1str);

totalindex+=startposition;

if((substr.indexOf(jf1str))!=-1){

//System.out.println("start:"+(startposition+1));

endposition=startposition+jf1str.length();

ta.select(totalindex, totalindex+jf1str.length());

//System.out.println("get:"+substr.substring(startposition, endposition));

substr=substr.substring(startposition+1);

totalindex++;

}else{

JOptionPane.showMessageDialog(dsear_rep,"没有您查找的内容了!","向下查找",JOptionPane.INFORMATION_MESSAGE);

isstart=true;

}

}else{//区分大小写

startposition=substr.toUpperCase().indexOf(jf1str.toUpperCase());

totalindex+=startposition;

if((substr.toUpperCase().indexOf(jf1str.toUpperCase()))!=-1){

endposition=startposition+jf1str.length();

ta.select(totalindex, totalindex+jf1str.length());

substr=substr.toUpperCase().substring(startposition+1);

totalindex++;

}else{

JOptionPane.showMessageDialog(dsear_rep,"没有您查找的内容了!","向下查找",JOptionPane.INFORMATION_MESSAGE);

isstart=true;

}

}

}

});

searpreviousbut.addActionListener(new ActionListener(){//查找前一个

public void actionPerformed(ActionEvent e){

if(jf1str==null || (jf1str!=null && !(jf1str.equals(jf1.getText())))){

isinit=true;

}

jf1str=jf1.getText();

if(isinit){

totalindex=ta.getText().length();

isinit=false;

}

if(!(capscheck.isSelected())){//不区分大小写

if(ta.getSelectedText()!=null){

if(isstart){

if(ta.getText().lastIndexOf(jf1str)!=-1){

substr=ta.getText().substring(0,ta.getText().lastIndexOf(jf1str));

isstart=false;

}

}else{

if(totalindex!=-1 && totalindex<ta.getText().length()){

substr=substr.substring(0,totalindex);

}

}

}

else{

substr=ta.getText().substring(0,ta.getText().length());

}

startposition=substr.lastIndexOf(jf1str);

totalindex=startposition;

if((substr.lastIndexOf(jf1str))!=-1){

endposition=startposition+jf1str.length();

ta.select(startposition, endposition);

}else{

JOptionPane.showMessageDialog(dsear_rep,"没有您查找的内容了!","向上查找",JOptionPane.INFORMATION_MESSAGE);

isinit=true;

}

}else{//区分大小写

if(ta.getSelectedText()!=null){

substr=ta.getText().substring(0,ta.getText().toUpperCase().lastIndexOf(jf1str.toUpperCase()));

}

else{

substr=ta.getText().substring(0,ta.getText().length());

}

startposition=substr.toUpperCase().lastIndexOf(jf1str.toUpperCase());

totalindex=startposition;

if((substr.toUpperCase().lastIndexOf(jf1str.toUpperCase()))!=-1){

endposition=startposition+jf1str.length();

ta.select(startposition, endposition);

substr=substr.substring(0,startposition);

}else{

JOptionPane.showMessageDialog(dsear_rep,"没有您查找的内容了!","向上查找",JOptionPane.INFORMATION_MESSAGE);

isinit=true;

}

}

}

});

replacenextbut.addActionListener(new ActionListener(){//替换(每次找到jf1str的位置,然后用jf2str换掉,再找。。。)

public void actionPerformed(ActionEvent e){

jf1str=jf1.getText();

jf2str=jf2.getText();

if(ta.getText().length()>0){

if(jf1str.length()<=0)

JOptionPane.showMessageDialog(dsear_rep,"所填为空,不能替换!","替换",JOptionPane.INFORMATION_MESSAGE);

else{

if(ta.getSelectedText()==null || substr==null){

if(!(capscheck.isSelected())){

if(ta.getText().indexOf(jf1str)==-1)

JOptionPane.showMessageDialog(dsear_rep,"找不到"+jf1str+"!","替换",JOptionPane.INFORMATION_MESSAGE);

startindex=ta.getText().indexOf(jf1str);

}else{

if(ta.getText().toUpperCase().indexOf(jf1str.toUpperCase())==-1)

JOptionPane.showMessageDialog(dsear_rep,"找不到"+jf1str+"!","替换",JOptionPane.INFORMATION_MESSAGE);

startindex=ta.getText().toUpperCase().indexOf(jf1str.toUpperCase());

}

substr=ta.getText().substring(startindex+1,ta.getText().length());

ta.select(startindex,startindex+jf1str.length());

}else{

if(startindex!=-1){

ta.replaceSelection(jf2str);

}

}

}

}else

JOptionPane.showMessageDialog(dsear_rep,"没有内容,不能替换!","替换",JOptionPane.INFORMATION_MESSAGE);

}

});

replaceallbut.addActionListener(new ActionListener(){//替换全部

public void actionPerformed(ActionEvent e){

jf1str=jf1.getText();

jf2str=jf2.getText();

if(ta.getText().length()>0){

if(jf1str.length()<=0)

JOptionPane.showMessageDialog(dsear_rep,"查找项所填为空,不能替换!","替换",JOptionPane.INFORMATION_MESSAGE);

else{

while(true){

if(ta.getSelectedText()==null || substr==null){

if(!(capscheck.isSelected())){

if(ta.getText().indexOf(jf1str)==-1){

JOptionPane.showMessageDialog(dsear_rep,"找不到"+jf1str+"!","替换",JOptionPane.INFORMATION_MESSAGE);

break;

}

startindex=ta.getText().indexOf(jf1str);

}else{

if(ta.getText().toUpperCase().indexOf(jf1str.toUpperCase())==-1){

JOptionPane.showMessageDialog(dsear_rep,"找不到"+jf1str+"!","替换",JOptionPane.INFORMATION_MESSAGE);

break;

}

startindex=ta.getText().toUpperCase().indexOf(jf1str.toUpperCase());

}

substr=ta.getText().substring(startindex+1,ta.getText().length());

ta.select(startindex,startindex+jf1str.length());

}else{

if(startindex!=-1){

ta.replaceSelection(jf2str);

}

}

}

}

}else

JOptionPane.showMessageDialog(dsear_rep,"没有内容,不能替换!","替换",JOptionPane.INFORMATION_MESSAGE);

}

});

sear_repcanbut.addActionListener(new ActionListener(){//查找替换取消

public void actionPerformed(ActionEvent e){

dsear_rep.setVisible(false);

isinit=true;

}

});

about.addActionListener(new ActionListener(){//about设置

public void actionPerformed(ActionEvent e){

fabout.setVisible(true);

}

});

abbut.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){//about设置确定按键

fabout.setVisible(false);

}

});

}

//创建文件

private void createFile(String str,String init_info)throws IOException{

filePath=filePath.substring(0, filePath.indexOf(".")+1)+filetype;

if(!(new File(filePath).exists()))

file=new File("D:\\Documents\\Desktop\\新建文档("+1+")."+filetype);

else{

if(filetype.equals("txt")){

file=new File("D:\\Documents\\Desktop\\新建文档("+(++filenum[0])+")."+filetype);

}else if(filetype.equals("cpp")){

file=new File("D:\\Documents\\Desktop\\新建文档("+(++filenum[1])+")."+filetype);

}else if(filetype.equals("java")){

file=new File("D:\\Documents\\Desktop\\新建文档("+(++filenum[2])+")."+filetype);

}else if(filetype.equals("html")){

file=new File("D:\\Documents\\Desktop\\新建文档("+(++filenum[3])+")."+filetype);

}else if(filetype.equals("perl")){

file=new File("D:\\Documents\\Desktop\\新建文档("+(++filenum[4])+")."+filetype);

}

}

//file.createNewFile();

FileWriter fw=new FileWriter(file);

fw.write(init_info);

ta.setText(init_info);

fw.close();

}

private void save(){//保存文件

filePath=filePath.substring(0, filePath.indexOf(".")+1)+filetype;

file=new File(filePath);

try{

BufferedWriter buwr=new BufferedWriter(new FileWriter(file));

String text=ta.getText();

buwr.write(text);

buwr.close();

//f.setVisible(false);

}

catch (IOException e5){

throw new RuntimeException("写入失败.");

}

}

private String codeString(String filePath) throws Exception{

bin = new BufferedInputStream(

new FileInputStream(filePath));

int p = (bin.read() << 8) + bin.read();

codetype = null;

switch (p) {

case 0xefbb:

codetype = "UTF-8";

break;

case 0xfffe:

codetype = "Unicode";

break;

case 0xfeff:

codetype = "UTF-16BE";

break;

case 0x5c75:

codetype = "ANSI|ASCII" ;

break;

default:

codetype = "GBK";

}

return codetype;

}

private void template(String filetype,String template){//传入参数,以创建不同的文档模板

File filex=new File(filePath.substring(0, filePath.indexOf(".")+1)+filetype);

if(filex.exists()){

if(JOptionPane.showConfirmDialog(f,"先前文档是否保存?","消息!", JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)

save();

else{

if(filex.exists())

filex.delete();

}

}

sufr=new StringBuffer();

sufr.append(template);

try{

createFile(filetype,sufr.toString());

}

catch (IOException e3){

e3.printStackTrace();

}

}

public static void main(String[] args) {

new MyEditor();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐