通过输入输出流实现仿记事本程序,能够实现新建、打开、保存、另存等基本功能
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class Main extends JFrame {
private JTextField t1;
private JTextArea ta1;
public Main() {
setTitle("记事本");
setSize(600, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p1 = new JPanel(new GridBagLayout());
//p1.setLayout(new BorderLayout());
GridBagConstraints g1 = new GridBagConstraints();
g1.insets = new Insets(10, 10, 10, 10);
JButton b1 = new JButton("新建");
JButton b2 = new JButton("打开");
JButton b3 = new JButton("保存");
JButton b4 = new JButton("另存");
JButton b5 = new JButton("退出");
t1 = new JTextField(20);
ta1 = new JTextArea(15, 40);
JScrollPane scrollPane = new JScrollPane(ta1);
g1.gridx = 0;
g1.gridy = 0;
p1.add(b1, g1);
g1.gridx = 1;
p1.add(b2, g1);
g1.gridx = 2;
p1.add(b3, g1);
g1.gridx = 3;
p1.add(b4, g1);
g1.gridx = 4;
p1.add(b5, g1);
g1.gridx = 0;
g1.gridy = 1;
g1.gridwidth = 5;
g1.fill = GridBagConstraints.HORIZONTAL;
p1.add(t1, g1);
g1.gridy = 2;
g1.fill = GridBagConstraints.BOTH;
p1.add(scrollPane, g1);
add(p1);
b1.addActionListener(e -> {
String fname = t1.getText().trim();
createFile(fname);
});
b2.addActionListener(e -> {
String fname = t1.getText().trim();
openFile(fname);
});
b3.addActionListener(e -> {
String fname = t1.getText().trim();
saveFile(fname);
});
b4.addActionListener(e -> {
String fname = JOptionPane.showInputDialog(this, "请输入另存为的文件名:");
saveFile(fname);
});
b5.addActionListener(e -> {
System.exit(0);
});
}
private void saveFile(String fname) {
if (fname == null || fname.isEmpty()) {
JOptionPane.showMessageDialog(this, "文件名为空,无法保存。");
return;
}
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(fname));
writer.write(ta1.getText());
writer.close();
JOptionPane.showMessageDialog(this, "文件已保存:" + fname);
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "保存文件时发生错误。");
}
}
private void openFile(String fileName) {
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
ta1.setText(content.toString());
reader.close();
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "打开文件时发生错误。");
}
}
private void createFile(String fileName) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.close();
JOptionPane.showMessageDialog(this, "文件已新建:" + fileName);
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "新建文件时发生错误。");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
Main app = new Main();
app.setVisible(true);
});
}
}