Fall 2006, David Matuszek
Three Musketeers is played on a 5x5 grid. You probably don't want 25 almost identical listeners, right? In a case like this, it's much better to have one listener. But that listener needs to know which square of the grid was actually clicked on. In the current game, you might want row and column.
You might populate your 5x5 grid with various types of
example, buttons, panels, or labels in panels. Or maybe something else. Here
are three quick example programs to show off the basic techniques.
JButtons. However, I want to ask the button what row and column it is in, and a plain old JButton doesn't know that. So I wrote a class
JButtonwith row and column information. (You can also use this trick with other component types, such as
JLabels don't respond to mouse clicks, so I put each
JPanel, and added a listener to each
JPanel. In this example, I just get the text of the
JLabel, but it might be more useful to extend the
JPanelwith row and column information.
LabelArray.javaby removing the labels (and adding color information). All the same comments apply.