MouseListener Help Java

后端 未结 4 956
有刺的猬
有刺的猬 2020-11-29 13:39

I am trying to write a program in Java Swing that outputs a 10 x 10 grid of geometric rectangles filled with randoms colors. However, when the user clicks on one of the rect

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 14:34

    This is what I came up with. Note: I'm still studying Java in University, so this might not be the exact way to do this but it worked when I did it.

    public class ColorGrid extends JPanel implements MouseListener {
    this.addMouseListener(this);
    addMouseListener(this);
    

    That's the first part, the second part is to have these methods in your code.

    public void mouseClicked(MouseEvent arg0) {
    
    }
    
    public void mouseEntered(MouseEvent arg0) {
    
    }
    
    public void mouseExited(MouseEvent arg0) {
    
    }
    
    public void mousePressed(MouseEvent arg0) {
    
    }
    
    public void mouseReleased(MouseEvent arg0) {
    
    }
    

    Then, depending on what you want, (i.e. Mouse clicked or pressed), just type in:

    repaint();
    

    Hope this helped.

提交回复
热议问题