import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
class AbacusPanel extends JPanel implements MouseListener
{
AbacusModel myAbacus;
int numCols;
int numRows;
int button;
public static void main(String[] args)
{
AbacusFrame w = new AbacusFrame();
w.setVisible(true);
}
public AbacusPanel(int nc, int nr)
{
numCols = nc;
numRows = nr;
addMouseListener(this);
myAbacus = new AbacusModel(numCols,numRows);
}
int getCol(int x)
{
return x*numCols/getWidth();
}
int getRow(int y)
{
return y*numRows/getHeight();
}
public void mouseReleased(MouseEvent event)
{
}
public void mousePressed(MouseEvent event)
{
}
public void mouseClicked(MouseEvent event)
{
int thisCol = getCol(event.getX());
int thisRow = getRow(event.getY());
System.out.println
("you clicked in column " + thisCol);
button = event.getButton();
if (button ==1)
{
myAbacus.addCounter(getCol(event.getX()));
}
if (button ==3)
{
myAbacus.removeCounter(getCol(event.getX()));
}
System.out.println("peg selected="+getCol(event.getX())+ " and Counter contained="+myAbacus.getNumCounters(getCol(event.getX())));
repaint();
}
public void mouseEntered(MouseEvent event)
{
}
public void mouseExited(MouseEvent event)
{
}
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);
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++)
{
g2.draw(getRect(i,j));
}
}
for(int thisRow = 0;thisRow<numRows;thisRow++)
{
for(int thisCol = 0;thisCol<numCols;thisCol++)
{
}
}
}
}