How to compare all the buttons? Or check if all are disabled? - java

I'm trying to do a memory game using "cards" all works fine but I need to know when the user win the game to display a message but I can't figure out how to do that? How can I check using a condition if all the buttons are .setEnabled(false)? Or should I compare all the buttons using a loop?
I hope you can help me.

Since you have cartas as an array. You should just iterate through a loop to see if all cards are set to false.
for(int x =0; x< cartas.length;x++)
{
if(cartas[x].isEnabled()) //enabled
{
break; //a button is still enabled so cancel loop
}
else if(x == cartas.length-1&& !cartas[x].isEnabled())
{
//All cards have been disabled. Do Something.
}
}
Therefore, the method
isEnabled();
allows you to check if all buttons are
.setEnabled(false);

Related

Disable Button on Activity, after user interacts with Buttons

Im having trouble disabling the Buttons for a particular question in my mQuestionsBank array. I created a mQuestionsAnswered boolean array with the size of the mQuestionsBank array to keep track of the questions that have been answered. Now, when the user interacts with either the "True" or "False" button, mQuestionsAnswered[mCurrentIndex] gets set to true, therefore disabling both of the buttons whether if they are right or wrong. Heres my code
Method to Enable Buttons image
Method to Check Answer image
True and False Button onClickListeners image
This is the code from your first picture:
private void buttonEnabler(){
if (...) {
...
} else
mTrueButton.setEnabled(true);
mFalseButton.setEnabled(true);
}
You're missing brackets on the else case. That means that this code "really" looks like this:
private void buttonEnabler(){
if (...) {
...
} else
mTrueButton.setEnabled(true);
}
mFalseButton.setEnabled(true);
}
In other words, mFalseButton will always be enabled, even when you don't want it to be. To fix it, add the brackets surrounding the else lines:
private void buttonEnabler(){
if (...) {
...
} else {
mTrueButton.setEnabled(true);
mFalseButton.setEnabled(true);
}
}
In your method buttonEnable, there's the if else error
Use else with {} brackets always, unless the statements to be executed is just one as illustrated below...
if (true)
say 'hello
else
be quiet
Or
if(true) {
say 'hello'
say 'how may I help you're
} else {
say statement 3
say statement 4
}

memory game java gui

I'm trying to write a logic in memory game that when I click on cards and they are not a pair (different ID), program should swap them back after 1s. If they are same, then leave them as they are.
The problem is that when I first click and the card appears, after second clicking on another (different) card it doesn't appear and swap the first card after 1s. someone knows why the second card does not appear after clicking?
Btw when the pair is correct, everything works fine, here is my fragment of the code responsible for that logic in listener:
final int copy = i;
card2.addActionListener((e) -> {
card2.setIcon(new ImageIcon(icons[copy].getAbsolutePath()));
if(firstClick == null)
{
firstClick = (Card)e.getSource();
}
else
{
Card secondClick = (Card)e.getSource();
if(firstClick.getID() != secondClick.getID())
{
try
{
Thread.sleep(1000);
} catch (InterruptedException e1)
{
//e1.printStackTrace();
}
firstClick.setIcon(new ImageIcon(background.getAbsolutePath()));
secondClick.setIcon(new ImageIcon(background.getAbsolutePath()));
firstClick = null;
}
else
firstClick = null;
}
});
While method actionPerformed is executing, the GUI cannot react to mouse and keyboard events, so basically your code is "freezing" your GUI for one second. I believe that the class javax.swing.Timer is what you need and at first glance it looks like the duplicate question that MadProgrammer referred to may help you.

How to force something to happen before something else JAVA

In my app I'm trying to create a "loading screen" so the user knows what's happening and doesn't think the app is lagging when loading a new view upon releasing a button. I'm trying to have my "setViewVisibility" method run before the rest of the code but I can't seem to make it work. The way I have it set up right now is that there's an instance boolean that gets changed when one action is completed but for some reason it's not working. Any ideas on how I could fix this?
if(isLoadScreen == true){
setViewVisibility(visibility.END);
buttoni.setAlpha((float) 1);
isLoadScreen = false;
}
if (isLoadScreen == false){
setKeysList(list);
startQuestion(keysList.get(0));
currentQuestion = 0;
isLoadScreen = true;
}
Your second block is always executed because isLoadScreen is always false at that point. You need to use else instead of if to get the behavior you want.
if (isLoadScreen == false){ //isLoadScreen is always false here - just use else instead
setKeysList(list);
startQuestion(keysList.get(0));
currentQuestion = 0;
isLoadScreen = true;
}
That said, there are better ways to create splash/loading screens - this question How do I make a splash screen? might provide some hints.

Changing label text when button is clicked

I am trying to create a swing app that is a quiz. I need the jLabel to change on a button click but when I click the button, the app locks up. Can someone point me in the right direction?
My button click code is below:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String[] questions = {"test0","test1","test2","test3","test4","test5","test6"};
String[] answers = {"","","","","","",""};
int i = 0;
do {
jLabel2.setText(questions[i]);
index.setText(String.valueOf(i));
if (txtAnswer.getText().toLowerCase().equals(answers[i].toLowerCase())) {
i++;
jLabel2.setText(questions[i]);
}
else {
add(lblWrong);
}
}
while(i < 7);
}
I am getting a warning that the evt parameter has not been used, could this be a problem?
Thank you
You don't want the do while loop. It's trapping you in the button press method as if you get an answer wrong you keep entering the else and can't leave it, stopping the app from working. Replace it with an if statement checking if i < 7.
In the else condition of your loop, you don't add 1 to i at all - therefore you can potentially end up in the situation where it's never incremented, thus it will be an infinite loop (locking your program up.)

Do not change right the icon,java

i have a problem with my code. I think that my problem is easy,but i have compiled for 3 days without good results. I have three images. They are put on screen one-one each time. User choose from 4 button if image's side is up, down, right or left. Also, i want to understand if user was wrong and then i will count errors. When user make 3 errors then the game will stop. I have shown code below. Please help me if you have any good idea.
The problem is that at the first loop,run right.It goes at the first if. After that it do the loop and then it does not go to second if.
if it is more helpful,some details:
i want to make a programma that it will show to user an image.This image has 4 sides (up,down,right,left).When the image is at "up side",user has to click on up button,when the image is at "down side",user has to click on down button etc. User can do 3 errors max. At first,program show the image at right side,if user clicks on right button then i want to show the "second image" at left side.If user does not at left side,then i want to add an error(error++) and after it shows the third image at up side etc. I hope it is more helpful to understand. If you can't please let me know.
My program is at Netbeans,java.
Thank you
public void actionPerformed(ActionEvent e)
{
while(errors<3)
{
image.setIcon(createImageIcon("visual1" + e.getActionCommand() + ".PNG"));
if (k==1)
{
if(e.getSource() == right_button)
{
image.setIcon(createImageIcon("visual2" + e.getActionCommand() + ".PNG"));
}
}
else if ( k==2 )
{
if(e.getSource() == left_button )
{
image.setIcon(createImageIcon("visual3" + e.getActionCommand() + ".PNG"));
}
}
else if (k==3 )
{
if(e.getSource() == up_button)
{
System.out.print("if3");
}
}
else
{
errors++;
}
k=k+1;
}
}
You should consider calling Repaint and Invalidate, right after you update your GUI like this -
mainframe.repaint();
mainframe.invalidate();
here mainframe is your JFrame object.
A problem I see with your while loop is that it is at risk of getting stuck in an infinite loop, since the variable used as an exit criterion is only updated some of the time, in an else block. I think you should re-arrange your logic:
Get rid of that while loop as it will only cause trouble. It is useful for a linear command line program but not for an event-driven GUI program like yours.
Read in all images and create all ImageIcons in the class constructor, and store them in variables. There's no need to re-read the images multiple times (unless they're huge).
Instead of using a while loop, increment the error variable in your method above, and then write the method so that it will change behaviors depending on the value of error (depending on the state of the class).
e.g.,
// somewhere in your code create your icons
Icon rightIcon = ......;
Icon leftIcon = .....;
Icon upIcon = .....;
Icon downIcon = .....;
// elsewhere in your code
public void actionPerformed(ActionEvent e) {
if (errors >= 3) {
// notify user of error
return; // end this method
}
// check if current icon matches image
// if so, change icon
// if not increment error
}
Note that an enum Direction {UP, DOWN, LEFT, RIGHT} and a Map<Direction, Icon> could be helpful here.

Categories

Resources