SavedFrame.java
****************
A Frame that lets you draw circles with mouse clicks
//**************
import java.awt.*;
import java.awt.event.*;
import java.io.*;
/** A Frame that lets you draw circles with mouse clicks
* and then save the Frame and all circles to disk.
*
public class SavedFrame extends CloseableFrame
implements ActionListener {
/** If a saved version exists, use it. Otherwise create a
* new one.
*/
public static void main(String[] args) {
SavedFrame frame;
File serializeFile = new File(serializeFilename);
if (serializeFile.exists()) {
try {
FileInputStream fileIn =
new FileInputStream(serializeFile);
ObjectInputStream in = new ObjectInputStream(fileIn);
frame = (SavedFrame)in.readObject();
frame.setVisible(true);
} catch(IOException ioe) {
System.out.println("Error reading file: " + ioe);
} catch(ClassNotFoundException cnfe) {
System.out.println("No such class: " + cnfe);
}
} else {
frame = new SavedFrame();
}
}
private static String serializeFilename ="SavedFrame.ser";
private CirclePanel circlePanel;
private Button clearButton, saveButton;
/** Build a frame with CirclePanel and buttons. */
public SavedFrame() {
super("SavedFrame");
setBackground(Color.white);
setFont(new Font("Serif", Font.BOLD, 18));
circlePanel = new CirclePanel();
add("Center", circlePanel);
Panel buttonPanel = new Panel();
buttonPanel.setBackground(Color.lightGray);
clearButton = new Button("Clear");
saveButton = new Button("Save");
buttonPanel.add(clearButton);
buttonPanel.add(saveButton);
add(buttonPanel, BorderLayout.SOUTH);
clearButton.addActionListener(this);
saveButton.addActionListener(this);
setSize(300, 300);
setVisible(true);
}
/** If "Clear" clicked, delete all existing circles. If "Save"
* clicked, save existing frame configuration (size,
* location, circles, etc.) to disk.
*/
public void actionPerformed(ActionEvent event) {
if (event.getSource() == clearButton) {
circlePanel.removeAll();
circlePanel.repaint();
} else if (event.getSource() == saveButton) {
try {
FileOutputStream fileOut =
new FileOutputStream("SavedFrame.ser");
ObjectOutputStream out =
new ObjectOutputStream(fileOut);
out.writeObject(this);
out.flush();
out.close();
} catch(IOException ioe) {
System.out.println("Error saving frame: " + ioe);
}
}
}
}
****************
Similar Posts
Machine Learning, Big Data, Data Science, Analytics, Cloud, Security, AI, Robotics, Database, BI, Development: Software, Web, Mobile