save as .txt format
Posted
by
user1180492
on Stack Overflow
See other posts from Stack Overflow
or by user1180492
Published on 2012-08-30T03:21:41Z
Indexed on
2012/08/30
3:38 UTC
Read the original article
Hit count: 125
java
I made a NotePad program. The problem is it doesn't save in .txt format, It save as a file with no format. But it can open .txt files. How can i fix it? Here is my work.
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());
}
}
}
btw I can't post my question because of not explaning the scenario according to the site. So there. Thanks for the help
© Stack Overflow or respective owner