I want to create a program more like a NotePad. When you type a text inside the JTextArea
and click Save as, the program will create a text file inside the workspace with the texts typed inside the JTextArea
. The problem is when I click save, the program can create a text file but the texts typed inside the textarea are not saved inside the created text file. The name of the text file is "Text"
. I used the getText()
method to get the texts inside the TextArea
.
This is the program:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
public class TextAreaWithMenus extends JFrame implements ActionListener {
JTextArea area;
JMenuBar menubar;
JMenu option;
JMenuItem menuitem;
File file;
FileWriter fwriter;
PrintWriter pwriter;
String order[] = {"Save as","Edit"};
public TextAreaWithMenus() {
setSize(new Dimension(500,500));
setDefaultCloseOperation(this.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setLayout(null);
area = new JTextArea();
menubar = new JMenuBar();
option = new JMenu("File");
for(String call : order) {
menuitem = new JMenuItem(call);
option.add(menuitem);
menuitem.addActionListener(this);
}
this.add(menubar);
menubar.setBounds(0,0,500,30);
menubar.add(option);
this.add(area);
area.setBounds(0,30,500,470);
area.setLineWrap(true);
area.setWrapStyleWord(true);
try{
file = new File("C://Users/LunaWorkspace/TestProject/src/Text");
fwriter = new FileWriter(file);
pwriter = new PrintWriter(fwriter,true);
}catch(Exception e) {}
setVisible(true);
}//END OF CONSTRUCTOR
public void save() {
try {
if(!file.exists()) {
try {
file.createNewFile();
pwriter.print(area.getText());
System.out.println(area.getText());
System.out.println("Saved complete");
}catch(Exception ef) {
ef.printStackTrace();
System.err.print("Cannot Create");
}
}else if(file.exists()) {
pwriter.print(area.getText());
System.out.println(area.getText());
System.out.println("Overwrite complete");
}
} catch(Exception exp) {
exp.printStackTrace();
System.err.println("Cannot Save");
}
}
public void actionPerformed(ActionEvent ac) {
String act = ac.getActionCommand();
if(act.equals("Save as")) {
save();
}else if(act.equals("Edit")) {}
}
public static void main (String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() { new TextAreaWithMenus();} });
}
}
you need to call flush as the save is being buffered. This works: