OK so I've got a JPanel with a GridLayout. Each cell of the grid then contains another JPanel.
What I'd like to be able to do is have a listener on the "underneath" JPanel which then tells me which of the "overlayed" JPanels was clicked - so I can react to it and the surrounding ones, without making the covering JPanels aware of their position (they change!!)
Is there a way of doing this - similar to Determine clicked JPanel component in the MouseListener. Event handling but I couldn't find a way of grabbing the component on top.
I could probably grab the co-oridnates and work it out using that info - but I'd rather not!!
Any help/pointers/tips would be appreciated :D
Do the same thing but use getParent()
on the source. Or you can search up the hierarchy if it is deeper, even some helper methods for that:
javax.swing.SwingUtilities.getAncestorOfClass
and getAncestorNamed
use putClientProperty
/ getClientProperty
, nothing simplest around ..., you can put endless numbers of ClientProperty to the one Object
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
public class MyGridLayout {
public MyGridLayout() {
JPanel bPanel = new JPanel();
bPanel.setLayout(new GridLayout(10, 10, 2, 2));
for (int row = 0; row < 10; row++) {
for (int col = 0; col < 10; col++) {
JPanel b = new JPanel();
System.out.println("(" + row + ", " + col + ")");
b.putClientProperty("column", row);
b.putClientProperty("row", col);
b.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JPanel btn = (JPanel) e.getSource();
System.out.println("clicked column " + btn.getClientProperty("column")
+ ", row " + btn.getClientProperty("row"));
}
});
b.setBorder(new LineBorder(Color.blue, 1));
bPanel.add(b);
}
}
JFrame frame = new JFrame("PutClientProperty Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(bPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyGridLayout myGridLayout = new MyGridLayout();
}
});
}
}