Chris Pollett >
Old Classes >
PIC20B

   ( Print View )

Enrollment info

Course Info: Homework Assignments: Practice Exams: PIC:
                            












HW2 Solutions Page

Return to homework page.

//
// FileName: IconPaint.java
//
// Purpose: a simple paint program that allows the user to select from
//          a panel of icons to draw into a draw area. The user can also
//          save drawings and load old one's.
//

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.zip.*;
import java.util.*;

//
// Class Name: IconPaint
//
// Purpose: main class for this paint application
//
// Note: Since we have not talked about exception handling much yet
//       I am just catching Exception.
//
public class IconPaint extends JFrame
{
	private static String SHAPE_RESOURCE = "IconPaint.zip";
	private static int OPEN = 1;
	private static int SAVE = 0;
	private Container c;
	private JButton reset, check;
	private Vector shapes,  picture;
	private PicturePanel picturePanel;
	private Icon curIcon;


	//
	// Method Name: IconPaint
	//
	// Purpose: constructor for applications. Sets up the PicturePanel where images
	//          can be drawn. Sets up the controlButtonPanel on the bottom used for
        //          loading, saving, random draw, and quitting the program. Sets up the shapePanel
        //          when the different draw Icons can be chosen from.
	//
	public IconPaint()
	{

		super("IconPaint");

		shapes = new Vector();
		picture = new Vector();

		c=getContentPane();
		c.setLayout(new BorderLayout());
		c.setBackground(Color.gray);

		JLabel drawLabel= new JLabel("Draw Area:");
		c.add(drawLabel, BorderLayout.NORTH);

		picturePanel =new PicturePanel();
		picturePanel.setBackground(Color.white);
		c.add(picturePanel, BorderLayout.CENTER);

		JPanel shapePanel = LoadShapes();
                            shapePanel.setBackground(Color.gray);
		c.add(shapePanel, BorderLayout.EAST);

		JPanel controlButtonPanel = CreateControls();
                            controlButtonPanel.setBackground(Color.gray);
		c.add(controlButtonPanel, BorderLayout.SOUTH);

		setSize(500,500);
		show();

	}

	//
	// Method Name: LoadShapes
	//
	// Purpose: reads in the shapes which can be used in drawing to the draw area from a
	//          Zip file.
	//
	private JPanel LoadShapes()
	{
		JPanel shapePanel =new JPanel();
		shapePanel.setLayout( new BoxLayout( shapePanel,
                                                                     BoxLayout.Y_AXIS));

		try
		{

		   ZipInputStream  inZip = new ZipInputStream(new
                                       FileInputStream(SHAPE_RESOURCE));
		   ObjectInputStream inObj;
		   Icon img;
		   JButton button;


		   while(inZip.getNextEntry() != null)
		   {
	 	          inObj = new ObjectInputStream(
				   inZip);

                                      img = (Icon)inObj.readObject();

		         shapes.add(img);
		         button = new JButton(img);
		         button.setBackground(Color.white);
		         button.addActionListener( new ButtonListener(img));


		         shapePanel.add(Box.createVerticalStrut(10));
		         shapePanel.add(button);
		    }
		    inZip.close();

		}
		catch (Exception e)
		{
			JOptionPane.showMessageDialog( this,
			   "Could Not Open Icon Resource",
			   "Could Not Open Icon Resource",
			   JOptionPane.ERROR_MESSAGE );
			 e.printStackTrace();
			 System.exit(-1);
		}

		curIcon =(Icon)shapes.elementAt(0);
		return shapePanel;
	}

	//
	// Method Name: CreateControls
	//
	// Purpose: sets up the buttons for clearing the screen, opening and saving drawings
	//          and draw a random icon randomly button.
	//
	private JPanel CreateControls()
	{
		JPanel controlPanel = new JPanel();

		JButton clearButton = new JButton("Clear");
		clearButton.setBackground(Color.white);
		clearButton.addActionListener( new ActionListener(){
			public void actionPerformed( ActionEvent e)
			{
				picture = new Vector();
			              repaint();
	 		}
		   }
		);
		controlPanel.add(clearButton);

		JButton openButton = new JButton("Open");
		openButton.setBackground(Color.white);
		openButton.addActionListener( new ActionListener() {
			public void actionPerformed( ActionEvent e)
			{
			   File openFile;
			   if((openFile=SelectFile(OPEN))==null)  return;
			   OpenPicture(openFile);
			}
		}
		);
		controlPanel.add(openButton);

		JButton saveButton = new JButton("Save");
		saveButton.setBackground(Color.white);
		saveButton.addActionListener( new ActionListener() {
			public void actionPerformed( ActionEvent e)
			{
			   File saveFile;
			   if((saveFile=SelectFile(SAVE))==null)  return;
			   SavePicture(saveFile);
			}
		}
		);
		controlPanel.add(saveButton);

		JButton randomButton = new JButton("Random");
		randomButton.setBackground(Color.white);
		randomButton.addActionListener( new ActionListener() {
			public void actionPerformed( ActionEvent e)
			{
				int x,y,i;
				Random r = new Random();
				x =  Math.abs(r.nextInt() % picturePanel.getWidth());
				y = Math.abs(r.nextInt() % picturePanel.getHeight());
				i = Math.abs(r.nextInt() % shapes.size());
				curIcon = (Icon)shapes.elementAt(i);

				PictureElt pelt= new PictureElt(x,y,curIcon);
				picture.addElement(pelt);

				repaint();
			}
		}
		);
		controlPanel.add(randomButton);
		return controlPanel;
	}

	//
	// Method Name: SelectFile
	//
	// Purpose: returns a file name gotten from the user to either open or save
	//          (depending on how the loadSave flag is set.
	//
	private  File SelectFile(int loadSave)
	{
		JFileChooser jchoose = new JFileChooser();
	              jchoose. setFileSelectionMode( JFileChooser.FILES_ONLY);

		File file;
		int result;

		if( loadSave == SAVE)
		      result = jchoose. showSaveDialog(this);
		else
		     result = jchoose. showOpenDialog(this);

		if(result == JFileChooser.CANCEL_OPTION)
				return null;
		file = jchoose.getSelectedFile();

		if(file == null) JOptionPane.showMessageDialog( this,
			                "Bad File Name", "Bad File Name",
			               JOptionPane.ERROR_MESSAGE );

		return file;
	}

	//
	// Method Name: OpenPicture
	//
	// Purpose: reads in a saved picture Vector and displays it
	//
	//
	private void OpenPicture(File file)
	{
	       try
	      {
              	ObjectInputStream in = new ObjectInputStream(
                                           new FileInputStream(file));
                	picture = (Vector)in.readObject();
                	in.close();
                    }
	      catch (Exception e)
	      {
		     JOptionPane.showMessageDialog( this,
			   "Could not read picture",
			   "Could not read picture",
			   JOptionPane.ERROR_MESSAGE );
			    e.printStackTrace();
			 return;
	      }

	      repaint();
	}

	//
	// Method Name: SavePicture(File file)
	//
	// Purpose: saves the picture Vector to the File named file.
	//
	//

	private void SavePicture(File file)
	{
	      try
	      {
              	ObjectOutputStream out = new ObjectOutputStream(
                                           new FileOutputStream(file));
                	out.writeObject(picture);

                	out.close();
               }
	      catch (Exception e)
	      {
		     JOptionPane.showMessageDialog( this,
			   "Could not write picture",
			   "Could not write picture",
			   JOptionPane.ERROR_MESSAGE );
			    e.printStackTrace();
			 return;
	      }
	}


	//
	// Method Name:  main()
	//
	// Purpose: application entry point. Calls IconPaint constructor
	//                 and sets up JFrame. Sets up listener to listen
	//                 for close window events.

	public static void main (String args[])
	{
		IconPaint app = new IconPaint();

		app.addWindowListener(
			new WindowAdapter()
                                          {
			public void windowClosing ( WindowEvent e)
				{
					System.exit(0);
				}
			}
		);
	}


	//
	// Inner Class Name: PicturePanel
	//
	// Purpose: the object created from this class is used by the application
	//          as the draw area onto which the user can make his picture.
	//          The constructor sets up a MouseListener that listens for
	//          click in the draw area and if received draws the current icon.
	//          at the Mouse X and Y value. Further it updates the vector
        //          picture of icons that have been drawn.
	//
	class PicturePanel extends JPanel
	{
		public PicturePanel()
		{
		  addMouseListener( new MouseAdapter() {
			public void mouseClicked( MouseEvent e)
                                          {
				PictureElt elt= new PictureElt(
					e.getX()-curIcon.getIconWidth()/2,
					e.getY()-curIcon.getIconHeight()/2,
                                                                      curIcon);
				picture.addElement(elt);
				repaint();
			}
		    }
		  );
		}

		public void paintComponent(Graphics g)
		{
			super.paintComponent(g);
			Enumeration enum = picture.elements();
			PictureElt p;

			while(enum.hasMoreElements())
			{
				p=(PictureElt)enum.nextElement() ;
		     	                    p.getIcon().paintIcon(this, g, p.getX(),
                                                              p.getY());
			}
		}

	}

	//
	// Inner Class Name: ButtonListener
	//
	// Purpose: stores an Icon associated with a button from the shapesPanel.
	//          When sent an ActionEvent sets the curIcon to be the stored icon.
	//

	class ButtonListener implements ActionListener
	{
		private Icon icon;
		public ButtonListener(Icon ic)
		{
			icon=ic;
		}
		public void actionPerformed( ActionEvent e)
		{
			curIcon = icon;
	 	}

	}


}

//
// Class Name: PictureElt
//
// Purpose: encapsulates the notion of one Icon drawn to the picturePanel.
//          Stores the x, y location of the Icon drawn togther with the Icon itself
//          that was drawn.
//

class PictureElt implements Serializable
{
	private int x, y;
	private Icon icon;

	public PictureElt(int xVal, int yVal, Icon ic)
	{
	    x=xVal;
	    y=yVal;
	    icon= ic;
	}
	public int getX() { return x;}
	public int getY() { return y;}
	public Icon getIcon() { return icon;}
}