I have been looking over past exam papers for revision for an upcoming uni exam for Java and one of the questions was, asking for code to add to a given abacus program to make the grid display 3 counters in each column of a 10x6. e.g. as soon as the JPanel opens.
So far the current program enables the user to click in each column and add counters to each column, so you can do this manually but it is not the way to do it as when its run there are no counters present in the abacus grid. I am unsure as to how i can complete this correctly although i am sure it would likely be a for loop?? I know nothing about the program itself or even what everything does??
The program is in 3 classes: Test2Model, Test2Frame and Test2Panel but the panel class is the one i believe i need to add code to? Please can anybody help me understand this? This is merely revision but would be hugely helpful for me. Thanks, the Test2Panel class is included below....
class Test2Panel extends JPanel implements MouseListener
{
Test2Model model;
public Test2Panel()
{
addMouseListener(this);
int test_num_pegs = 10;
int test_max_counters = 6;
model = new Test2Model(test_num_pegs, test_max_counters);
}
Rectangle getRect(int i,int j)
{
if(i<0 || j<0 || i>=model.getNumPegs() || j >=model.getMaxCounters())
return null;
int w = getWidth()/model.getNumPegs();
int h = getHeight()/model.getMaxCounters();
System.out.println("getRect: w is " + w + " and h is " + h);
int x = i*w;
int y = j*h;
Rectangle r = new Rectangle(x,y,w,h);
return r;
}
int getColumn(int x)
{
return x*model.getNumPegs()/getWidth();
}
public void mouseReleased(MouseEvent event)
{
}
public void mousePressed(MouseEvent event)
{
}
public void mouseClicked(MouseEvent event)
{
int b = event.getButton();
int col = getColumn(event.getX());
if(b==1)
{
model.addCounter(col);
}
if (b==3)
{
model.removeCounter(col);
}
repaint();
}
public void mouseEntered(MouseEvent event)
{
}
public void mouseExited(MouseEvent event)
{
}
public void paint(Graphics g)
{
g.setColor(Color.white);
int w = getWidth();
int h = getHeight();
g.fillRect(0,0,w,h);
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.black);
for(int j = 0;j<model.getMaxCounters();j++)
{
for(int i = 0;i<model.getNumPegs();i++)
{
Rectangle r = getRect(i,j);
g.drawRect(r.x,r.y,r.width, r.height);
}
}
int max_counters = model.getMaxCounters();
for(int i = 0;i<model.getNumPegs();i++)
{
int num_pegs = model.getNumCounters(i);
for(int j = 0;j<num_pegs;j++)
{
Rectangle r = getRect(i,max_counters-j-1);
g2.setColor(Color.red);
g2.fillOval(r.x,r.y,r.width,r.height);
g2.setColor(Color.black);
g2.drawOval(r.x,r.y,r.width,r.height);
}
}
}
// copied from the W2MouseEvents for convenience
// (so we can run the program from Test2Panel class too!)
public static void main(String[] args)
{
Test2Frame w = new Test2Frame();
w.setVisible(true);
}
}