Is there a way to create a method in java to get what/information on what JPanel was clicked on?

StackOverflow https://stackoverflow.com/questions/22257461

Domanda

For example: There are two panels, each with a different name, but made by the same constructor. You click, with a mouselistener, on one. I want it to display information from the panel, such as the name. However, the mouselistener is located in the constructor. Any ideas or workarounds. In c++ I could pass it as reference but I don't know what to do in Java.

È stato utile?

Soluzione

The MouseEvent of each method of a MouseListener has a reference to the listened-to component, the getSource() method. Use it and you'll have your information. For example,

@Override
public void mousePressed(MouseEvent mEvt) {
   Component theCurrentPressedComponent = (Component) mEvt.getSource();

   // now you can use your variable above, although you probably need to 
   // cast it to something else, such as a JPanel

   // e.g., if it has been assigned a name String via setName(...)
   System.out.println(theCurrentPressedComponent.getName()); 
}

If you need more specific advice, consider creating and posting a minimal example program.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top