import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.io.FileReader;
import java.io.FileWriter;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;
public class LoadSave {
public static void main(String args[]) {
final String filename = "text.out";
JFrame frame = new JFrame("Loading/Saving Example");
Container content = frame.getContentPane();
final JTextField textField = new JTextField();
content.add(textField, BorderLayout.NORTH);
JPanel panel = new JPanel();
Action loadAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
doLoadCommand(textField, filename);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
loadAction.putValue(Action.NAME, "Load");
JButton loadButton = new JButton(loadAction);
panel.add(loadButton);
Action saveAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
doSaveCommand(textField, filename);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
saveAction.putValue(Action.NAME, "Save");
JButton saveButton = new JButton(saveAction);
panel.add(saveButton);
Action clearAction = new AbstractAction() {
{
putValue(Action.NAME, "Clear");
}
public void actionPerformed(ActionEvent e) {
textField.setText("");
}
};
JButton clearButton = new JButton(clearAction);
panel.add(clearButton);
content.add(panel, BorderLayout.SOUTH);
frame.setSize(250, 150);
frame.setVisible(true);
}
public static void doSaveCommand(JTextComponent textComponent, String filename) throws Exception {
FileWriter writer = null;
writer = new FileWriter(filename);
textComponent.write(writer);
writer.close();
}
public static void doLoadCommand(JTextComponent textComponent, String filename) throws Exception {
FileReader reader = null;
reader = new FileReader(filename);
textComponent.read(reader, filename);
reader.close();
}
}
|