我做了一个记事本程序。问题是它不保存为 .txt 格式,它保存为没有格式的文件。但它可以打开 .txt 文件。我该如何解决?这是我的工作。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
import java.io.*;
public class NotePad extends JFrame {
private JTextArea noteArea;
public static void main(String[] args) {
NotePad p = new NotePad();
p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p.setSize(500,300);
p.setVisible(true);
}
public NotePad() {
super("Java Notepad");
setLayout(new BorderLayout());
noteArea = new JTextArea("",20,20);
noteArea.setWrapStyleWord(true);
noteArea.setLineWrap(true);
Font font = new Font("sanserif", Font.BOLD,14);
noteArea.setFont(font);
JScrollPane scroller = new JScrollPane(noteArea);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
add(scroller,BorderLayout.CENTER);
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem openMenu = new JMenuItem("Open");
openMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser openFile = new JFileChooser();
openFile.showOpenDialog(new NotePad());
loadFile(openFile.getSelectedFile());
}
});
JMenuItem saveMenu = new JMenuItem("Save");
saveMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser saveFile = new JFileChooser();
saveFile.showSaveDialog(new NotePad());
fileSaved(saveFile.getSelectedFile());
}
});
JMenuItem exitMenu = new JMenuItem("Close");
exitMenu.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
fileMenu.add(openMenu);
fileMenu.add(saveMenu);
fileMenu.add(exitMenu);
menuBar.add(fileMenu);
this.setJMenuBar(menuBar);
}
public void loadFile(File file) {
noteArea.setText("");
try {
BufferedReader read = new BufferedReader(new FileReader(file));
String line = null;
while((line =read.readLine())!=null) {
noteArea.append(line +"\n");
}
read.close();
}
catch (Exception e) {
System.out.println("Error " + e.toString());
}
}
public void fileSaved(File file) {
try {
PrintWriter writer = new PrintWriter(file);
String[] lines = noteArea.getText().split("\\n");
for (String ) {
writer.println(words);
}
writer.close();
} catch (Exception e) {
System.out.println("Error " + e.toString());
}
}
}
顺便说一句,由于没有根据网站解释场景,我无法发布我的问题。所以在那里。谢谢您的帮助