My applet works for the most part, but there is something askew with it. My code to notify the user that they need to enter a file name WORKS. But that is the end of it, as notifying the user they didn't enter text doesn't work, and neither does the writing of the text to a file.
It's as if my program breaks half way through. I was hopeful someone could just take a look at the code and let me know of anything obvious. I've been starring at it for 6 hours and don't trust my eyes anymore. The applet is pretty basic and straight forward. The user enters a file name of a txt file in the working directory, and whataver they then type in the test field is written to the file.
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.HeadlessException;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JOptionPane;
public class wwalker2 extends Applet {
Button write = new Button("WriteToFile");
Label label1 = new Label("Enter the file name:");
TextField text = new TextField(20);
Label label2 = new Label("Write your text:");
TextArea area = new TextArea(10, 20);
public void init() {
add(label1);
label1.setBackground(Color.orange);
add(text);
add(label2);
label2.setBackground(Color.orange);
add(area);
add(write, BorderLayout.CENTER);
write.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent z) {
WriteText writeText = new WriteText();
}
});
}
public class WriteText {
WriteText() {
try {
String str = text.getText();
if (str.equals("")) {
JOptionPane.showMessageDialog(null,
"It's not that smart... You have to enter the path and filename");
text.requestFocus();
} else {
File f = new File(str);
if (f.exists()) {
BufferedWriter out = new BufferedWriter(new FileWriter(f, true));
if (area.getText().equals("")) {
JOptionPane.showMessageDialog(null, "You haven't written anything yet!");
area.requestFocus();
} else {
out.write(area.getText());
if (f.canWrite()) {
JOptionPane.showMessageDialog(null, "There is now some text in " + str);
text.setText("");
area.setText("");
text.requestFocus();
} else {
JOptionPane.showMessageDialog(null, "There isn't any text in " + str);
}
out.close();
}
} else {
JOptionPane.showMessageDialog(null, "Error 404 File not found!");
text.setText("");
text.requestFocus();
}
}
} catch (HeadlessException | IOException x) {
}
}
}
}