|
楼主 |
发表于 2020-7-2 16:00:01
|
显示全部楼层
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class NotepadJFrame extends JFrame {
JScrollPane jsp;
JTextArea jta;
boolean motified = false;
String currentFileName = null;
NotepadJFrame() {
setProp();
addComponent();
this.setVisible(true);
}
private void setProp() {
this.setSize(500, 400);
this.setLocation(200, 100);
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setTitle("我的记事本");
this.setJMenuBar(new NoteMenuBar(this));
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
close();
}
});
}
private void addComponent() {
jsp = new JScrollPane();
jta = new JTextArea();
jsp.getViewport().add(jta);
this.getContentPane().add(jsp, BorderLayout.CENTER);
jta.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
motified = true;
}
public void removeUpdate(DocumentEvent e) {
motified = true;
}
public void changedUpdate(DocumentEvent e) {
motified = true;
}
});
}
void close() {
if(motified) {
int rst = JOptionPane.showConfirmDialog(null, "是否要保存");
switch(rst){
case JOptionPane.YES_OPTION:
save();
break;
case JOptionPane.NO_OPTION: System.exit(0);
case JOptionPane.CANCEL_OPTION:
}
} else {
System.exit(0);
}
}
void open() {
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(null);
File f = jfc.getSelectedFile();
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String tmp;
StringBuffer all = new StringBuffer();
while(!(tmp = br.readLine()).trim().equals("")) {
all.append(tmp);
all.append("\n");
}
br.close();
fr.close();
this.jta.setText(all.toString());
}catch(IOException e) {
e.printStackTrace();
}
}
void save() {
try {
if(currentFileName==null) {
saveAsFile();
}
FileWriter fw = new FileWriter(this.currentFileName);
BufferedWriter bw = new BufferedWriter(fw);
String[] all = this.jta.getText().split("\n");
for(int i=0;i<all.length;i++) {
bw.write(all[i]);
bw.newLine();
}
bw.flush();
bw.close();
fw.close();
motified=false;
}catch(IOException e) {
e.printStackTrace();
}
}
void saveAsFile() {
JFileChooser chooser = new JFileChooser("c:/");
chooser.showSaveDialog(null);
this.currentFileName = chooser.getSelectedFile().getPath();
save();
}
void newFile() {
if(motified) {
int rst = JOptionPane.showConfirmDialog(null, "是否要保存");
switch(rst){
case JOptionPane.YES_OPTION:
save();
break;
case JOptionPane.NO_OPTION:
case JOptionPane.CANCEL_OPTION:
}
}
jta.setText("");
motified = false;
}
} |
|