FileDocCategorySizeDatePackage
PictureButton.javaAPI DocExample1711Tue Mar 04 01:28:48 GMT 1997None

PictureButton.java

import java.awt.*;
import java.awt.event.*;

class PictureButton extends Component {
	private Image image;
	boolean pressed = false;
    ActionListener actionListener;
	String actionCommand;

	PictureButton(Image image) {
		this.image = image;
		MediaTracker mt = new MediaTracker(this);
		mt.addImage( image, 0 );
		try { mt.waitForAll(); } catch (InterruptedException e) { /* error */ };
		setSize( image.getWidth(null), image.getHeight(null) );
		enableEvents( AWTEvent.MOUSE_EVENT_MASK );
	}
	public void paint( Graphics g ) {
		g.setColor(Color.white);
		int width = getSize().width, height = getSize().height;
		int offset = pressed ? -2 : 0;	// fake depth
		g.drawImage( image, offset, offset, width, height, this );
		g.draw3DRect(0, 0, width-1, height-1, !pressed);
		g.draw3DRect(1, 1, width-3, height-3, !pressed);
	}
	public Dimension getPreferredSize() {
		return getSize();
	}

	public void processEvent( AWTEvent e ) {
		if ( e.getID() == MouseEvent.MOUSE_PRESSED ) {
			pressed = true;
			repaint();
		} else 
		if ( e.getID() == MouseEvent.MOUSE_RELEASED ) {
			pressed = false;
			repaint();
			fireEvent();
		}
		super.processEvent(e);
	}

	public void setActionCommand( String actionCommand ) {
		this.actionCommand = actionCommand;
	}
	public void addActionListener(ActionListener l) {
		actionListener = AWTEventMulticaster.add(actionListener, l);
	}
	public void removeActionListener(ActionListener l) {
		actionListener = AWTEventMulticaster.remove(actionListener, l);
	}
	private void fireEvent() {
		if (actionListener != null) {
			ActionEvent event = new ActionEvent( this, 
								ActionEvent.ACTION_PERFORMED, actionCommand );
			actionListener.actionPerformed( event );
		}
	}
}