// how can i obtain info from getRect to forfill my program. I want to create a circle on the grid that's clicked on
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.event.*;
class GridPanel extends JPanel implements MouseListener
{
int numCols;
int numRows;
int numRow = -1;
int numCol = -1;
public void mouseReleased(MouseEvent event)
{
System.out.println("mouse realeased");
}
public void mousePressed(MouseEvent event)
{
System.out.println("Mouse has been pressed");
}
public void mouseClicked(MouseEvent event)
{
int x = event.getX();
int y = event.getY();
System.out.println("the x position is " + x);
System.out.println("the y position is " + y);
System.out.println("the grid possition is: " + numRow + ", " + numCol);
}
public void mouseEntered(MouseEvent event)
{
System.out.println("Mouse has been activated");
}
public void mouseExited(MouseEvent event)
{
System.out.println("You're outside the area");
}
public GridPanel(int nc, int nr)
{
numCols = nc;
numRows = nr;
addMouseListener(this);
}
Rectangle getRect(int thisCol, int thisRow)
{
// if input is out of range, return "null"
if(thisCol <0 || thisRow < 0)
return null;
if(thisCol>=numCols || thisRow>=numRows)
return null;
// otherwise, make and return the Rectangle
int w = getWidth()/numCols;
int h = getHeight()/numRows;
int x = thisCol*w;
int y = thisRow*h;
Rectangle myRect = new Rectangle(x,y,w,h);
return myRect;
}
public void paint(Graphics g)
{
g.setColor(Color.gray);
g.fillRect(0,0,getWidth(), getHeight());
g.setColor(Color.black);
g.setcolor(Color.red);
g.fillOval(x,y,getWidth(),getHeight();
g.setcolor(Color.black);
Graphics2D g2 = (Graphics2D)g;
// we'll use Graphics2D for it's "draw" method -
// neater than the Graphics "drawRect" suppled
// (which you could also use)
for (int i = 0;i<numCols;i++)
{
for(int j = 0;j<numRows;j++)
{
Rectangle r = getRect(i,j);
g2.draw(r);
}
}
}
// copied from the W2MouseEvents for convenience
// (so we can run the program from GridPanel class too!)
public static void main(String[] args)
{
W2MouseEvents w = new W2MouseEvents();
w.setVisible(true);
}
}