Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
Solved

# Make a grid with selectable squares

Posted on 2001-08-13
Medium Priority
934 Views
Last Modified: 2008-03-06
Hi, i'm quite a newbie java programmer, and i got a quite simple question (with a long answer)... I got an idee to make a turn based strategie game (already made an rpg), but i need a grid with about 25x25 squares, and every square needs some properties. I tried some newbie stuff but i'm afraight i'll have to use some kind of difficult math line that i have never heard of.
So if you could just explain me how i have to tell my program over wich square my mouse is when i press it, i should be able to continue on my own. I Painted a grid and placed some buttons above it already, but that's all i have done so far...
It may take some of your time so that's why i filled in 150 points.

tnx,
Vincent Sels
0
Question by:Vincent_Sels
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• Learn & ask questions
• 5
• 2
8 Comments

LVL 1

Accepted Solution

lawrie earned 450 total points
ID: 6381247
The most flexible way would be to make a 'Cell' class, that takes care of each square. This could include drawing it (assuming later it will be more sophisticated than just a square) and knowing what size it is .. my suggestion is to have an java.awt.Rectangle class for each Cell that defines its location and size.

Then on your mouse click events, you will get the x & y coord of your mouse (event.getX() & event.getY()) and just test to see if you are in each Cell with Rectangle.contains(new Point(x, y))

This would be best if the board will not be just a big grid (eg some cells are different widths). If it will be (make sure this won't change later) perhaps just some maths to check which cell the x & y of the mouse click event occurred in.

If all cells the same, something like this would work
clickedColumn = x / (boardWidth / numColumns);
clickedRow = y / (boardHeight / numRows);

Hope this helps
0

Author Comment

ID: 6381347
tnx i'll try some more and let you know if i was able to continue...
0

Author Comment

ID: 6381658
OK this is how i'm gonna do it: subclass rectangle so i can add extra options, add all those 'rects' (in an array field) to the applet, and draw lines around them. Than i'll just use the contains method; that should do it...

but i encountered a problem... see for yourself:

extracts from class WorldMap:

Rect[] field = new Rect[400];

void addRects()
{
for (int y=0; y<20; y++)
{
for (int x=0; x<20; x++)
{
field[(y*20)+x] = new Rect(3+ x*25, 30+ y*25, 25, 25); //here's the problem...
field[(y*20)+x].nr = y*20 + x;
}
}
}

public class Rect extends java.awt.Rectangle
{
stuff
}

when I try to create a new rect the compiler sais he cant find constructor Rect(int, int, int, int) in class Rect... but there certainly is one in class Rectangle. Do I do something wrong ? Do I have to make a new constructor ?
And btw, will it work that way or would you do it completely different ?
0

LVL 1

Expert Comment

ID: 6381842
If you have no constructors for Rect, will only get the default constructor, and hence the default Rectangle constructor. add the following to Rect, and it should fix things

public Rect(int x, int y, int width, int height)
{
super(x, y, width, height);
}

What you propose would be the most generic way of doing things, offering flexibility to have different sizes or shapes later, so it would be the method I would go for personally. The only drawback would be having to search through all 400 cells to find a click, which will be a bit slower, but shouldn't have a great impact as long as you don't do many lookups unnecessarily (eg don't find it again if you have already found the required cell and could save which one it was instead of recalculating)
0

LVL 92

Expert Comment

ID: 6382453
If you simply make each of your cells a component then you can add mouse motion listeners to each cell, removing the need for any calculations to work out which cell the mouse is over.
0

Author Comment

ID: 6383602
Tnx for your replies...

Lawrie, I used that constructor and now both classes compile but unfortunately the whole thing won't work... When, for example, I try to display the string 'it worked' in field[200] (the rect in the middle), and draw a line from field[1].x, field[1].y to field[399].x, field[399].y nothing at all shows up ! I checked my formulas (field[(y*20)+x] = new Rect(3+ x*25, 30+ y*25, 25, 25);) to place the rectangles and I just can't find any mistakes :/
(the +3 or +30 i add to the place were the rectangle should be construted, is because it has to start at point (3,30) in stead of 0,0. With a canvas I would probably be able to avoid this but I just couldn't get the canvas in the right position so I decided to do it without...)

regards,
BlackDeath
0

Author Comment

ID: 6383991
Ok i'll just give the whole program... find out what's wrong because i really don't see the problem. I included some actions to trace the error but I don't see why it happens there.

import java.awt.*;
import java.lang.Math;

public class WorldMap extends java.applet.Applet
{

/*////////////////////////////////////////*/
/*/               Variables              /*/
/*////////////////////////////////////////*/

/******************\
* LAYOUT VARIABLES *
\******************/

Panel buttons = new Panel();
Button b_endTurn = new Button("END TURN");
Button b_money = new Button("money");
Button b_resources = new Button ("resources");
Button b_production = new Button ("production");
Button b_research = new Button ("research");
Button b_bases = new Button ("bases");
Button b_groups = new Button ("groups");

/*********************\
* SELECTION VARIABLES *
\*********************/

Rect[] field = new Rect[400];
Point mousePos;
boolean groupSelected;

/*****************\
* OTHER VARIABLES *
\*****************/

boolean fieldAdded;

/*////////////////////////////////////////*/
/*/                Functions             /*/
/*////////////////////////////////////////*/

void addRects()
{
for (int y=0; y<20; y++)
{
for (int x=0; x<20; x++)
{
field[(y*20)+x] = new Rect(3+ x*25, 30+ y*25, 25, 25);
field[(y*20)+x].nr = y*20 + x;
}
}
fieldAdded = true;
}

public void init()
{
/******************\
* ARRANGING LAYOUT *
\******************/

buttons.setLayout(new GridLayout(1, 7, 0, 0));
buttons.add(b_endTurn);
buttons.add(b_money);
buttons.add(b_resources);
buttons.add(b_production);
buttons.add(b_research);
buttons.add(b_bases);
buttons.add(b_groups);
add(buttons);

addRects();
}

public void paint(Graphics g)
{
/**************\
* DRAWING GRID *
\**************/

///////////////////////TEST///////////////////////
if(fieldAdded)
g.drawString("Field added", 100, 100);
else
g.drawString("Field not added", 100, 100);
//////////////////////////////////////////////////

g.setColor(Color.black);
g.drawLine(3, 30, 503, 30);
g.drawLine(3, 30, 3, 530);
g.drawLine(503, 30, 503, 530);
g.drawLine(3, 530, 503, 530);

///////////////////////TEST///////////////////////
if (field[1].x != 0 && field[1].y != 0 && field[499].x != 0 && field[499].y != 0)
g.drawString("field[1].x = " + field[1].x + ". field[1].y = " + field[1].y + ". field[499].x = " +
field[499].x + ". field[499].y = " + field[499].y + ".", 50, 50);
else
g.drawString("1 or more values = 0...", 50, 50);
//////////////////////////////////////////////////
}

public boolean mouseDown(Event evt, int x, int y)
{

return true;
}
}

import java.awt.Rectangle;

public class Rect extends java.awt.Rectangle
{
Rect(int x, int y, int widht, int height)
{
super();
}

int nr;

boolean explored;

boolean isSite;
boolean isResource;
boolean isMountain;
boolean isForest;
boolean groupPresent;

int sitePlace;
int resPerTurn;
int resTurns;
int numSite;
int numResource;
int numGroup;
}
0

Author Comment

ID: 6385882
Ok I got a lot further now; I have the cells and they can contain new properties, they are selectable and easy editable... just what I wanted.

I'll accept on of your answers lawrie, because you first mentioned the rectangle system... thanks again !
If I encounter other problems I'll post them here to.
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
###### Suggested Courses
Course of the Month9 days, 2 hours left to enroll

#### 604 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.