[Java2D] How would I go for making buttons?

For better design and flexibility, a UI button should not inherit from a rectangle class, but use it.
A button is not a rectangle but can have the shape of a rectangle.

Alright, I got that down.

The detection still won’t work.

Also, I feel like the tick method should constantly be running. If I only use it when the mouse is moved, there can be a delay so the coordinates aren’t exact.

The tick method should definitely be constantly checked. However if you have a million buttons (which I have a hard time imagining why you would but still) that will be bad. What I had was a Gui class which basically held and array of all of that gui’s buttons. Then in my main class I had a Gui displayedGui that, in the update loop, called displayedGui.drawGui() which drew and updated (tick()) the buttons.

Here’s what I did for my game, though I used a polygon (hexagonal) rather than a rectangle.

  1. put a Rectangle variable in your Button object. No need to extend the Rectangle class. Instantiate the Rectangle in terms relative to the X, Y location of the button on the screen, e.g.:

	Rectangle rectangle = new Rectangle(xLoc, yLoc, width, height);
  1. put a “contains(Point p)” method in your Button object.
	public boolean contains(Point point)
	{
		if (rectangle.contains(point)) return true;
		return false;
	}
  1. put a “hover” boolean in your Button object. I’d probably make this instance variable ‘volatile’.

  2. have your MouseMotionListener include the following code:

	public void mouseMoved(MouseEvent arg0) 
	{
		button.setHover(button.contains(arg0.getPoint());
	}

You may have to do same for mouseDragged(). This should keep the state of the button current.

  1. have the update() or render() method for the button look at the “hover” boolean before deciding what to do or draw.

Maybe a setup like the above will work for your game.

Hey. I did a whole UI system I did in java2D if you want to look. Here is a just the button class.

http://www.java-gaming.org/?action=pastebin&id=709

Stop writing code for a second and think of what a button needs.

Is the button active? can it test for events?

Is the mouse over the button?

Is the mouse pressed?

Is the mouse released when it is still over the button?

How do we know when the mouse is over the button?

You probably already thought of these but now think of how you will code them. Once you have an idea, hop to it and make some buttons.


Rectangle rect = new Rectangle(0, 0, 50, 50);

if (mx > rect.x && my > rect.y && mx < (rect.x + rect.width) && my < (rect.y + rect.height)) {
do stuff
}

You do realize that your example re-invents the wheel. The Rectangle’s contains method does pretty much the same thing.


Rectangle rect = new Rectangle(0, 0, 50, 50);

if (rect.contains(mx, my) {
    // do stuff
}

Other than that, the checks should be “>=” and “<=” otherwise you miss intersections with the border pixels.