Skip to content

Instantly share code, notes, and snippets.

@RustyKnight
Created July 24, 2023 03:09
Show Gist options
  • Save RustyKnight/d5e3622392f9d02ddf72ff1e78513ac4 to your computer and use it in GitHub Desktop.
Save RustyKnight/d5e3622392f9d02ddf72ff1e78513ac4 to your computer and use it in GitHub Desktop.
Simple demonstration of using multiple panels with a single MouseListener
package stackoverflow;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
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 Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new BoardPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class BoardPane extends JPanel {
public BoardPane() {
setLayout(new GridLayout(12, 12));
MouseAdapter mouseHandler = new MouseAdapter() {
private CellPane lastClicked;
@Override
public void mouseClicked(MouseEvent e) {
if (lastClicked != null) {
lastClicked.setBackground(null);
}
if (e.getSource() instanceof CellPane) {
CellPane cell = (CellPane) e.getSource();
cell.setBackground(Color.RED);
lastClicked = cell;
}
}
};
for (int index = 0; index < 12 * 12; index++) {
CellPane cell = new CellPane();
add(cell);
cell.addMouseListener(mouseHandler);
}
}
}
public class CellPane extends JPanel {
public CellPane() {
setBorder(new LineBorder(Color.BLACK));
}
@Override
public Dimension getPreferredSize() {
return new Dimension(40, 40);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment