Mercurial > hg > ristipolku
diff game/IDMButton.java @ 162:e8eeac403e5f
Backed out changeset fb33d3796942
author | Matti Hamalainen <ccr@tnsp.org> |
---|---|
date | Thu, 01 Dec 2016 14:33:25 +0200 |
parents | src/IDMButton.java@fb33d3796942 |
children | dda7152d2402 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/game/IDMButton.java Thu Dec 01 14:33:25 2016 +0200 @@ -0,0 +1,134 @@ +/* + * Ristipolku IDM button widget + * (C) Copyright 2011 Matti 'ccr' Hämäläinen <ccr@tnsp.org> + */ +package game; + +import java.awt.*; +import java.awt.event.*; +import java.awt.image.*; +import java.awt.geom.*; +import javax.imageio.*; +import java.io.*; + + +public class IDMButton extends IDMWidget +{ + enum State { FOCUSED, PRESSED, NORMAL } + State state; + static BufferedImage imgUp, imgPressed; + Font font; + FontMetrics metrics; + String text; + boolean active; + + public IDMButton(IDMPoint pos, int keyCode, Font font, String text) + { + super(pos); + loadImages(); + setSize(imgUp.getWidth(), imgUp.getHeight()); + + this.font = font; + this.keyCode = keyCode; + this.text = text; + + state = State.NORMAL; + active = false; + } + + public IDMButton(float x, float y, int keyCode, Font font, String text) + { + this(new IDMPoint(x, y), keyCode, font, text); + } + + private static void loadImages() + { + if (imgUp != null && imgPressed != null) + return; + + try + { + ResourceLoader res = new ResourceLoader("graphics/button1_up.png"); + imgUp = ImageIO.read(res.getStream()); + + res = new ResourceLoader("graphics/button1_down.png"); + imgPressed = ImageIO.read(res.getStream()); + } + catch (IOException e) + { + System.out.print(e.getMessage()); + } + } + + public void scale() + { + } + + public void paint(Graphics2D g) + { + BufferedImage img; + int xoffs, yoffs; + + if (state == State.PRESSED) + { + img = imgPressed; + xoffs = yoffs = 5; + } + else + { + xoffs = yoffs = 0; + img = imgUp; + } + + if (metrics == null) + metrics = g.getFontMetrics(font); + + int textWidth = metrics.stringWidth(text); + g.drawImage(img, getScaledX() + xoffs, getScaledY() + yoffs, null); + + g.setFont(font); + g.setPaint(Color.black); + g.drawString(text, + getScaledX() + xoffs + (getScaledWidth() - textWidth) / 2, + getScaledY() + yoffs + getScaledHeight() / 2); + } + + + public boolean mousePressed(MouseEvent e) + { + state = State.PRESSED; + active = true; + return true; + } + + public boolean mouseReleased(MouseEvent e) + { + boolean oldActive = active; + super.mouseReleased(e); + state = State.NORMAL; + active = false; + return oldActive; + } + + public boolean mouseEntered(MouseEvent e) + { + if (active) + { + state = State.PRESSED; + return true; + } + else + return false; + } + + public boolean mouseExited(MouseEvent e) + { + if (active) + { + state = State.NORMAL; + return true; + } + else + return false; + } +}