Hello everyone,
I have an 10 x 10 array of JButtons in my battleships project, which represent the sea. I was just wondering how do i find out which button the mouse is over at any given time? I need to know this as i am designing a way to place the ships at the start and it will show which where the ship will be placed when the mouse cursor is over any button. I add a mouse listener to the players board :
board.addMouseM otionListener(n ew MouseMovingHand ler());
board.addMouseL istener(new MouseHandler()) ;
and handle them in the folowing way:
I have an 10 x 10 array of JButtons in my battleships project, which represent the sea. I was just wondering how do i find out which button the mouse is over at any given time? I need to know this as i am designing a way to place the ships at the start and it will show which where the ship will be placed when the mouse cursor is over any button. I add a mouse listener to the players board :
board.addMouseM otionListener(n ew MouseMovingHand ler());
board.addMouseL istener(new MouseHandler()) ;
and handle them in the folowing way:
Code:
private class MouseMovingHandler extends MouseMotionAdapter
{
public void mouseMoved(MouseEvent e)
{
int x = (int)(e.getPoint().getX()/25);
int y = (int)(e.getPoint().getY()/25);
if(x<10 && y<10)
{
lastSelected = battleshipgrid[x][y];
cursorLocation = new Point(x,y);
repaint();
}
}
}
private class MouseHandler extends MouseAdapter
{
public void mousePressed(MouseEvent e)
{
if(e.getModifiers() == e.BUTTON1_MASK)
{
}
if(e.getModifiers() == e.BUTTON3_MASK)
{
vertical = !vertical; //toggle vertical ships placing state
repaint();
}
}
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
if (selectedShipSize!=0 && validPlacement())
{
//Not sure how to paint it correctly?
}
}