user4332856
user4332856

Reputation:

How to use JPanel mouse listener

I have a JPanel that is painted as a rectangle with a specific color. In my JPanel class in the constructor I accept a color and text. The text is the name of the color.

I am trying to make a mouse listener that will get the color of the jpanel after a person clicks on the jpanel. Any suggestions?

I did store the color in a variable but I have multiple color panels so when I click on one panel for example a yellow one I want to make a check to see if the panel clicked is a certain color and if so then something will happen but I'm having trouble figuring out how to get the JPanel source from the mouse listener.

Upvotes: 0

Views: 8377

Answers (2)

Matt Coubrough
Matt Coubrough

Reputation: 3829

This is how to get the background Color of the JPanel that was clicked on via a mouse handler (assuming the mouse event handler is attached to the JPanel you want to get the Color of):

private void mouseClicked(java.awt.event.MouseEvent evt) {

    JPanel panel = (JPanel)evt.getSource();
    Color c = panel.getBackground();
    System.out.println("color: " + c.toString());

}

Explanation:

In the mouseClicked method the MouseEvent argument evt is an Object which contains a reference to the "source" of the mouse event (ie. the Object that had the click event handler attached to it). If you know you've only added the event handler to JPanel objects, then you can safely cast the result of getSource() to a JPanel instance as is done in the example code.

Then you can perform operations on the JPanel source of the click event such as getBackground().

Upvotes: 2

Shadi
Shadi

Reputation: 92

here is a complete class showing how to print color name the JPanel is clicked is tested the code

class RectanglePanel extends JPanel implements MouseListener {

String colorName;
Color color;

public RectanglePanel(String text, Color c) {
    this.colorName = text;
    this.color = c;
    super.addMouseListener(this);

}

@Override
public void paint(Graphics g) {

    super.paint(g); //To change body of generated methods, choose Tools | Templates.
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(color);
    g2.fillRect(50, 50, 100, 100);
}

@Override
public void mouseClicked(MouseEvent e) {
   System.out.println(colorName);
}

@Override
public void mousePressed(MouseEvent e) {

}

@Override
public void mouseReleased(MouseEvent e) {

}

@Override
public void mouseEntered(MouseEvent e) {

}

@Override
public void mouseExited(MouseEvent e) {

}

}

Upvotes: 1

Related Questions