The Artima Developer Community
Sponsored Link

Java Answers Forum
Wanting general help on my current project

4 replies on 1 page. Most recent reply: Dec 13, 2002 2:00 PM by Matt Gerrans

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 4 replies on 1 page
Chris Reck

Posts: 7
Nickname: creck
Registered: Nov, 2002

Wanting general help on my current project Posted: Dec 5, 2002 11:14 AM
Reply to this message Reply
Advertisement
I am wanting to ask for help about my code, suggestions for removing my innner methods. I know that you I will need to send or post my code for that to happen, what is the BEST way to do this?


Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: Wanting general help on my current project Posted: Dec 5, 2002 1:02 PM
Reply to this message Reply
What's an inner method? Do you mean inner class?

As far as posting your code, be sure and use the java tags (see the Formatting Your Post box at the right, when you are posting). Also, you can use the Preview button before you post, to make sure everything looks lovely before you post.

Chris Reck

Posts: 7
Nickname: creck
Registered: Nov, 2002

Re: Wanting general help on my current project Posted: Dec 6, 2002 6:07 AM
Reply to this message Reply
Here is my code. It works as far as I have gotten, i.e. no problems with its function. My problem is that I am having to tie my classes together very hard. I am wanting to get rid of all of my globals and move my inner classes out of my main function. So the question is what is the best and proper way to access all of the methods and variables that I need in my different classes?

If my question doesn't make sense, and suggestions for improvement to my code will be appricated.


package Clone_Icon_Editor;
/*******************************************************************
*	Programmer: Chris Reck
*	Project:	Icon editor	
*	Started:		02-Feb-2001
*	Last Worked on:	   6-Dec-2002
*	
********************************************************************/
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.colorchooser.*;
import java.awt.Insets.*;
 
 
 
public class ImageTry extends JFrame {
 
	private static MyListenerHandler mice;
	private static ColorPanel cp;
	private static IconPreview iconPV;
	
    Image img = null;
    Image backImg = null;
    static Image icon = null;
    Graphics gImg = null;
	static int[] pixels = new int[32*32];
	int iconOriginX = 0;
	int iconOriginY = 0;
	int screenWidth = 0;
	int screenHeight = 0;
	int editSize = 0;
	Color c = new Color(Color.black.getRGB());
	PixelGrabber pg = null;
	IconPallet iconPallet = null;
	IconButtonEdit iconEdit = null;
    Insets MFinsets = null;
    File myFile = new File("test2.dat");
    
	  
    public ImageTry() {
        super("Clone's Icon Editor");
        mice = new MyListenerHandler(this);
 
        setBackground(c);
 
        this.addWindowListener(new BasicWindowMonitor());
 
		Dimension D = Toolkit.getDefaultToolkit( ).getScreenSize( );
		screenWidth = D.width;
		screenHeight = D.height;
 
		Frame frame = new Frame();
		frame.addNotify();
		backImg = frame.createImage(512, 512);
		gImg = backImg.getGraphics();
 
        img = getToolkit().getImage(myFile.getAbsolutePath());
        try {
            MediaTracker tracker = new MediaTracker(this);
            tracker.addImage(img, 0);
            tracker.waitForID(0);
        } catch (Exception e) {}
 
 
		JMenuBar menuBar = new JMenuBar();
		JMenu file = new JMenu("File");
		file.setMnemonic('F');
		
		JMenuItem newf = new JMenuItem("New");
		newf.addActionListener(mice);
		JMenuItem open = new JMenuItem("Open");
		open.addActionListener(mice);
		JMenuItem save = new JMenuItem("Save");
		save.addActionListener(mice);
		JMenuItem saveas = new JMenuItem("Save As");
		saveas.addActionListener(mice);
		JMenuItem exit = new JMenuItem("Exit");
		exit.addActionListener(mice);
		
		file.add(newf);		
		file.add(open);		
		file.add(save);		
		file.add(saveas);		
		file.addSeparator();
		file.add(exit);		
 
		menuBar.add(file);			
		this.setJMenuBar(menuBar);
 
		gImg.drawImage(img,0,0,null);
 
		pack();
		MFinsets = getInsets();
 
        setSize(screenWidth, screenHeight);
	
		setVisible(true);
		showIconPallet();
		//iconPallet = new IconPallet(this, img);
	}		 
 
	public boolean visibleIconPallet() {
		return iconPallet.isShowing();
	}
	
    public void showIconPallet() {
		iconPallet = new IconPallet(this, img, MFinsets);
    }
    
    public void closeIconPallet(){
			if(iconPallet.isVisible()) {
				iconPallet.setVisible(false);
				iconPallet.getGraphics().dispose();
			}			
	}
 
 	public boolean visibleIconButtonEdit() {
		return iconEdit.isShowing();
	}
	
	public void showIconButtonEdit() {
				iconEdit = new IconButtonEdit(this, 32,32, MFinsets);
    }
    
    public void closeIconButtonEdit(){
			if(iconEdit.isVisible()) {
				iconEdit.setVisible(false);
				iconEdit.getGraphics().dispose();
			}			
	}
 
 	public boolean visibleColorPanel() {
		return cp.isShowing();
	}
	
    public void showColorPanel() {
        cp = new ColorPanel(this, screenHeight, MFinsets);
    }
    
    public void closeColorPanel(){
			if(cp.isVisible()) {
				cp.setVisible(false);
				cp.getGraphics().dispose();
			}			
	}
    
 	public boolean visibleIconPreview() {
		return iconPV.isShowing();
	}
	
	public void showIconPreview() {
        iconPV = new IconPreview(this, 32, 32);
    }
    
	public void closeIconPreview() {
		if(iconPV.isVisible()) {
			iconPV.setVisible(false);
			iconPV.getGraphics().dispose();
		}
	}
 
 
    class IconButtonEdit extends JDialog implements MouseInputListener, ComponentListener, ActionListener {
    	Insets IBEinsets = null;
    	MouseEvent me = null;
    	int oldSize = 0;
    	String editMode = "Edit";
		JButton[] buttons = new JButton[32*32];
		Object pix = null;
		
		public IconButtonEdit(ImageTry mParent,  int iconW, int iconH, Insets MFinsets) {
			super (mParent, "Icon Editing panel", true);
			addWindowListener(new DialogWindowMonitor());
			setModal(false);
			setLocation(MFinsets.left, MFinsets.top+23);
			pix = iconPallet.pg.getPixels();
			JButton jb;
			for (int i = 0; i < iconW*iconH; i++) {
				jb = new JButton();
				jb.setBackground(new Color(((int[])pix)[i]));
				jb.setBorderPainted(false);
 				jb.addMouseListener(this);
	 			jb.setName(""+i);
				getContentPane().add(jb);
				buttons[i] = jb;
				pixels[i] = ((int[])pix)[i];
			}
 			addComponentListener(this);
 			//addMouseListener(this);
 			//addMouseMotionListener(this);
			
			JMenuBar editMenuBar = new JMenuBar();
			setJMenuBar(editMenuBar);
	
			JMenu icon = new JMenu("Icon");
			icon.setMnemonic('I');
			JMenu view = new JMenu("View");
			view.setMnemonic('V');
			
			JMenuItem clearIcon = new JMenuItem("Clear");
			clearIcon.addActionListener(this);
			JMenuItem reloadIcon = new JMenuItem("Reload");
			reloadIcon.addActionListener(this);
			JMenuItem getColorIcon = new JMenuItem("Get Color");
			getColorIcon.addActionListener(this);
			JMenuItem saveIcon = new JMenuItem("Save");
			saveIcon.addActionListener(this);
			JMenuItem saveAtIcon = new JMenuItem("Save-At");
			saveAtIcon.addActionListener(this);
			JMenuItem exitIcon = new JMenuItem("Exit");
			exitIcon.addActionListener(this);
			
			icon.add(clearIcon);
			icon.add(reloadIcon);
			icon.add(getColorIcon);
			icon.add(saveIcon);
			icon.add(saveAtIcon);
			icon.add(exitIcon);
			
			editMenuBar.add(icon);			
		
			getContentPane().setLayout(new GridLayout(iconW,iconH));
			pack();
			IBEinsets = getInsets();
			editSize = screenHeight-cp.getHeight()-MFinsets.top-MFinsets.bottom-80;
			editSize = (editSize/32)*32;
			oldSize = editSize;
			setSize(editSize+IBEinsets.left+IBEinsets.right, editSize+IBEinsets.top);
	    	setVisible(true);
	    }
	    
 
		public void actionPerformed(ActionEvent ae) {
			Color c = new Color(Color.black.getRGB());
			if(ae.getActionCommand() == "Clear")
			{
				editMode = "Clear";
				for (int i = 0; i < 32*32; i++) {
					buttons[i].setBackground(c);
					pixels[i] = Color.black.getRGB();
				}
				icon = createImage(new MemoryImageSource(32, 32, pixels, 0, 32));
				iconPV.repaint();
			}
 
			if(ae.getActionCommand() == "Reload")
			{	
				editMode = "Reload";
				for (int i = 0; i < 32*32; i++) {
					buttons[i].setBackground(new Color(((int[])pix)[i]));
					pixels[i] = ((int[])pix)[i];
				}
				icon = createImage(new MemoryImageSource(32, 32, pixels, 0, 32));
				iconPV.repaint();					
			}
 
			
			if(ae.getActionCommand() == "Save-At")
			{
				editMode = "Save-At";
				System.out.println("Save-At, not yet implemented");
			}
 
			if(ae.getActionCommand() == "Get Color")
			{
				editMode = "getColor";
			}
			
			if(ae.getActionCommand() == "Save")
			{
				editMode = "Save";
				gImg.drawImage(icon,
					IconPallet.iconOriginX,
					IconPallet.iconOriginY,
					IconPallet.iconOriginX+32,
					IconPallet.iconOriginY+32,
					0,0,32,32,null);
				img = backImg;
				try {
					GIFEncoder encode = new GIFEncoder(img);
					OutputStream output = new BufferedOutputStream(new FileOutputStream(myFile.getAbsolutePath()));
					encode.Write(output);
				}
				catch (AWTException awte) {System.out.println("AWTE");}
				catch (FileNotFoundException FNF) {System.out.println("File not found");}
				catch (IOException ie) {System.out.println("IO Execption");}
			}
								
			if(ae.getActionCommand() == "Exit")
			{	
				editMode = "Exit";
				showIconPallet();
				setVisible(false);
				dispose();
				closeIconPreview();
				closeColorPanel();
			}					
		}
			
	    public void mousePressed(MouseEvent me) {
			if(editMode == "Edit") {
		  		if ( (me.getModifiers() & InputEvent.BUTTON1_MASK) !=0 )
		       		c = ColorPanel.getPriColor();
				
			   	else
			   		c = ColorPanel.getSecColor();
			    		
				me.getComponent().setBackground(c);
				pixels[Integer.valueOf(me.getComponent()
					.getName()).intValue()] = c.getRGB();
				icon = createImage(new MemoryImageSource(32, 32, pixels, 0, 32));
				iconPV.repaint();
			}
			
	
			if(editMode == "getColor") {
	      		if ( (me.getModifiers() & InputEvent.BUTTON1_MASK) !=0 ) {
	           		ColorPanel.setPriColor(me.getComponent().getBackground()) ;
	           		ColorPanel.preView1.setBackground(ColorPanel.getPriColor());
	           	}
		    	else {
		    		ColorPanel.setSecColor(me.getComponent().getBackground());
	           		ColorPanel.preView2.setBackground(ColorPanel.getSecColor());
	           	}
		  	}
	    	editMode = "Edit";
		}
  
	    public void mouseEntered(MouseEvent me) {
		  	if(editMode == "Edit")
		  	{
		  		if ((me.getModifiers() & InputEvent.BUTTON1_MASK ) !=0 )
				{	c = ColorPanel.getPriColor();
					me.getComponent().setBackground(c);
					pixels[Integer.valueOf(me.getComponent()
						.getName()).intValue()] = c.getRGB();
					icon = createImage(new MemoryImageSource(32, 32, pixels, 0, 32));
					iconPV.repaint();
				}
			  	if ((me.getModifiers() & InputEvent.BUTTON3_MASK) !=0 )
		    	{	c = ColorPanel.getSecColor();
					me.getComponent().setBackground(c);
					pixels[Integer.valueOf(me.getComponent()
						.getName()).intValue()] = c.getRGB();
					icon = createImage(new MemoryImageSource(32, 32, pixels, 0, 32));
					iconPV.repaint();
		    	}
		    }
		}
 
 
    	public void mouseMoved(MouseEvent me) {}
 
	    public void mouseClicked(MouseEvent me) {}
	
    	public void mouseReleased(MouseEvent me) {}
 
    	public void mouseDragged(MouseEvent me) {}
 
    	public void mouseExited(MouseEvent me) {}
 
		
 
		public void componentResized(ComponentEvent ce) {
			if(getWidth() != oldSize+IBEinsets.left+IBEinsets.right)
			{
				editSize = getWidth();
				if (editSize > screenHeight-(int)(screenHeight*.1))
					editSize = screenHeight-(int)(screenHeight*.1);
				editSize = (editSize/32)*32;
				oldSize = editSize;
			}
			else if(this.getHeight() != oldSize+IBEinsets.top)
			{	
				editSize = getHeight();
				if (editSize > screenHeight-(int)(screenHeight*.1))
					editSize = screenHeight-(int)(screenHeight*.1);
				editSize = (editSize/32)*32;
				oldSize = editSize;
			}
	
			setSize(editSize+IBEinsets.left+IBEinsets.right, editSize+IBEinsets.top-5);
		}
	    
	    public void componentMoved (ComponentEvent ce) {}
 
		public void componentShown (ComponentEvent ce) {}
 
		public void componentHidden (ComponentEvent ce) {}
		
	}
	
   
    public class DialogWindowMonitor extends WindowAdapter {
		public void windowClosing(WindowEvent e) {
			showIconPallet();
			Window w = e.getWindow();
			closeColorPanel();
			closeIconPreview();
			w.setVisible(false);
			w.dispose();
 
		}   
	}
 
	public static void main(String[] args){
        ImageTry ac = new ImageTry();
            ac.setVisible(true);
    }
}					 
 
 
 
 
package Clone_Icon_Editor;
import java.awt.event.*;
import java.awt.Window;
 
public class BasicWindowMonitor extends WindowAdapter {
 
  public void windowClosing(WindowEvent e) {
    Window w = e.getWindow();
    w.setVisible(false);
    w.dispose();
    System.exit(0);
  }
}
 
 
 
 
package Clone_Icon_Editor;
 
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.colorchooser.*;
import java.awt.Insets.*;
 
public class ColorPanel extends JDialog {
 
	static JButton preView1 = new JButton("Primary");
	static JButton preView2 = new JButton("Secondary");
	static Color c = new Color(Color.black.getRGB());
	static Color priColor = new Color(Color.white.getRGB());
	static Color secColor = c;
 
	public ColorPanel(ImageTry parent, int screenHeight,Insets MFinset) {
		super (parent, "Color Panel", true);
		setResizable(false);
		setModal(false);
	
		final JColorChooser jcc = new JColorChooser(secColor);
		
		AbstractColorChooserPanel[] oldPanels = jcc.getChooserPanels();
		jcc.removeChooserPanel(oldPanels[1]);
		//jcc.removeChooserPanel(oldPanels[2]);
		
		final JPanel panel = new JPanel();
		panel.setPreferredSize(new Dimension(100,30));
		preView1.setBackground(priColor);
		preView2.setBackground(secColor);
		panel.add(preView1);
		panel.add(preView2);
		
		jcc.setPreviewPanel(panel);
	
		final ColorSelectionModel csm = jcc.getSelectionModel();
		csm.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				c = csm.getSelectedColor();
				if (preView1.hasFocus())
				{	preView1.setBackground(c);
					priColor = c;
				}
				else
				{	preView2.setBackground(c);
					secColor = c;
				}
			}
		});
	
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		getContentPane().add(jcc);
		pack();
	
		setLocation(5,(parent.screenHeight-getHeight())-parent.MFinsets.top);
		setVisible(true);
	}
    
    static  Color getPriColor() {
    	return priColor;
    }
    static  Color getSecColor() {
    	return secColor;
    }
    static  void setPriColor(Color c) {
		priColor = c;
	}
    static  void setSecColor(Color c) {
    	secColor = c;
	}
 	public void setPriButton(Color c) {
		preView1.setBackground(c);
	}
	public void setSecButton(Color c) {
		preView2.setBackground(c);
	}
 
}		
 
 
 
 
 
 
/*
 * @(#)GIFEncoder.java    0.90 4/21/96 Adam Doppelt
 */
package Clone_Icon_Editor;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
 
/**
 * GIFEncoder is a class which takes an image and saves it to a stream
 * using the GIF file format (<A
 * HREF="http://www.dcs.ed.ac.uk/%7Emxr/gfx/">Graphics Interchange
 * Format</A>). A GIFEncoder
 * is constructed with either an AWT Image (which must be fully
 * loaded) or a set of RGB arrays. The image can be written out with a
 * call to <CODE>Write</CODE>.<P>
 *
 * Three caveats:
 * <UL>
 *   <LI>GIFEncoder will convert the image to indexed color upon
 *   construction. This will take some time, depending on the size of
 *   the image. Also, actually writing the image out (Write) will take
 *   time.<P>
 *
 *   <LI>The image cannot have more than 256 colors, since GIF is an 8
 *   bit format. For a 24 bit to 8 bit quantization algorithm, see
 *   Graphics Gems II III.2 by Xialoin Wu. Or check out his <A
 *   HREF="http://www.csd.uwo.ca/faculty/wu/cq.c">C source</A>.<P>
 *
 *   <LI>Since the image must be completely loaded into memory,
 *   GIFEncoder may have problems with large images. Attempting to
 *   encode an image which will not fit into memory will probably
 *   result in the following exception:<P>
 *   <CODE>java.awt.AWTException: Grabber returned false: 192</CODE><P>
 * </UL><P>
 *
 * GIFEncoder is based upon gifsave.c, which was written and released
 * by:<P>
 * <CENTER>
 *                                  Sverre H. Huseby<BR>
 *                                   Bjoelsengt. 17<BR>
 *                                     N-0468 Oslo<BR>
 *                                       Norway<P>
 *
 *                                 Phone: +47 2 230539<BR>
 *                                 sverrehu@ifi.uio.no<P>
 * </CENTER>
 * @version 0.90 21 Apr 1996
 * @author <A HREF="http://www.cs.brown.edu/people/amd/">Adam Doppelt</A> */
public class GIFEncoder {
    short width_, height_;
    int numColors_;
    byte pixels_[], colors_[];
    
    ScreenDescriptor sd_;
    ImageDescriptor id_;
    
/**
 * Construct a GIFEncoder. The constructor will convert the image to
 * an indexed color array. <B>This may take some time.</B><P>
 * 
 * @param image The image to encode. The image <B>must</B> be
 * completely loaded.
 * @exception AWTException Will be thrown if the pixel grab fails. This
 * can happen if Java runs out of memory. It may also indicate that the image
 * contains more than 256 colors.
 * */
    public GIFEncoder(Image image) throws AWTException {
	width_ = (short)image.getWidth(null);
	height_ = (short)image.getHeight(null);
 
	int values[] = new int[width_ * height_];
	PixelGrabber grabber = new PixelGrabber(
	    image, 0, 0, width_, height_, values, 0, width_);
	
	try {
	    if(grabber.grabPixels() != true)
		throw new AWTException("Grabber returned false: " +
				       grabber.status());
	}
	catch (InterruptedException e) { ; }
	
	byte r[][] = new byte[width_][height_];
	byte g[][] = new byte[width_][height_];
	byte b[][] = new byte[width_][height_];
	int index = 0;
	for (int y = 0; y < height_; ++y)
	    for (int x = 0; x < width_; ++x) {
		r[x][y] = (byte)((values[index] >> 16) & 0xFF);
		g[x][y] = (byte)((values[index] >> 8) & 0xFF);
		b[x][y] = (byte)((values[index]) & 0xFF);  
		++index;
	    }
	ToIndexedColor(r, g, b);
    }
 
/**
 * Construct a GIFEncoder. The constructor will convert the image to
 * an indexed color array. <B>This may take some time.</B><P>
 *
 * Each array stores intensity values for the image. In other words,
 * r[x][y] refers to the red intensity of the pixel at column x, row
 * y.<P>
 *
 * @param r An array containing the red intensity values.
 * @param g An array containing the green intensity values.
 * @param b An array containing the blue intensity values.
 *
 * @exception AWTException Will be thrown if the image contains more than
 * 256 colors.
 * */
    public GIFEncoder(byte r[][], byte g[][], byte b[][]) throws AWTException {
	width_ = (short)(r.length);
	height_ = (short)(r[0].length);
 
	ToIndexedColor(r, g, b);
    }
 
/**
 * Writes the image out to a stream in the GIF file format. This will
 * be a single GIF87a image, non-interlaced, with no background color.
 * <B>This may take some time.</B><P>
 *
 * @param output The stream to output to. This should probably be a
 * buffered stream.
 *
 * @exception IOException Will be thrown if a write operation fails.
 * */
    public void Write(OutputStream output) throws IOException {
	BitUtils.WriteString(output, "GIF87a");
	
	ScreenDescriptor sd = new ScreenDescriptor(width_, height_,
						   numColors_);
	sd.Write(output);
 
	output.write(colors_, 0, colors_.length);
 
	ImageDescriptor id = new ImageDescriptor(width_, height_, ',');
	id.Write(output);
 
	byte codesize = BitUtils.BitsNeeded(numColors_);
	if (codesize == 1)
	    ++codesize;
	output.write(codesize);
 
	LZWCompressor.LZWCompress(output, codesize, pixels_);
	output.write(0);
 
	id = new ImageDescriptor((byte)0, (byte)0, ';');
	id.Write(output);
	output.flush();
    }
 
    void ToIndexedColor(byte r[][], byte g[][],
			byte b[][]) throws AWTException {
	pixels_ = new byte[width_ * height_];
	colors_ = new byte[256 * 3];
	int colornum = 0;
	for (int x = 0; x < width_; ++x) {
	    for (int y = 0; y < height_; ++y) {
		int search;
		for (search = 0; search < colornum; ++search)
		    if (colors_[search * 3]     == r[x][y] &&
			colors_[search * 3 + 1] == g[x][y] &&
			colors_[search * 3 + 2] == b[x][y])
			break;
		
		if (search > 255)
		    throw new AWTException("Too many colors.");
 
		pixels_[y * width_ + x] = (byte)search;
		
		if (search == colornum) {
		    colors_[search * 3]     = r[x][y];
		    colors_[search * 3 + 1] = g[x][y];
		    colors_[search * 3 + 2] = b[x][y];
		    ++colornum;
		}
	    }
	}
	numColors_ = 1 << BitUtils.BitsNeeded(colornum);
	byte copy[] = new byte[numColors_ * 3];
	System.arraycopy(colors_, 0, copy, 0, numColors_ * 3);
	colors_ = copy;
    }
    
}
 
class BitFile {
    OutputStream output_;
    byte buffer_[];
    int index_, bitsLeft_;
 
    public BitFile(OutputStream output) {
	output_ = output;
	buffer_ = new byte[256];
	index_ = 0;
	bitsLeft_ = 8;
    }
 
    public void Flush() throws IOException {
	int numBytes = index_ + (bitsLeft_ == 8 ? 0 : 1);
	if (numBytes > 0) {
	    output_.write(numBytes);
	    output_.write(buffer_, 0, numBytes);
	    buffer_[0] = 0;
	    index_ = 0;
	    bitsLeft_ = 8;
	}
    }
 
    public void WriteBits(int bits, int numbits) throws IOException {
	int bitsWritten = 0;
	int numBytes = 255;
	do {
	    if ((index_ == 254 && bitsLeft_ == 0) || index_ > 254) {
		output_.write(numBytes);
		output_.write(buffer_, 0, numBytes);
 
		buffer_[0] = 0;
		index_ = 0;
		bitsLeft_ = 8;
	    }
 
	    if (numbits <= bitsLeft_) {
		buffer_[index_] |= (bits & ((1 << numbits) - 1)) <<
		    (8 - bitsLeft_);
		bitsWritten += numbits;
		bitsLeft_ -= numbits;
		numbits = 0;
	    }
	    else {
		buffer_[index_] |= (bits & ((1 << bitsLeft_) - 1)) <<
		    (8 - bitsLeft_);
		bitsWritten += bitsLeft_;
		bits >>= bitsLeft_;
		numbits -= bitsLeft_;
		buffer_[++index_] = 0;
		bitsLeft_ = 8;
	    }
	} while (numbits != 0);
    }
}
 
class LZWStringTable {
    private final static int RES_CODES = 2;
    private final static short HASH_FREE = (short)0xFFFF;
    private final static short NEXT_FIRST = (short)0xFFFF;
    private final static int MAXBITS = 12;
    private final static int MAXSTR = (1 << MAXBITS);
    private final static short HASHSIZE = 9973;
    private final static short HASHSTEP = 2039;
 
    byte strChr_[];
    short strNxt_[];
    short strHsh_[];
    short numStrings_;
 
    public LZWStringTable() {
	strChr_ = new byte[MAXSTR];
	strNxt_ = new short[MAXSTR];
	strHsh_ = new short[HASHSIZE];    
    }
 
    public int AddCharString(short index, byte b) {
	int hshidx;
 
	if (numStrings_ >= MAXSTR)
	    return 0xFFFF;
	
	hshidx = Hash(index, b);
	while (strHsh_[hshidx] != HASH_FREE)
	    hshidx = (hshidx + HASHSTEP) % HASHSIZE;
	
	strHsh_[hshidx] = numStrings_;
	strChr_[numStrings_] = b;
	strNxt_[numStrings_] = (index != HASH_FREE) ? index : NEXT_FIRST;
 
	return numStrings_++;
    }
    
    public short FindCharString(short index, byte b) {
	int hshidx, nxtidx;
 
	if (index == HASH_FREE)
	    return b;
 
	hshidx = Hash(index, b);
	while ((nxtidx = strHsh_[hshidx]) != HASH_FREE) {
	    if (strNxt_[nxtidx] == index && strChr_[nxtidx] == b)
		return (short)nxtidx;
	    hshidx = (hshidx + HASHSTEP) % HASHSIZE;
	}
 
	return (short)0xFFFF;
    }
 
    public void ClearTable(int codesize) {
	numStrings_ = 0;
	
	for (int q = 0; q < HASHSIZE; q++) {
	    strHsh_[q] = HASH_FREE;
	}
 
	int w = (1 << codesize) + RES_CODES;
	for (int q = 0; q < w; q++)
	    AddCharString((short)0xFFFF, (byte)q);
    }
    
    static public int Hash(short index, byte lastbyte) {
	return ((int)((short)(lastbyte << 8) ^ index) & 0xFFFF) % HASHSIZE;
    }
}
 
class LZWCompressor {
 
    public static void LZWCompress(OutputStream output, int codesize,
				   byte toCompress[]) throws IOException {
	byte c;
	short index;
	int clearcode, endofinfo, numbits, limit, errcode;
	short prefix = (short)0xFFFF;
 
	BitFile bitFile = new BitFile(output);
	LZWStringTable strings = new LZWStringTable();
 
	clearcode = 1 << codesize;
	endofinfo = clearcode + 1;
    
	numbits = codesize + 1;
	limit = (1 << numbits) - 1;
	
	strings.ClearTable(codesize);
	bitFile.WriteBits(clearcode, numbits);
 
	for (int loop = 0; loop < toCompress.length; ++loop) {
	    c = toCompress[loop];
	    if ((index = strings.FindCharString(prefix, c)) != -1)
		prefix = index;
	    else {
		bitFile.WriteBits(prefix, numbits);
		if (strings.AddCharString(prefix, c) > limit) {
		    if (++numbits > 12) {
			bitFile.WriteBits(clearcode, numbits - 1);
			strings.ClearTable(codesize);
			numbits = codesize + 1;
		    }
		    limit = (1 << numbits) - 1;
		}
		
		prefix = (short)((short)c & 0xFF);
	    }
	}
	
	if (prefix != -1)
	    bitFile.WriteBits(prefix, numbits);
	
	bitFile.WriteBits(endofinfo, numbits);
	bitFile.Flush();
    }
}
 
class ScreenDescriptor {
    public short localScreenWidth_, localScreenHeight_;
    private byte byte_;
    public byte backgroundColorIndex_, pixelAspectRatio_;
 
    public ScreenDescriptor(short width, short height, int numColors) {
	localScreenWidth_ = width;
	localScreenHeight_ = height;
	SetGlobalColorTableSize((byte)(BitUtils.BitsNeeded(numColors) - 1));
	SetGlobalColorTableFlag((byte)1);
	SetSortFlag((byte)0);
	SetColorResolution((byte)7);
	backgroundColorIndex_ = 0;
	pixelAspectRatio_ = 0;
    }
 
    public void Write(OutputStream output) throws IOException {
	BitUtils.WriteWord(output, localScreenWidth_);
	BitUtils.WriteWord(output, localScreenHeight_);
	output.write(byte_);
	output.write(backgroundColorIndex_);
	output.write(pixelAspectRatio_);
    }
 
    public void SetGlobalColorTableSize(byte num) {
	byte_ |= (num & 7);
    }
 
    public void SetSortFlag(byte num) {
	byte_ |= (num & 1) << 3;
    }
 
    public void SetColorResolution(byte num) {
	byte_ |= (num & 7) << 4;
    }
    
    public void SetGlobalColorTableFlag(byte num) {
	byte_ |= (num & 1) << 7;
    }
}
 
class ImageDescriptor {
    public byte separator_;
    public short leftPosition_, topPosition_, width_, height_;
    private byte byte_;
 
    public ImageDescriptor(short width, short height, char separator) {
	separator_ = (byte)separator;
	leftPosition_ = 0;
	topPosition_ = 0;
	width_ = width;
	height_ = height;
	SetLocalColorTableSize((byte)0);
	SetReserved((byte)0);
	SetSortFlag((byte)0);
	SetInterlaceFlag((byte)0);
	SetLocalColorTableFlag((byte)0);
    }
    
    public void Write(OutputStream output) throws IOException {
	output.write(separator_);
	BitUtils.WriteWord(output, leftPosition_);
	BitUtils.WriteWord(output, topPosition_);
	BitUtils.WriteWord(output, width_);
	BitUtils.WriteWord(output, height_);		
	output.write(byte_);
    }
 
    public void SetLocalColorTableSize(byte num) {
	byte_ |= (num & 7);
    }
 
    public void SetReserved(byte num) {
	byte_ |= (num & 3) << 3;
    }
 
    public void SetSortFlag(byte num) {
	byte_ |= (num & 1) << 5;
    }
    
    public void SetInterlaceFlag(byte num) {
	byte_ |= (num & 1) << 6;
    }
 
    public void SetLocalColorTableFlag(byte num) {
	byte_ |= (num & 1) << 7;
    }
}
 
class BitUtils {
    public static byte BitsNeeded(int n) {
	byte ret = 1;
 
	if (n-- == 0)
	    return 0;
 
	while ((n >>= 1) != 0)
	    ++ret;
	
	return ret;
    }    
 
    public static void WriteWord(OutputStream output,
				 short w) throws IOException {
	output.write(w & 0xFF);
	output.write((w >> 8) & 0xFF);
    }
    
    static void WriteString(OutputStream output,
			    String string) throws IOException {
	for (int loop = 0; loop < string.length(); ++loop)
	    output.write((byte)(string.charAt(loop)));
    }
}
 
 
 
 
 
package Clone_Icon_Editor;
 
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.colorchooser.*;
import java.awt.Insets.*;
 
 
	class IconPallet extends JDialog implements MouseListener {	
    	Insets IPInsets = null;
    	Image myImg = null;
    	static int iconOriginX = 0;
		static int iconOriginY = 0;
		PixelGrabber pg = null;
		ImageTry myParent = null;
	
    	
		public IconPallet(ImageTry parent, Image img, Insets MFinsets) {
			super (parent, "Icon Pallet", true);
			setResizable(false);
			setModal(false);
			setLocation(MFinsets.left, MFinsets.top+23);
			addMouseListener(this);
			myImg = img;
			myParent = parent;
			pack();
			IPInsets = getInsets();
	        setSize(img.getWidth(this)+IPInsets.left+IPInsets.right, img.getHeight(this)+IPInsets.top+IPInsets.bottom);
	    	setVisible(true);
	    }
	    
	    public PixelGrabber currentGrab ()
	    {
	    	return pg;
	 	}
	 	
	    public void paint(Graphics g) {
	    	g.drawImage(myImg, IPInsets.left, IPInsets.top, null);
	 	}
	    
	    public void mousePressed(MouseEvent me) {
	    	try {
	    		if (myParent.visibleIconButtonEdit() == true) 
	    			return;
	    	}
	    	catch (Exception e){}
	     	try {
	   			if (myParent.visibleColorPanel() == true) 
	    			return;
	    	}
	    	catch (Exception e){}
	     	try {
	   			if (myParent.visibleIconPreview() == true) 
	    			return;
	    	}
	    	catch (Exception e){}
	    	
			int iconX = (me.getX()-2)/32;
			int iconY = (me.getY()-22)/32;
	        int sizeX = 32;
	        int sizeY = 32;
	        iconOriginX = iconX * sizeX;
	        iconOriginY = iconY * sizeY;
			if (iconX < 16 && iconY < 16 )
			{	PixelGrabber pg = grabPixels(iconX, iconY, 32, 32);
				ColorModel cm = pg.getColorModel();
				this.setVisible(false);
				myParent.showColorPanel();
				myParent.showIconButtonEdit();
				myParent.showIconPreview();
			}
			
	 	}
		
		public void mouseClicked(MouseEvent me) {}
		
	    public void mouseReleased(MouseEvent me) {}
	
	    public void mouseEntered(MouseEvent me) {}
	
	    public void mouseExited(MouseEvent me) {}
	   
		
	    public PixelGrabber grabPixels(int iconX, int iconY, int sizeX, int sizeY){
	        iconOriginX = iconX*sizeX;
	        iconOriginY = iconY*sizeY;
	        pg = new PixelGrabber(myImg, iconX*sizeX, iconY*sizeY, sizeX, sizeY, true);
		    pg.startGrabbing();
	
		    try {
				pg.grabPixels();
		    } 
		    catch (InterruptedException e) {
				System.err.println("grab was interrupted");
				return null;
		    }
	
			return pg;
		}
	}
 
 
 
 
 
package Clone_Icon_Editor;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.colorchooser.*;
import java.awt.Insets.*;
 
 
 
 	public class IconPreview extends Dialog
    {	
    	private MyListenerHandler listen;
    	
    	Insets PInsets = null;
    	Image myIcon = null;
    	int[] mypixels = null;
    	int width = 0;
    	int heigth = 0;
 
		public IconPreview(ImageTry parent,  int w, int h) {
			super (parent, "Preview", true);
			listen = parent.getHandle();
			this.addWindowListener(listen);
			
			setResizable(false);
			setModal(false);
			setLocation(parent.iconEdit.getWidth()+32, 50);
			width = w;
			heigth = h;
			mypixels = parent.pixels;
			pack();
			PInsets = getInsets();
			setSize(0, 32+PInsets.top+PInsets.bottom);
	    	setVisible(true);
	    }
 
 
	    
	    public void paint(Graphics g) {
			myIcon = createImage(new MemoryImageSource(width, heigth, mypixels, 0, width));
	    	g.drawImage(myIcon , (getWidth()/2)-16, PInsets.top, this);
	 	}
	}
 
 
package Clone_Icon_Editor;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.colorchooser.*;
import java.awt.Insets.*;
 
 
public class MyListenerHandler extends MouseAdapter implements WindowListener, ActionListener, MouseListener {
 
	private ImageTry myFrame;
	
	public MyListenerHandler(ImageTry aFrame) {
		myFrame = aFrame;
	}
 
  	public void windowClosing(WindowEvent e) {
    	Window w = e.getWindow();
    	w.setVisible(false);
    	w.dispose();
    	System.exit(0);
  	}
  	
	
	public void windowClosed(WindowEvent we) {}
	public void windowIconified(WindowEvent we) {}
	public void windowDeiconified(WindowEvent we) {}
	public void windowOpened(WindowEvent we) {}
	public void windowDeactivated(WindowEvent we) {}
	public void windowActivated(WindowEvent we) {}
 
	public void actionPerformed(ActionEvent ae)
	{
		if(ae.getSource() instanceof JMenuItem) {
			JMenuItem mi = (JMenuItem) ae.getSource();
			String label = mi.getLabel();
			if (label.equals ("Exit")) {
				System.exit(0);
				return;
			}
			if (label.equals ("New")) {
				System.out.println((JMenuItem) ae.getSource());
				System.out.println("New not yet implemented");
				return;
			}
			if (label.equals ("Open")) {
				System.out.println("Open not yet implemented");
				return;
			}
			if (label.equals ("Save")) {
				System.out.println("Save not yet implemented");
				return;
			}
			if (label.equals ("Save As")) {
				System.out.println("Save As not yet implemented");
				return;
			}
		}
	}	
}
 
 
 

Chris Reck

Posts: 7
Nickname: creck
Registered: Nov, 2002

Re: Wanting general help on my current project Posted: Dec 13, 2002 6:56 AM
Reply to this message Reply
I guess my request must be too hard, or maybe it's just stupid to want to learn to write better code!

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: Wanting general help on my current project Posted: Dec 13, 2002 2:00 PM
Reply to this message Reply
I tried to compile the code but it didn't fly and I don't have time to eyeball it to try and deduce what may be happening.

In such cases as these, a debugger is helpful. You can put a breakpoint in the handler for the menu and one in the handler for the button for starters.

As I said before, I don't subscribe to the technique of the main frame (JFrame in this case) implementing all the handlers, as I think it makes things unnecessarily coupled (and complex). Instead, I prefer a separate listener for each event generator and these are usually inner classes, many of which are also anonymous. You will see examples of this in Sun's Swing Tutorials at http://java.sun.com/docs/books/tutorial/uiswing/.

Flat View: This topic has 4 replies on 1 page
Topic: ANother  try(interesting prob) Previous Topic   Next Topic Topic: Thats Y I luv to play different things with java

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use