Skip to content

Instantly share code, notes, and snippets.

@cemremengu
Created January 3, 2012 17:03
Show Gist options
  • Save cemremengu/1555805 to your computer and use it in GitHub Desktop.
Save cemremengu/1555805 to your computer and use it in GitHub Desktop.
Code to create a grid of clickable panels in SWING
public static class GridPane extends JPanel {
public GridPane(int row, int col) {
int count = 0 ; // use to give a name to each box so that you can refer to them later
setLayout(new GridLayout(row, col));
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
for (int i = 1; i <= (row * col); i++) {
JPanel pan = new JPanel();
pan.setEnabled(true);
pan.setBackground(Color.WHITE);
pan.setPreferredSize(new Dimension(3, 3));
pan.setBorder(BorderFactory.createLineBorder(Color.BLACK));
pan.addMouseListener(new BoxListener()); // add a mouse listener to make the panels clickable
pan.setName(count+"");
++count;
add(pan);
}
}
}
//Class that defines what happens (i.e: the color changes) when a panel is clicked
public static class BoxListener extends MouseAdapter
{
public void mouseClicked(MouseEvent me)
{
JPanel clickedBox =(JPanel)me.getSource(); // get the reference to the box that was clicked
// insert here the code defining what happens when a grid is clicked
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment