I have just started learning java swing and I have been trying to create a simple game. The game is similar to minesweeper. A window with a matrix of bottons with just 1 mine. On clicking a button, if it's not a mine, i disable the button and display green color, and if it's a mine i disable the button and display red color. I have displayed the color by setting the button background to the required color. I have done the implementation so far just fine. Next i added a reset button, on clicking which i renable all buttons by using : setEnabled(true).
But for some reason, the button is not getting enabled. I have confirmed that the program flow reaches the code for enabling the button, but i'm not able to find the reason why it is not working.
Here is a test program i wrote with a reset button and 1 button. Same issue. Can anyone point out what I maybe doing wrong?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Test implements ActionListener{
JFrame frame = new JFrame("Mine");
JButton buttons = new JButton();
JButton reset = new JButton("Reset");
Container grid = new Container();
public Test(){
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLayout(new BorderLayout());
frame.add(reset, BorderLayout.NORTH);
reset.addActionListener(this);
buttons = new JButton();
buttons.addActionListener(this);
frame.add(buttons, BorderLayout.CENTER);
}
public static void main(String[] args){
new Test();
}
@Override
public void actionPerformed(ActionEvent event) {
if(event.getSource().equals(reset))
buttons.setEnabled(true);
else{
if(event.getSource()==buttons){
buttons.setBackground(Color.RED);
buttons.setEnabled(false);
}
}
}
}
addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { // first disable all other buttons DownButton. setEnabled(false); LeftButton. setEnabled(false); RightButton. setEnabled(false); System.
addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //If Button is clicked, make the button unclickable if(button == (JButton)e. getSource()) { button. setEnabled(false); } } });
Actually it's getting enabled when you click reset, all you forgot to do was reset the color:
@Override
public void actionPerformed(ActionEvent event) {
if(event.getSource().equals(reset)){
buttons.setEnabled(true);
buttons.setBackground(null);
}else{
if(event.getSource()==buttons){
System.out.println("xxx");
buttons.setBackground(Color.RED);
buttons.setEnabled(false);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With