[Solved] I am Using Jbuttons on Jpanel and addding this jpanel on Jlist. I am using addMouseListener on list. Not able to get click on Button on Jpanel


item.getComponentAt(p);

What is the point of that statement? How can you tell if the code worked or not since you never assign the result of the method to a variable?

Turns out that because the panel is not really a component displayed on the frame you can’t just do as I originally suggested.

If you add code like:

JPanel item = (JPanel) target.getModel().getElementAt(index);
System.out.println( item.getBounds() );

You get output like:

java.awt.Rectangle[x=-487,y=-36,width=0,height=0]

Which doesn’t make any sense.

So, I changed the logic to assign the bounds to the panel as if it was displayed on the JList:

item.setBounds(target.getCellBounds(index, index));

Now, I get output like:

java.awt.Rectangle[x=0,y=54,width=487,height=36]

Which does make more sense. However, that still doesn’t help because if you add:

Point p = SwingUtilities.convertPoint(target,me.getPoint(),item);
System.out.println( p );

You get something like:

java.awt.Point[x=834,y=166]

The conversion of the point does do what I expected.

So, I decided to convert the point manually:

int y = me.getY() - item.getBounds().y;
Point p = new Point(me.getX(), y);

Putting it all together you get something like:

JList target = (JList) me.getSource();
int index = target.locationToIndex(me.getPoint());
JPanel item = (JPanel) target.getModel().getElementAt(index);
item.setBounds(target.getCellBounds(index, index));
int y = me.getY() - item.getBounds().y;
Point p = new Point(me.getX(), y);
JButton button = (JButton)item.getComponentAt(p);
System.out.println(button.getText());

And you get the text of the button when you click on it.

Of course, you get Exceptions if you click anywhere else. I’ll leave it up to you do handle the Exception logic.

Note, I see your latest question is about adding labels and a panel to a frame. It is a much better approach to use real components as you can add ActionListeners to your buttons.

1

solved I am Using Jbuttons on Jpanel and addding this jpanel on Jlist. I am using addMouseListener on list. Not able to get click on Button on Jpanel