Setting Icons and checking for matches
I'm having some trouble figuring out how to set and check for matches in my program. It is a 4x4 grid matching game. Any help is appreciated.
Code :
public class MemoryGUI extends JPanel
{
JPanel icons;
JPanel score;
//instance variables
private JPanel symbolPanel, turnPanel;
private IconHolder icons;
private JLabel turnLabel;
private JTextField turnField;
public MemoryGUI()
{
JPanel p = new JPanel("*");
pane.add(p);
p.setLayout(new GridLayout(4,4));
for (int i = 0; i < 16; i++)
JButton button = icons.buttonAtIndex(i);
p.add(score);
score.addMouseListener(this);
// instantiate all above components
JPanel symbolPanel = new JPanel();
JPanel turnPanel = new JPanel();
turnLabel = new JLabel("Turns left: ");
turnField = new JTextField(4);
// set button sizes and listeners
icons.buttonAtIndex(0).setPreferredSize(new Dimension(100, 100));
for(int i = 0; i < 16; i++){
icons.buttonAtIndex(i).addActionListener(new FlipListener());
}
// set panel layouts
this.setLayout(new BoxLayout(this, BOXLAYOUT.Y_AXIS));
symbolPanel.setLayout(new GridLayout(4, 4));
// you may set display of buttons using Font class and setFont methods, use for loop as done above for setting font
b.setFont(new Font("sansserif", Font.BOLD, 32));
// add components to the panel with the symbol buttons
for(int i = 0; i < 16; i++){
symbolPanel.add(icons.buttonAtIndex(i));
}
// add components to panel with turn information
turnPanel.add(turnLabel);
turnPanel.add(turnField);
this.add(symbolPanel);
this.add(turnPanel);
//set the text of turnField (JTextField)
textField = new JTextField(20);
}
private class FlipListener implements ActionListener{
public void actionPerformed(ActionEvent event){
// determine which button has been pressed
for(int i = 0; i < 16; i++){
icons.buttonAtIndex(i).addActionListener(new FlipListener(i));
}
// if this is first icon, set as first
//otherwise, set as second and check for match
// (within else) check for match, if so reset flips and set both to complete
// if not matched, reduce turns by 1 and unflip
if(false)
{
i--;
}
// refresh turns and end if turns is 0
}
}
}
Re: Setting Icons and checking for matches
I am guessing the problem has to do with FlipListener? First, you do not need to add the listener again (the for loop in the listener). You can retrieve the source of the event using the ActionEvent getSource, and then use this object to do what you need
Code :
public void actionPerformed(ActionEvent e){
Object o = e.getSource();
if ( o instanceof JButton ){
JButton button = (JButton)o;//the button that was clicked
///do what you need with the button.
}
}
Hope this helps...