Below is what im trying to implement but its giving error on the line mentioned ; this is because the function doesnot get which Component.getName() is of ...
String name=new String();
mntmOneToOne.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent arg0)
{
String name=new String();
int count = arg0.getClickCount();
if (count == 1)
{
Component panel = (Component) arg0.getSource();
System.out.println(panel.getName());
}
}
});
Get the clicked object via your MouseEvent's getSource()
method. Then call its getName()
method.
mntmOneToOne.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent mouseEvent) {
int count = mouseEvent.getClickCount();
if (count == 1) {
Component panel = (Component)mouseEvent.getSource();
name = panel.getName();
}
}
});
See this example :
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class PanelTest extends JFrame {
List<JPanel> panels;
public PanelTest(){
panels = new ArrayList<>();
setLayout(new GridLayout(2,3));
Color [] color = {Color.white,Color.black,Color.blue,Color.red,Color.orange,Color.gray};
for(int i = 0 ; i < 6;i++)
{
panels.add(new JPanel());
panels.get(i).setName("Panel "+i);
panels.get(i).addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent ev){
//JPanel p = (JPanel)ev.getSource();
System.out.println(((JPanel)ev.getSource()).getName());
}
});
panels.get(i).setBackground(color[i]);
getContentPane().add(panels.get(i));
}
setVisible(true);
setDefaultCloseOperation(3);
setSize(400,400);
}
public static void main(String...args){
new PanelTest();
}
}