import java.awt.AWTEvent; import java.awt.AWTEventMulticaster; import java.awt.event.ActionListener; import java.awt.Component; import java.awt.Graphics; import java.awt.Image; import java.awt.event.*; /** * a lightweight button which holds 3 image states, 1 for no-focus, 1 for focus and 1 for pressed. */ public class ImageButton extends ImageLabel { /** * the 'focused' image */ Image imageFocus = null; /** * the 'pressed' image */ Image imagePress = null; /** * button state */ boolean press; /** * mouse/pointer state (inside this button's boundaries) */ boolean inside; /** * used for posting action events to listeners */ ActionListener actionListener; /** * construct a new ImageButton, and enable Mouse events for this component */ public ImageButton() { super(); this.enableEvents(AWTEvent.MOUSE_EVENT_MASK); } /** * set the 'focused' image */ public void setImageFocus(String imageFilename) throws InterruptedException { imageFocus = Utils.getImage(imageFilename); } /** * set the 'pressed' image */ public void setImagePress(String imageFilename) throws InterruptedException { imagePress = Utils.getImage(imageFilename); } /** * draw the image onto the Graphics context based upon the state variables 'inside' and 'press'. */ public void paint(Graphics g) { if (inside && !press && imageFocus != null) { g.drawImage(imageFocus,getLocation().x,getLocation().y,getSize().width,getSize().height,null); } else if (press) { g.drawImage(imagePress,getLocation().x,getLocation().y,getSize().width,getSize().height,null); } else { g.drawImage(image,getLocation().x,getLocation().y,getSize().width,getSize().height,null); } } /** * set the specified listener for this component */ public void addActionListener(ActionListener listener) { actionListener = AWTEventMulticaster.add(actionListener, listener); enableEvents(AWTEvent.MOUSE_EVENT_MASK); } /** * remove the specified listener */ public void removeActionListener(ActionListener listener) { actionListener = AWTEventMulticaster.remove(actionListener, listener); } /** * handler for mouse events */ public void processMouseEvent(MouseEvent e) { // the button was clicked if (e.getID() == MouseEvent.MOUSE_PRESSED) { press = true; repaint(); // notify listeners if(actionListener != null) { actionListener.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "")); } } // end of button press else if(e.getID() == MouseEvent.MOUSE_RELEASED) { press = false; repaint(); } // the mouse has entered the boundaries of the button else if (e.getID() == MouseEvent.MOUSE_ENTERED) { inside = true; repaint(); } // the mouse has exited the boundaries of the button else if (e.getID() == MouseEvent.MOUSE_EXITED) { inside = false; repaint(); } // Pass unhandled events to superclass. super.processMouseEvent(e); } }