diff --git a/src/java2022spring/Notepad.java b/src/java2022spring/Notepad.java new file mode 100644 index 0000000000000000000000000000000000000000..7d3146159ed2362b6ad550f4b1cae5c007e0283d --- /dev/null +++ b/src/java2022spring/Notepad.java @@ -0,0 +1,1180 @@ +package java2022spring; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Container; +import java.awt.Desktop; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.InputEvent; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.print.PageFormat; +import java.awt.print.PrinterJob; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Calendar; +import java.util.GregorianCalendar; +import javax.swing.*; +import javax.swing.border.EmptyBorder; +import javax.swing.event.CaretEvent; +import javax.swing.event.CaretListener; +import javax.swing.undo.UndoManager; + +public class Notepad extends JFrame implements ActionListener { + + //设个文本区 + private JTextArea editArea; + + //设个控制面板 + private JPanel panel; + + //设个滚动面板 + private JScrollPane scrollPane;//可滚动的pane里面添加editArea就可以变为一个可以滚动的文本框 + + //设个状态栏 + private JToolBar statusBarState; + //状态栏时间标签 + static JLabel time_label; + //状态栏行数列数标签 字数标签 + private JLabel Line_label,ForCount_label; + + //设个菜单栏 + private JMenuBar menuBar; + + //设个子菜单 + private JMenu m_File,m_Edit,m_Format,m_View,m_Help; //菜单栏内的菜单 文件 编辑 格式 查看 帮助 + private JMenuItem iF_new,iF_open,iF_save,iF_saveas,iF_exit,iF_page, + iE_undo,IE_redo,iE_cut,iE_copy,iE_stick,iE_delete,iE_findReplace,iE_turnto,iE_selectall,iE_timeItem, + iFt_background,iFt_fontcolor,iFt_font, + iV_statistics, + iH_viewHelp,iH_about; + private JCheckBoxMenuItem iFt_wrap, iV_statusBar,iV_lineNumber; + //file菜单的子项 新建 打开 保存 另存为 退出 edit菜单的子项 撤销 剪切 复制 粘贴 删除 查找 查找下一个 替换 转到 全选 时间/日期 + //快捷菜单右键设置 撤销 恢复 剪切 复制 粘贴 删除 全选 + //Format菜单的子项 自动换行 字体 + //View菜单的子项 缩放 状态栏 显示行号 Help菜单的子项 查看帮助 关于记事本 + + + //鼠标右键弹窗快捷菜单 + private JPopupMenu rightMenu; + //鼠标右键子菜单 + private JMenuItem r_undo,r_redo,r_cut,r_copy,r_stick,r_delete, + r_selectAll; + + + //撤销 + private UndoManager undoMgr = new UndoManager(); + + + //判断文档保存状态 + private int flag=0;//1:新建 2:修改过 3:保存过的 + //当前文件路径 + private String dirPath = null; + //当前文件名 + private String fileName = null; + + + //文本行的行数 列数 字数 + private int row=1,col=1; + private int length = 0; + + //字体 字体大小 字体样式 下拉框 + private JFrame fontFrame; + private JPanel pCom_all,pCom;//布局面板 放置下拉框的面板 取消 + private JComboBox jcbFont, jcbFont_size, jcbFont_style; + private String fontFont[] = { "SERIF", "SANS_SERIF", "MONOSPACED", "DIALOG", + "DIALOG_INPUT" }; + private String fontStyle[] = { "PLAIN", "BOLD", "ITALIC", "BOLD+ITALIC" }; + private String fontSize[] = { "10", "12", "14", "16", "18", "20", "22", + "24", "26", "48", "72" }; + private JLabel Test_label;//示例标签 + private JButton okButton= new JButton("确定"),cancelButton=new JButton("取消"); + private Font editAreaFont,testFont;//编辑区字体 示例字体 + private String fofont="Serif",fontstyleTemp; + private int fostyle=Font.PLAIN,fosize=17; + //字体/背景颜色 + private JColorChooser jColorChooser = null; + private Color color = Color.BLACK; + + + //查看帮助网址 + private String webSite = "https://cn.bing.com/search?q=%E8%8E%B7%E5%8F%96%E6%9C%89%E5%85%B3+windows&%E4%B8%AD%E7%9A%84%E8%AE%B0%E4%BA%8B%E6%9C%AC%E7%9A%84%E5%B8%AE%E5%8A%A9&filters=guid:%224466414-zh-hans-dia%22%20lang:%22zh-hans%22&form=T00032&ocid=HelpPane-BingIA"; + + + //时间/日期 + private GregorianCalendar c=new GregorianCalendar(); + private int hour=c.get(Calendar.HOUR_OF_DAY); + private int min=c.get(Calendar.MINUTE); + private int second=c.get(Calendar.SECOND); + private int year = c.get(Calendar.YEAR); + private int month = c.get(Calendar.MONTH); + private int day = c.get(Calendar.DAY_OF_MONTH); + + +/*程序开始*/ + public static void main(String args[]){ + try //此处的try-catch语句为借鉴以生成记事本的UI风格 + { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException + | UnsupportedLookAndFeelException e) { + e.printStackTrace(); + }; + EventQueue.invokeLater( + new Runnable() { + public void run() { + try { + Notepad notepad = new Notepad(); + + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + + }//查看帮助窗口网址跳转 + public static void OpenBroswer(String webSite) throws URISyntaxException,IOException { + Desktop desktop = Desktop.getDesktop(); + if (Desktop.isDesktopSupported() && desktop.isSupported(Desktop.Action.BROWSE)) {//测试此类是否在当前平台上得到支持&测试当前平台是否支持操作 + URI uri = new URI(webSite); + desktop.browse(uri);//启动默认浏览器以显示URI(标识某一互联网资源名称的字符串) + } + +} + +/*构造函数*/ + public Notepad() { + editArea = new JTextArea();//设个文本编辑区 + editAreaFont = new Font(fofont,fostyle,fosize); + editArea.setFont(editAreaFont); + MenuBar();//菜单 + InitListener();//处理事件 + + setSize(800,600);//设置窗口大小 + setTitle("文本编辑器"); + setIconImage(new ImageIcon("C:\\Users\\frank\\git\\java2022spring\\src\\notepad.jpg").getImage());//老师自己改一下路径相信你! + setJMenuBar(menuBar);//在窗口中放置菜单条 + + panel = new JPanel(); + panel.setBorder(new EmptyBorder(5,5,5,5)); + panel.setLayout(new BorderLayout(0,0)); + setContentPane(panel); + scrollPane = new JScrollPane(editArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + panel.add(scrollPane,BorderLayout.CENTER);//添加滚动面板到面板 + + statusBarState = new JToolBar();//声明状态栏 + + panel.add(statusBarState,BorderLayout.SOUTH);//添加状态栏到面板 + + editArea.setComponentPopupMenu(rightMenu);//添加鼠标右键快捷键 + + + //文件更改时的判断方法 + isChanged(); + MainFrameWidowListener(); + + setVisible(true); + setLocationRelativeTo(null); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + //状态栏------------------------------------------------------------------------------------------------------------------------- + statusBarState.setSize(editArea.getSize().width,10); + statusBarState.setBackground(Color.LIGHT_GRAY); + + //显示行数列数 + Line_label= new JLabel(" 第 "+row+" 行,第 "+(col+1)+" 列 "); + statusBarState.add(Line_label); + statusBarState.addSeparator(); + editArea.addCaretListener(new CaretListener() { + @Override + public void caretUpdate(CaretEvent e) { + JTextArea editArea2 = (JTextArea)e.getSource(); + try { + int caretpos = editArea.getCaretPosition(); + row=editArea2.getLineOfOffset(caretpos); + col=caretpos-editArea.getLineStartOffset(row); + row+=1; + Line_label.setText("第 "+row+" 行,第 "+(col+1)+" 列 "); + } + catch (Exception ex) {} + }}); + + //显示字数 + ForCount_label = new JLabel("一共"+length+" 字 "); + statusBarState.add(ForCount_label); + statusBarState.addSeparator(); + editArea.addCaretListener(new CaretListener() { + @Override + public void caretUpdate(CaretEvent e) { + try { + length = Notepad.this.editArea.getText().toString().length(); + ForCount_label.setText("一共"+length+" 字 "); + } + catch (Exception ex) {} + }}); + + //显示时间 + time_label = new JLabel("当前系统时间:"+year+"年"+(month+1)+"月"+day+"日"+""+ hour + ":" + min + ":" + second); + statusBarState.add(time_label); + statusBarState.setVisible(false); + statusBarState.setFloatable(false); + java2022spring.Clock clock=new java2022spring.Clock(); + clock.start(); + + } + +//菜单----------------------------------------------------------------------------------------------------------------------------------------------- + public void MenuBar() { + //菜单栏 + menuBar = new JMenuBar(); + + //菜单:文件File + m_File = new JMenu("文件(F)"); + m_File.setMnemonic('F');//快捷键 alt+f 打开 + iF_new = new JMenuItem("新建(N)",'N'); + iF_new.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));//快捷键ctrl+N + iF_open = new JMenuItem("打开(O)",'O'); + iF_open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK)); + iF_save = new JMenuItem("保存(S)"); + iF_save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK)); + iF_saveas = new JMenuItem("另存为(A)"); + iF_saveas.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.ALT_MASK |InputEvent.SHIFT_MASK, true));//CTRL+SHIFT+S + iF_exit = new JMenuItem("退出(X)",'X'); + iF_page = new JMenuItem("页面布置(U)"); + + + //添加文件菜单项到菜单 + m_File.add(iF_new); + m_File.add(iF_open); + m_File.add(iF_save); + m_File.add(iF_saveas); + m_File.addSeparator();//分割线 + m_File.add(iF_page); + m_File.addSeparator(); + m_File.add(iF_exit); + + + //菜单:编辑Edit + m_Edit = new JMenu("编辑(E)"); + m_Edit.setMnemonic('E');//alt+e + + iE_undo = new JMenuItem("撤销(U)"); + iE_undo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_MASK)); + + IE_redo = new JMenuItem("恢复(R)"); + IE_redo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.CTRL_MASK)); + + iE_cut = new JMenuItem("剪切(T)",'T'); + iE_cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK)); + + iE_copy = new JMenuItem("复制(C)",'C'); + iE_copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK)); + + iE_stick = new JMenuItem("粘贴(P)",'P'); + iE_stick.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK)); + + iE_delete = new JMenuItem("删除(L)"); + iE_delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.CTRL_MASK)); + + iE_findReplace = new JMenuItem("查找与替换(F)"); + iE_findReplace.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,InputEvent.CTRL_MASK)); + + iE_turnto = new JMenuItem("转到(G)"); + iE_turnto.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G,InputEvent.CTRL_MASK)); + + iE_selectall = new JMenuItem("全选(A)"); + iE_selectall.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,InputEvent.CTRL_MASK)); + + iE_timeItem = new JMenuItem("时间/日期(D)"); + iE_timeItem.setAccelerator(KeyStroke.getKeyStroke("F5")); + + m_Edit.add(iE_undo); + m_Edit.add(IE_redo); + m_Edit.addSeparator(); + m_Edit.add(iE_cut); + m_Edit.add(iE_copy); + m_Edit.add(iE_stick); + m_Edit.add(iE_delete); + m_Edit.addSeparator(); + m_Edit.add(iE_findReplace); + m_Edit.add(iE_turnto); + m_Edit.addSeparator(); + m_Edit.add(iE_selectall); + m_Edit.add(iE_timeItem); + + + //右键弹出快捷菜单 + rightMenu = new JPopupMenu(); + r_undo = new JMenuItem("撤销"); + r_redo = new JMenuItem("恢复"); + r_cut = new JMenuItem("剪切"); + r_copy = new JMenuItem("复制"); + r_stick = new JMenuItem("粘贴"); + r_delete = new JMenuItem("删除"); + rightMenu.add(r_undo); + rightMenu.add(r_redo); + rightMenu.add(r_cut); + rightMenu.add(r_copy); + rightMenu.add(r_stick); + rightMenu.add(r_delete); + + + //菜单:格式Format + m_Format = new JMenu("格式(O)"); + m_Format.setMnemonic('o');//alt+o + iFt_wrap = new JCheckBoxMenuItem("自动换行(W)"); + iFt_font = new JMenuItem("字体(F)"); + iFt_background = new JMenuItem("背景颜色"); + iFt_fontcolor = new JMenuItem("字体颜色"); + m_Format.add(iFt_wrap); + m_Format.add(iFt_font); + m_Format.add(iFt_fontcolor); + m_Format.add(iFt_background); + + //菜单:查看View + m_View = new JMenu("查看(V)"); + m_View.setMnemonic('v');//快捷键alt+v + //iV_zoomBox = new JComboBox(); + iV_statusBar = new JCheckBoxMenuItem("状态栏(S)"); + iV_lineNumber = new JCheckBoxMenuItem("显示行号(N)"); + iV_statistics = new JMenuItem("统计"); + m_View.add(iV_statusBar); + m_View.add(iV_lineNumber); + m_View.add(iV_statistics); + + + //菜单:帮助Help + m_Help = new JMenu("帮助(H)"); + m_Help.setMnemonic('H');//快捷键 alt+h + iH_viewHelp = new JMenuItem("查看帮助(H)"); + iH_about = new JMenuItem("关于记事本(A)"); + m_Help.add(iH_viewHelp); + m_Help.addSeparator(); + m_Help.add(iH_about); + + //添加菜单 + menuBar.add(m_File); + menuBar.add(m_Edit); + menuBar.add(m_Format); + menuBar.add(m_View); + menuBar.add(m_Help); + } +//处理事件------------------------------------------------------------------------------------------------------------------------- + //对菜单子项统一设置监视器 + public void InitListener() { + //文件 + iF_new.addActionListener(this); + iF_open.addActionListener(this); + iF_save.addActionListener(this); + iF_saveas.addActionListener(this); + iF_exit.addActionListener(this); + iF_page.addActionListener(this); + + //编辑 + iE_undo.addActionListener(this); + IE_redo.addActionListener(this); + iE_cut.addActionListener(this); + iE_copy.addActionListener(this); + iE_stick.addActionListener(this); + iE_delete.addActionListener(this); + //getDocument()为文本框中的文本注册监视器 + editArea.getDocument().addUndoableEditListener(undoMgr); + iE_findReplace.addActionListener(this); + iE_turnto.addActionListener(this); + iE_selectall.addActionListener(this); + iE_timeItem.addActionListener(this); + + + r_undo.addActionListener(this); + r_redo.addActionListener(this); + r_cut.addActionListener(this); + r_copy.addActionListener(this); + r_stick.addActionListener(this); + r_delete.addActionListener(this); + + //格式 + iFt_wrap.addActionListener(this); + iFt_font.addActionListener(this); + iFt_fontcolor.addActionListener(this); + iFt_background.addActionListener(this); + okButton.addActionListener(this); + cancelButton.addActionListener(this); + + //查看 + iV_statusBar.addActionListener(this); + iV_lineNumber.addActionListener(this); + iV_statistics.addActionListener(this); + + //帮助 + iH_viewHelp.addActionListener(this); + iH_about.addActionListener(this); +} + +//文件------------------------------------------------------------------------------------------------------------------------- + + //判断文件是否被修改 + private void isChanged() { + editArea.addKeyListener(new KeyAdapter() { + @Override + public void keyTyped(KeyEvent e) {//按回车、空格键会有反应 + Character c = e.getKeyChar();//返回与此事件的键相关联的字符 + if(c!=null&&!editArea.getText().toString().equals("")) { + flag=2;//文件被修改过了 + } + } + }); + } + + //新建的或保存过的退出有三个选择 + private void MainFrameWidowListener() { + + this.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + if(flag==2 && dirPath==null) { + //刚启动记事本为0,刚新建文档为1 修改了文件且之前文件不存在,路径为零 + int result = JOptionPane.showConfirmDialog(Notepad.this,"你想将更改保存到无标题吗?", "记事本", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); + if(result==JOptionPane.OK_OPTION) {//保存 + try { + Notepad.this.saveasFile(); + } catch (IOException e1) { + e1.printStackTrace(); + } + }else if(result==JOptionPane.NO_OPTION) {//不保存 + System.exit(0); + Notepad.this.setDefaultCloseOperation(EXIT_ON_CLOSE); + }else { + Notepad.this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + } + }else if(flag==2&& dirPath!=null) { + //修改了文件且文件本来就存在 路径不为0 + int result =JOptionPane.showConfirmDialog(Notepad.this, "你想将更改保存到"+dirPath+"吗?", "记事本", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); + if(result==JOptionPane.OK_OPTION) { + try { + Notepad.this.saveFile(); + } catch (IOException e1) { + e1.printStackTrace(); + } + }else if(result==JOptionPane.NO_OPTION) { + System.exit(0); + Notepad.this.setDefaultCloseOperation(EXIT_ON_CLOSE); + }else { + Notepad.this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + } + } + else {//没有修改文件 + int result =JOptionPane.showConfirmDialog(Notepad.this,"确定关闭?", "系统提示", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE); + if(result==JOptionPane.OK_OPTION){//确定 + System.exit(0); + Notepad.this.setDefaultCloseOperation(EXIT_ON_CLOSE); + }else { + Notepad.this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + } + } + } + }); + } + + //另存为 + private void saveasFile() throws IOException{ + JFileChooser saveasDia = new JFileChooser();//选择文件 + int result = saveasDia.showSaveDialog(this); + + if(result==JFileChooser.APPROVE_OPTION) {//取得选择的文件 + File file =saveasDia.getSelectedFile(); + BufferedWriter bWriter = null; + + if(file==null||file.getName().equals("")) { + JOptionPane.showMessageDialog(this, "不合法的文件名","不合法的文件名",JOptionPane.ERROR_MESSAGE); + } + + else if(file.exists()) { + int i = JOptionPane.showConfirmDialog(null, "该文件已存在,是否覆盖原文件","确认",JOptionPane.YES_NO_OPTION); + if(i==JOptionPane.YES_OPTION) { + saveFile(); + } + else { + JOptionPane.showConfirmDialog(Notepad.this,"保存失败","确认",JOptionPane.YES_NO_CANCEL_OPTION); + } + } + try { + bWriter=new BufferedWriter(new FileWriter(file)); + bWriter.write(editArea.getText()); + fileName=file.getName(); + dirPath=file.getAbsolutePath(); + bWriter.flush(); + this.flag=3; + this.setTitle(dirPath); + }catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException("文件保存失败!"); + }finally { + try { + if(bWriter!=null)bWriter.close(); + } catch (IOException e) + { + e.printStackTrace();//在命令行打印异常信息在程序中出错的位置及原因。 + + }}}} + + //保存 + private void saveFile() throws IOException { + if(this.dirPath==null){ + this.saveasFile(); + if(this.dirPath==null){ + return; + } + } + FileWriter fw=null; + //保存 + try { + fw=new FileWriter(new File(dirPath)); + fw.write(editArea.getText()); + fw.flush(); + flag=3; + this.setTitle(this.dirPath); + } catch (IOException e1) { + e1.printStackTrace(); + }finally{ + try { + if(fw!=null) fw.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + }} + + //新建 + private void newFile() throws IOException { + if(flag==0||flag==1) {//刚启动记事本为0,刚新建文档为1 + return; + }else if(flag==2&&this.dirPath==null){//修改后的文件为2 + // 条件0、1下修改后 + int result=JOptionPane.showConfirmDialog(Notepad.this,"你想将更改保存到 无标题 吗?", "记事本", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); + if(result == JOptionPane.OK_OPTION){ + this.saveasFile();//另存为 + }else if(result == JOptionPane.NO_OPTION) { + this.editArea.setText(""); + this.setTitle("无标题"); + flag=1; + }return; + }else if(flag==2&&this.dirPath!=null) { + //所打开的文件路径不为零并被修改后 + int result = JOptionPane.showConfirmDialog(Notepad.this, "你想将更改保存到"+this.dirPath+"?", "记事本", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); + if(result == JOptionPane.OK_OPTION) { + this.saveFile();//直接保存 + }else if(result==JOptionPane.NO_OPTION) { + this.editArea.setText(""); + this.setTitle("无标题"); + flag=1; + } + }else if(flag ==3) { + this.editArea.setText(""); + flag=1; + this.setTitle("无标题"); + } +} + + //退出 + private void exit() throws IOException { + if(flag==2 && dirPath==null) { + //刚启动记事本为0,刚新建文档为1 修改了文件且之前文件不存在,路径为零 + int result = JOptionPane.showConfirmDialog(Notepad.this,"是否将更改保存到无标题?", "记事本", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); + if(result==JOptionPane.OK_OPTION) { + Notepad.this.saveasFile(); + }else if(result==JOptionPane.NO_OPTION) { + Notepad.this.dispose(); + Notepad.this.setDefaultCloseOperation(EXIT_ON_CLOSE); + } + }else if(flag==2&& dirPath!=null) { + //修改了文件且文件本来就存在 路径不为0 + int result =JOptionPane.showConfirmDialog(Notepad.this, "是否将更改保存到"+dirPath+"?", "记事本", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); + if(result==JOptionPane.OK_OPTION) { + Notepad.this.saveFile(); + }else if(result==JOptionPane.NO_OPTION) { + Notepad.this.dispose(); + Notepad.this.setDefaultCloseOperation(EXIT_ON_CLOSE); + } + else { //没有修改 + int result1 =JOptionPane.showConfirmDialog(Notepad.this,"确定关闭?", "系统提示", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE); + if(result1 ==JOptionPane.OK_OPTION){ + Notepad.this.dispose(); + Notepad.this.setDefaultCloseOperation(EXIT_ON_CLOSE); + }else { + Notepad.this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + } + + }}} + + //打开文件 + private void openFile() throws IOException { + if(flag==2&&this.dirPath==null) { + //刚启动记事本为0,刚新建文档为1 修改后 + int result = JOptionPane.showConfirmDialog(Notepad.this, "是否将更改保存到无标题?", "记事本", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); + if(result==JOptionPane.OK_OPTION) { + this.saveasFile(); + } + }else if (flag==2&& this.dirPath!=null) { + //打开的文件2,保存的文件3 修改后 + int result=JOptionPane.showConfirmDialog(Notepad.this, "是否将更改保存到"+this.dirPath+"?", "记事本", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); + if(result==JOptionPane.OK_OPTION){ + this.saveFile(); + } + }//打开文件选择框 + JFileChooser chooser=new JFileChooser(); + //选择文件 + int result=chooser.showOpenDialog(this); + if(result==JFileChooser.APPROVE_OPTION) { + //取得选择的文件 + File file=chooser.getSelectedFile(); + //打开已存在的文件,提前存文件名 + fileName=file.getName(); + //存文件路径 + dirPath=file.getAbsolutePath(); + flag=3; + this.setTitle(this.dirPath); + BufferedReader bReader=null; + try { + //建立字符流 + InputStreamReader inputStreamReader=new InputStreamReader(new FileInputStream(file),"GBK"); + bReader=new BufferedReader(inputStreamReader); + //读取内容 + StringBuffer sBuffer=new StringBuffer(); + String line=null; + while((line=bReader.readLine())!=null) { + sBuffer.append(line+"\r\n"); + }//显示在文本框 + editArea.setText(sBuffer.toString()); + }catch(FileNotFoundException e1) { + e1.printStackTrace(); + }catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException("文件读取失败!"); + }finally { + try { + if(bReader!=null)bReader.close(); + }catch (Exception e) { + e.printStackTrace(); + }}}} + + //页面布置 参考 https://blog.csdn.net/qq_15722517/article/details/91038301?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165397119816781685387434%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=165397119816781685387434&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-1-91038301-null-null.142^v11^pc_search_result_control_group,157^v12^new_style&utm_term=printerjob&spm=1018.2226.3001.4187 + private void page() { + PageFormat pFormat=new PageFormat(); + PrinterJob.getPrinterJob().pageDialog(pFormat); + } + +//编辑--------------------------------------------------------------------------------------- + //查找与替换 + private void FindReplaceall() { + //查找与替换 + final JDialog findDialog = new JDialog(Notepad.this,"查找",true);//查找对话框 + Container container = findDialog.getContentPane();//布局管理器 + JLabel searchLabel = new JLabel("查找内容(N)"); + JLabel replaceLabel = new JLabel("替换为(P)"); + final JTextField findText = new JTextField(16); + final JTextField replaceText = new JTextField(16); + final JCheckBox matchCase = new JCheckBox("区分大小写"); + final JRadioButton upButton = new JRadioButton("向上(U)"); + final JRadioButton downButton = new JRadioButton("向下(D)"); + JButton searchNextButton = new JButton("查找下一个(F)"); + JButton replaceButton = new JButton("替换(R)"); + JButton S_cancelButton = new JButton("取消"); + final JButton replaceAllButton = new JButton("全部替换(A)"); + + container.setLayout(new FlowLayout(FlowLayout.LEFT));//设置 + downButton.setSelected(true);//down默认选中 + searchNextButton.setPreferredSize(new Dimension(117,27)); + replaceButton.setPreferredSize(new Dimension(117,27)); + replaceAllButton.setPreferredSize(new Dimension(117,27)); + + //替换全部 + replaceAllButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + int a=0;//要替换的文本开头 + int b=0;//要替换的文本结尾 + int replaceCount =0;//替换多少处文本 + editArea.setCaretPosition(0); + + if(findText.getText().length()==0) { + JOptionPane.showMessageDialog(findDialog, "请填写查找内容!","提示",JOptionPane.WARNING_MESSAGE); + findText.requestFocus(true);//焦点 + return; + } + while(a>-1)//当没有找到匹配内容时,结束循环 + { + int fStartPosition = editArea.getCaretPosition();//获取光标位置 + String s1,s2; + s1=editArea.getText();//获取文本区文本 + s2=editArea.getText();//获取查找内容框中的文本 + + if(editArea.getSelectedText()==null)//文本区选取文本为空 + { //从开头开始找 + a=s1.indexOf(s2,fStartPosition);//从fstartposition开始向后查找s2第一个出现的位置 + } + else { + //文本区选取文本不为空时 + a=s1.indexOf(s2,fStartPosition-findText.getText().length()+1); + //返回s2字符串最开始出现的位置,在s1中的指定位置fStartPosition-findText.getText().length()+1从前向后搜索 + } + if(a>-1) { + editArea.setCaretPosition(a); + b=findText.getText().length(); + editArea.select(a, a+b);//选中文本区中的指定区域 + } + else { + if(replaceCount==0) { + JOptionPane.showMessageDialog(findDialog, "查不到您查找的内容!","记事本",JOptionPane.INFORMATION_MESSAGE); + } + else { + JOptionPane.showMessageDialog(findDialog, "成功替换"+replaceCount+"个匹配内容","替换成功",JOptionPane.INFORMATION_MESSAGE); + } + } + if(replaceText.getText().length()==0 && editArea.getSelectedText()!=null) + { + editArea.replaceSelection("");//选中文本区中的指定区域 用空白代替 + replaceCount++; + } + if(replaceText.getText().length()>0&&editArea.getSelectedText()!=null) { + editArea.replaceSelection(replaceText.getText()); + replaceCount++; + } + } + + } + }); + //查找下一个 + searchNextButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + int a=0,b=0; + int fStartPosition = editArea.getCaretPosition();//获取光标位置 + String s1,s2,s3,s4,sA,sB; + s1=editArea.getText(); + s2=s1.toLowerCase();//把字符串全部转换成小写,非字母的不变 + s3=findText.getText(); + s4=s3.toLowerCase(); + //区分大小写 + if(matchCase.isSelected()) {//"区分大小写"被选中 + sA=s1; + sB=s2; + } + else { + sA=s2; + sB=s4; + } + if(upButton.isSelected()) { + if(editArea.getSelectedText()==null) { + a=sA.lastIndexOf(sB,fStartPosition-1); + //第fStartPosition-1位置开始向前查sB第一个出现的位置 + }else { + a=sA.lastIndexOf(sB,fStartPosition-findText.getText().length()); + }} + else if(downButton.isSelected()) { + if(editArea.getSelectedText()==null) { + a=sA.indexOf(sB,fStartPosition); + }else { + a=sA.indexOf(sB,fStartPosition-findText.getText().length());//字符串最先出现的位置 从前向后搜索 + } + } + if (a>-1) { + editArea.setCaretPosition(a); + b=findText.getText().length(); + editArea.select(a, a+b); + } + else { + JOptionPane.showMessageDialog(null, "找不到您查找的内容!","记事本",JOptionPane.INFORMATION_MESSAGE); + } + } + }); + + //替换 + replaceButton.addActionListener(new ActionListener() { + + public void actionPerformed(ActionEvent e) { + if(replaceText.getText().length()==0 && editArea.getSelectedText()!=null) + editArea.replaceSelection("");//替换成空白 + if(replaceText.getText().length()>0 && editArea.getSelectedText()!=null) + editArea.replaceSelection(replaceText.getText()); + } + }); + + //取消 + S_cancelButton.setPreferredSize(new Dimension(110, 22)); + S_cancelButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + findDialog.dispose(); //退出窗口 + } + }); + + //创建查找对话框 + JPanel buttonPanel = new JPanel(); + JPanel centerPanel = new JPanel(); + JPanel topPanel = new JPanel(); + JPanel searchPanel = new JPanel(); + + searchPanel.setLayout(new GridLayout(2,1)); + searchPanel.add(searchNextButton); + searchPanel.add(replaceButton); + + topPanel.add(searchLabel); + topPanel.add(findText); + topPanel.add(searchPanel); + + centerPanel.add(replaceLabel); + centerPanel.add(replaceText); + centerPanel.add(replaceAllButton); + + buttonPanel.add(matchCase); + buttonPanel.add(upButton); + buttonPanel.add(downButton); + buttonPanel.add(S_cancelButton); + + container.add(topPanel); + container.add(centerPanel); + container.add(buttonPanel); + + findDialog.setSize(400,200); + findDialog.setResizable(false); + findDialog.setLocation(240,290); + findDialog.setVisible(true); + } + +//转到------------------------------------------------------------------------------------------------------------------------- + private void turnTo() { + final JDialog gotoDialog = new JDialog(this,"转到下列行"); + JLabel gotoLabel = new JLabel("行数(L)"); + final JTextField linenum = new JTextField(5);//构造一个新的空的 TextField与指定的行数 + linenum.setText("1"); + linenum.selectAll(); + + JButton okButton = new JButton("确定"); + okButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + int totalLine = editArea.getLineCount();//文本编辑区包含的行数 + int [] lineNumber = new int[totalLine+1]; + String string=editArea.getText();//文本区域里的字符串 + int position =0,i=0; + + while(true) { + position=string.indexOf('\12',position); + if(position==-1) + break; + lineNumber[i++]=position++; + }//一行结束 + + int targetLine=1; + try { + targetLine=Integer.parseInt(linenum.getText()); + }catch(NumberFormatException e1) { + JOptionPane.showMessageDialog(null, "请输入行数!","提示",JOptionPane.WARNING_MESSAGE); + linenum.requestFocus(true); + return; + } + + if(targetLine<2||targetLine>=totalLine) { + if(targetLine<2) + editArea.setCaretPosition(0);//将滚动条自动拉到JTextArea最顶端 + else { + editArea.setCaretPosition(string.length());//将滚动条拉到文本结尾 + } + }else {//targetLine [2,targetLine) + editArea.setCaretPosition(lineNumber[targetLine-2]+1); + } + gotoDialog.dispose(); + + } + }); + + Container turnToContainer = gotoDialog.getContentPane();//获得gotoDialog的内容面板,再对其加入组件 + turnToContainer.setLayout(new FlowLayout()); + turnToContainer.add(gotoLabel); + turnToContainer.add(linenum); + turnToContainer.add(okButton); + turnToContainer.add(cancelButton); + + gotoDialog.setSize(200,100); + gotoDialog.setResizable(false); + gotoDialog.setLocation(300,280); + gotoDialog.setVisible(true); + } + + +//格式------------------------------------------------------------------------------------------------------------------------- + //背景颜色 + private void BackgroundColor() { + jColorChooser = new JColorChooser(); + JOptionPane.showMessageDialog(null, jColorChooser,"选择背景颜色",-1); + color = jColorChooser.getColor(); + editArea.setBackground(color); + } + //字体颜色 + private void FontColor() { + jColorChooser=new JColorChooser(); + JOptionPane.showMessageDialog(null, jColorChooser,"选择字体颜色",-1); + color=jColorChooser.getColor(); + editArea.setForeground(color); + } + //文字选择框--------------------------------------------------------------------------------------------------------------------------- + private void fontFrame() { + fontFrame = new JFrame("文字"); + pCom_all= new JPanel(new GridLayout(2,1));//设置为两行一列 + pCom = new JPanel(); + jcbFont = new JComboBox(fontFont); + jcbFont.setBorder(BorderFactory.createTitledBorder("粗细"));//设置边框 + jcbFont_style=new JComboBox(fontStyle); + jcbFont_style.setBorder(BorderFactory.createTitledBorder("样式")); + jcbFont_size=new JComboBox(fontSize); + jcbFont_size.setBorder(BorderFactory.createTitledBorder("大小")); + Test_label =new JLabel("示例:Welcome to use the notepad.",JLabel.CENTER); + pCom.add(jcbFont); + pCom.add(jcbFont_style); + pCom.add(jcbFont_size); + pCom_all.add(pCom); + pCom_all.add(Test_label); + okButton= new JButton("确定"); + cancelButton = new JButton("取消"); + fontFrame.setLayout(new FlowLayout()); + fontFrame.add(pCom_all); + fontFrame.add(okButton); + fontFrame.add(cancelButton); + fontFrame.setBounds(200,300,360,300); + fontFrame.setVisible(true); + + //文字对话框 + fontFrame.addWindowFocusListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + fontFrame.setVisible(false); + } + }); + //粗细下拉框 + jcbFont.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + if(e.getStateChange() == ItemEvent.SELECTED) { + jcbFont =(JComboBox)e.getSource(); + fofont =(String)jcbFont.getSelectedItem(); + testFont=new Font(fofont,fostyle,fosize); + Test_label.setFont(testFont); + } + } + }); + //样式下拉框 + jcbFont_style.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + if(e.getStateChange()==ItemEvent.SELECTED) { + jcbFont_style=(JComboBox)e.getSource(); + fontstyleTemp=(String)jcbFont_style.getSelectedItem(); + if ("PLAIN".equals(fontstyleTemp)) + fostyle = Font.PLAIN; + else if ("BOLD".equals(fontstyleTemp)) + fostyle = Font.BOLD; + else if ("ITALIC".equals(fontstyleTemp)) + fostyle = Font.ITALIC; + else if ("BOLD+ITALIC".equals(fontstyleTemp)) + fostyle = Font.BOLD + Font.ITALIC; + testFont = new Font(fofont, fostyle, fosize); + Test_label.setFont(testFont); + } + } + }); + //大小下拉框 + jcbFont_size.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + if(e.getStateChange() == ItemEvent.SELECTED) { + jcbFont_size=(JComboBox)e.getSource(); + fosize=Integer.parseInt((String)jcbFont_size.getSelectedItem()); + testFont=new Font(fofont,fostyle,fosize); + Test_label.setFont(testFont); + } + } + }); + + //确定 + okButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + editArea.setFont(testFont); + fontFrame.setVisible(false); + } + }); + + //取消 + cancelButton.addActionListener(new ActionListener() { +public void actionPerformed(ActionEvent e) { + fontFrame.setVisible(false); + } + }); + } + + +//查看------------------------------------------------------------------------------------------------------------------------- + //统计 + private void statistics(){ + String a = editArea.getText();//获取用户输入的文本 + int Chinese = 0 ,Majuscule=0, Minuscule=0,Number=0,other=0,Sum=0 ; + for(int i=0;i{ + this.dispose(); + }); + } + } \ No newline at end of file