JTextArea 记事本 内容变化 关闭前询问保存
主要代码:
?
//为记事本窗口添加监听事件 this.addWindowListener(new WindowAdapter(){ //windowClosing事件:当用户点击窗口右上角的关闭按钮时触发。public void windowClosing(WindowEvent arg0) {beforeClose();} }); /** * 窗口关闭前的处理 */ private void beforeClose(){ //如果文档内容发生了变化,则询问用户是否执行保存操作 if(jTextArea1.textIsChanged){ int opt = JOptionPane.showConfirmDialog(this,"文档内容已更改,是否保存?","确认对话框", JOptionPane.YES_NO_OPTION); if(opt == JOptionPane.YES_OPTION){ save(); } }}//文本域内容是否发生变化,外部可进行修改。public boolean textIsChanged = false;public Document doc = this.getDocument();//为文本域添加内容变动监听 doc.addDocumentListener(new DocumentListener(){@Overridepublic void changedUpdate(DocumentEvent e) {textIsChanged = true;}@Overridepublic void insertUpdate(DocumentEvent e) {textIsChanged = true;}@Overridepublic void removeUpdate(DocumentEvent e) {textIsChanged = true;} }); //打开文件 public void open(String defaultPath){ //弹出路径选择对话框 FileDialog saveDialog = new FileDialog(this, "打开文件",FileDialog.LOAD); if(defaultPath != null){ saveDialog.setDirectory(defaultPath); } saveDialog.setVisible(true); // 点击了【确定】按钮 if (saveDialog.getDirectory() != null && saveDialog.getFile() != null) { String path = saveDialog.getDirectory() + saveDialog.getFile(); String str[] = DocUtil.getCharDocContent(path); //记录打开的文件的路径,并设置为标题显示 this.filePath = str[0]; this.setTitle(str[0]); jTextArea1.setText(str[1]); this.status.setText("当前文件编码:"+str[2]); //新打开文档,textIsChanged重置为false jTextArea1.textIsChanged = false; } } /** * 保存 */ private void save() { //1、如果filePath为null,则弹出路径选择对话框 //2、如果filePath不为null,则更新原文件。 if(filePath == null){ //弹出路径选择对话框 FileDialog saveDialog = new FileDialog(this, "保存为",FileDialog.SAVE); saveDialog.setFile("未命名记事本.txt"); saveDialog.setVisible(true); // 点击了【确定】按钮 if (saveDialog.getDirectory() != null) { String path = saveDialog.getDirectory() + saveDialog.getFile(); String saveStr = jTextArea1.getText(); saveToFile(path,saveStr); //保存完成后,记录新创建的文件路径,并更新窗口标题 filePath = path; this.setTitle(filePath); //重置textIsChanged为false jTextArea1.textIsChanged = false; } }else{ String saveStr = jTextArea1.getText();saveToFile(this.filePath,saveStr);//重置textIsChanged为falsejTextArea1.textIsChanged = false; } }?
?