Question

private class Board extends JPanel {
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        int w=getWidth();
        int h=getHeight();
        Graphics2D g2d = (Graphics2D) g;

The following code draws the grid:

        g2d.setPaint(Color.WHITE);
        g2d.fill(new Rectangle2D.Double(0, 0, w, h));
        g2d.setPaint(Color.BLACK);
        g2d.setStroke(new BasicStroke(4));
        g2d.draw(new Line2D.Double(0, h/3, w, h/3));
        g2d.draw(new Line2D.Double(0, h*2/3, w, h*2/3));
        g2d.draw(new Line2D.Double(w/3, 0, w/3, h));
        g2d.draw(new Line2D.Double(w*2/3, 0, w*2/3, h));

The following code draws circles and xs by visiting elements in the array List:

        for(Shape shape : shapes){
            g2d.setPaint(Color.BLUE);
            g2d.draw(shape);
        }
    }
}

public void addMouseListener(MouseListener ml){

    // HOW CAN I ADD A MOUSE LISTENER HERE? 

}
Was it helpful?

Solution

You can create a class that implements the MouseListener interface as so:

   public class CustomMouseListener implements MouseListener{

      public void mouseClicked(MouseEvent e) {
         statusLabel.setText("Mouse Clicked: ("+e.getX()+", "+e.getY() +")");
      }

      public void mousePressed(MouseEvent e) {
      }

      public void mouseReleased(MouseEvent e) {
      }

      public void mouseEntered(MouseEvent e) {
      }

      public void mouseExited(MouseEvent e) {
      }
   }

You want define each of those methods based on the action the method represents (which are self explanatory). The MouseEvent object will have all the info you need related to the mouse (ex. x and y position of mouse).

Now you want to add this new MouseListener to a JPanel (which in this case is your Board class):

  //JPanel panel = new JPanel();      
  Board panel = new Board();
  panel.addMouseListener(new CustomMouseListener());

Source

OTHER TIPS

Create your class which implements MouseListener, and pass it by addMouseListener method... ?

http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html

you need to make the class implements MouseListener. you need to add the unimplements methods. and here you go :) you got few new methods:

public void mouseClicked(MouseEvent e) // method calls when mouse clicked
public void mousePressed(MouseEvent e) // method calls when mouse pressed
public void mouseReleased(MouseEvent e) // method calls when mouse relesed
public void mouseEntered(MouseEvent e) // method calls when the mouse curser getting into the component's geometry
public void mouseExited(MouseEvent e) // method calls when mouse curser getting out of the component's geometry

hope it helped you :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top