import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.text.JTextComponent;
import javax.swing.text.html.HTMLEditorKit;
public class LoadSaveAction {
public static void main(String args[]) {
final String filename = "Test.html";
JFrame frame = new JFrame("Loading/Saving Example");
Container content = frame.getContentPane();
final JEditorPane editorPane = new JEditorPane();
JScrollPane scrollPane = new JScrollPane(editorPane);
content.add(scrollPane, BorderLayout.CENTER);
editorPane.setEditorKit(new HTMLEditorKit());
JPanel panel = new JPanel();
Action loadAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
doLoadCommand(editorPane, 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(editorPane, 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() {
public void actionPerformed(ActionEvent e) {
editorPane.setText("");
}
};
clearAction.putValue(Action.NAME, "Clear");
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();
}
}
|