Mercurial > hg > ristipolku
diff game/IDMButton.java @ 49:e6da5c71be28
Add more code to IDM widgets, do preliminary work for integrating them.
author | Matti Hamalainen <ccr@tnsp.org> |
---|---|
date | Tue, 22 Feb 2011 10:52:08 +0200 |
parents | |
children | 496e616ff09d |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/game/IDMButton.java Tue Feb 22 10:52:08 2011 +0200 @@ -0,0 +1,116 @@ +/* + * 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; + Point pos; + Font font; + FontMetrics metrics; + String text; + + public IDMButton(Point pos, int keyCode, Font font, String text) + { + loadImages(); + this.pos = pos; + this.font = font; + this.keyCode = keyCode; + this.text = text; + state = State.NORMAL; + } + + public IDMButton(int x, int y, int keyCode, Font font, String text) + { + this(new Point(x, y), keyCode, font, text); + } + + public void move(Point pos) + { + this.pos = pos; + } + + public void move(int x, int y) + { + this.pos = new Point(x, y); + } + + private static void loadImages() + { + 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 paint(Graphics2D g) + { + BufferedImage img; + int xoffs, yoffs; + + if (state == State.PRESSED) + { + img = imgPressed; + xoffs = yoffs = 15; + } + else + { + xoffs = yoffs = 0; + img = imgUp; + } + + if (metrics == null) + metrics = g.getFontMetrics(font); + + int textWidth = metrics.stringWidth(text); + g.drawImage(img, pos.x + xoffs, pos.y + yoffs, null); + + g.setFont(font); + g.setPaint(Color.black); + g.drawString(text, + pos.x + xoffs + (img.getWidth() - textWidth) / 2, + pos.y + yoffs + (img.getHeight() - metrics.getHeight() / 2) / 2); + } + + public boolean contains(Point where) + { + return (where.x >= pos.x && where.y >= pos.y && + where.x < pos.x + imgUp.getWidth() && + where.y < pos.y + imgUp.getHeight()); + } + + public void mousePressed(MouseEvent e) + { + state = State.PRESSED; + } + + public void mouseReleased(MouseEvent e) + { + super.mouseReleased(e); + state = State.NORMAL; + } + + public void clicked() + { + } +}