public void testDialog()
{
JPanel myPanel = new JPanel();
JTextField tfNames [] = new JTextField[getNumOfPlayers()];
for(int i=0;i < getNumOfPlayers();i++)
{
tfNames[i] = new JTextField(20);
myPanel.add(new JLabel("Player " + (i+1)));
myPanel.add(tfNames[i]);
}
int result = JOptionPane.showConfirmDialog(null, myPanel,
"Please Enter The Player Names", JOptionPane.OK_CANCEL_OPTION);
playerNames = new String [getNumOfPlayers()];
if(result == JOptionPane.OK_OPTION)
{
for(int i=0;i < getNumOfPlayers();i++)
{
if(tfNames[i].getText() == null)
{
//NOT GETTING INSIDE HERE FOR ONE REASON OR ANOTHER
System.out.println("NULL FIELD" + i);
testDialog();
}
else
{
playerNames[i] = tfNames[i].getText();
System.out.println(playerNames[i]);
}
}
}
else if (result == JOptionPane.CANCEL_OPTION)
{
numPlayersDialog();
}
else
{
numPlayersDialog();
}
}
Basically I'm trying to check if one of the textFields are blank when the 'OK' button is clicked and if it is recall this method again but for some reason it never gets inside the piece of the code checking to see whether the textField is null or not it skips straight over it everytime even if it is null :/ Can anyone explain why? Set for an hour trying to figure it out and haven't been able to find a reason for it :/ Thanks, for any advice you may have.
PS. If there is away of disabling the 'OK' button while one of more of the textFields are blank please let me know.
Because most likesly tfNames[i].getText() returns an empty string, not null.
Maybe you should check for that instead:
if(tfNames[i].getText() != null && tfNames[i].getText().isEmpty()){
// ...
}
That is because text will never be null, it will be empty so just change your check to :
if (tfNames[i].getText().isEmpty()) {
}
if using sdk lower than 1.6 than use the plain ole checking : tfNames[i].getText().equals("")
Related
I am a noob in Java and programing and I am making an app where the user is trying to guess a city based on a picture. The user sees a picture of the city and has three buttons under the picture with different answers in them. The pictures are randomized from an array and the buttons text changes so that atleast one of the buttons has the correct answer. I want a TextView with "correct" to show if user is correct and one with "incorrect" to show if user is wrong. The text is showing up when pressing any button and not when the button with the correct text is pressed. So this is what I have tried and am stuck on. And yes I know I have many mistakes in my code, such as names of methods and so. I will change these later.
I have three booleans that are set to false, they are representing which button is pressed. You will understand more later.
Boolean test1 = false;
Boolean test2 = false;
Boolean test3 = false;
In main i have three buttons and they all call on the checkanswer function. Also they all turn their own boolean to true there, which u will se why soon. Example of one of the buttons.
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
test1 = true;
checkanswer();
}
});
So here is the checkanswer function
public void checkanswer() {
DisplayRandomImage();
//Giving three strings random city names from the "cities" array.
Random rndBtnTxt = new Random();
String randomCity1 = cities[rndBtnTxt.nextInt(cities.length)];
String randomCity2 = cities[rndBtnTxt.nextInt(cities.length)];
String randomCity3 = cities[rndBtnTxt.nextInt(cities.length)];
//Setting the random city names to the three different buttons.
btn1.setText(randomCity1);
btn2.setText(randomCity2);
btn3.setText(randomCity3);
//takes the picked image from the "DisplayRandomImage" method.
String str = String.valueOf(pickedImg);
//Tells what to call the different pictures, they are known as numbers make sure they are given names instead.
if (pickedImg == 0)
str = "venice";
if (pickedImg == 1)
str = "new york";
//If-statement checking so that atleast one button has the correct answer.
if (randomCity1 != str || randomCity2 != str || randomCity3 != str) {
Random rndbtn = new Random();
Button x = btnArray.get(rndbtn.nextInt(btnArray.size()));
//Sets one of the three buttons so that it has the correct answer.
x.setText(str);
}
//See where the correct answer is
String buttonText1 = btn1.getText().toString();
String buttonText2 = btn2.getText().toString();
String buttonText3 = btn3.getText().toString();
//check if the button that the user pressed has the correct answer
if (test1.equals(true) && buttonText1.equals(str)){
CorrectAnswer();
test1 = false;
}
if (test2.equals(true) && buttonText2.equals(str)){
CorrectAnswer();
test2 = false;
}
if (test3.equals(true) && buttonText3.equals(str)){
CorrectAnswer();
test3 = false;
}
else
WrongAnswer();
}
I am not sure what I am doing wrong here. For example the "test1" is set to True when I press "btn1" and if "buttontext1" equals to the same as "str" does it should work. But for some reason it seems randomised which of the three buttons calls for the CorrectAnswer method. What am I doing wrong here?
Can we see CorrectAnswer? Also,
right off the bat, I noticed that instead of using test1, test2 and test3 to indicate which button was pressed, you can just pass some sort of argument into checkAnswer, like int button.
So onClick would look like this for the first button, and subsequent buttons by incrementing the 1:
public void onClick(View v) {
checkanswer(1);
}
and checkanswer would look like this:
public void checkanswer(int button) {
... (previous stuff) ...
//check if the button that the user pressed has the correct answer
if (button == 1 && buttonText1.equals(str)){
CorrectAnswer();
}
if (button == 2 && buttonText2.equals(str)){
CorrectAnswer();
}
if (button == 3 && buttonText3.equals(str)){
CorrectAnswer();
}
else
WrongAnswer();
}
So try this out.
Its pretty hard to tell where the bug is, if you only show us pieces of the full code.
Mistakes could be e.g. in CorrectAnswer()...
I would recommend binding onlick-listeners to your buttons instead of changing booleans.
Check this out here: https://developer.android.com/reference/android/widget/Button
Additionally I noticed another mistake:
randomCity1 != str || randomCity2 != str || randomCity3 != str
This will return true if at least one of the Strings does not contain the right answer
You probably want to enter the if-Statement, when there isnt already a button with the correct answer.This is what you would like to use:
randomCity1 != str && randomCity2 != str && randomCity3 != str
EDIT: Check out the answer of Barcode for another example of using onClicklisteners.
Thank you both for answering the question, i have found a way to complete this problem:
public void testingMethod(int button){
switch(button){
case 1:
if (buttonText1 == str)
CorrectAnswer();
else
WrongAnswer();
break;
case 2:
if (buttonText2 == str)
CorrectAnswer();
else
WrongAnswer();
break;
case 3:
if (buttonText3 == str)
CorrectAnswer();
else
WrongAnswer();
break;
}
}
And since you were wondering how the method CorrectAnswer looked like here it is, yes I know it's probably unnecessary having this method but I am noob after all.
public void CorrectAnswer() {
findViewById(R.id.txtIncorrect).setVisibility(View.GONE);
findViewById(R.id.txtCorrect).setVisibility(View.VISIBLE);
}
I am trying to get the names of all selected JRadioButtons from my graphics interface. As such I create the allFacilities array in which I include all of my JRadioButtons.
The first for loop serves to find the number of selected radio buttons.
The second for loop aspires to get the name of each selected button.
When checking what the .getName() returns:
System.out.println("A##" + button.getName());, only null is returned for all cases.
Here is my code:
JRadioButton[] allFacilities = {restaurant, laundry, parking};
int selectedFacilitiesCounter = 0;
for(JRadioButton check : allFacilities) {
if(check.isSelected()) {
selectedFacilitiesCounter += 1;
}
}
String[] selectedFacilities = new String[selectedFacilitiesCounter];
int index = 0;
for(JRadioButton button : allFacilities) {
if(button.isSelected()) {
System.out.println("A##" + button.getName());
switch(button.getName()) {
case "restaurant":
selectedFacilities[index] = "restaurant";
break;
case "laundry":
selectedFacilities[index] = "laundry";
break;
case "parking":
selectedFacilities[index] = "parking";
break;
default:
System.out.println("Facility Not Found");
}
index += 1;
}
}
Does anybody have any ideas on how I can solve my problem?
I believe that what you want is this:
JRadioButton button = new JRadioButton("test");
System.out.println(button.getText());
Which will print test.
The method getName retrieves the name of the component, which you should've set with setName, which I believe you didn't.
Here's my problem, I'm trying to get this bit of code to work so that in my GUI, when I click on yes, the product is added (that bit of code is still to be developed) and the addproductwindow closes, but when no is clicked the JOptionPane closes, but the add product window remains open.
(the System.out.print(" no ");) was me just testing what came out from the inputs.
#Override
public void actionPerformed(ActionEvent e) {
int dialogButton = JOptionPane.YES_NO_OPTION;
JOptionPane.showConfirmDialog (null, "Do you want to add Product: ","Confirmation",dialogButton);
if (dialogButton == 1){
System.out.println(" no ");
} else {
addProductWindow.dispose();
}
}
When using JOptionPane.showConfirmDialog (...) you need to check which button was clicked by the user.
The basic code is:
int result = JOptionPane.showConfirmDialog (...);
if (result == JOptionPane.YES_OPTION)
// do something
Read the section from the Swing tutorial on How to Use Dialogs for more information and working examples.
if (dialogButton == 1)
Don't use "magic numbers". Nobody knows what "1" means. The API will have variable for you do use that are more descriptive.
For addProductWindow to close, you have to call addProductWindow.dispose() method in the if block too.
#Override
public void actionPerformed(ActionEvent e) {
int dialogButton = JOptionPane.YES_NO_OPTION;
JOptionPane.showConfirmDialog(null, "Do you want to add Product: ", "Confirmation", dialogButton);
if (dialogButton == JOptionPane.YES_OPTION) {
addProductWindow.dispose(); // you forgot this
} else {
System.out.println(" no ");
addProductWindow.dispose();
}
}
So my argument in my if statement below has to check if my JRadioButton is checked, but for some reason, even if it's not checked, the program still runs.
public void actionPerformed(ActionEvent e) {
String actionCheck = Binary.userInput1.getText();
if(Binary.binary.isEnabled() && actionCheck.matches("[01]+")){ // checks if its binary
int decimalValue = Integer.parseInt(actionCheck, 2);
String convertedDecimal = Integer.toString(decimalValue);
Binary.userInput2.setText(convertedDecimal);
}
else if (Binary.decimal.isEnabled() && decimalCheck(Binary.userInput1)){
int binaryValue = Integer.parseInt(actionCheck);
Binary.userInput2.setText(Integer.toBinaryString(binaryValue));
}
else
Binary.userInput1.setText("WRONG INPUT! -- try again");
}
What am I missing?
The buttons are called binary and decimal (Yes i know, my class is called Binary also, newbie errors)
Answer was found!
It's not isEnabled() that should be used in this case but the method isSelected()
Try to use yourJRadioButton.isSelected() instead of isEnabled().
Lets say if the last level of a game is beaten then you dont show a dialog box asking if the player wants to go on to the next level, but rather to the mainmenu. SO basically if something happens the things that are supposed to happen afterward dont.
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
final ImageIcon pokeballIcon = new ImageIcon("C:\\Users\\bacojul15\\Pictures\\pokeball5.gif");
final ImageIcon pokemoneggIcon = new ImageIcon("C:\\Users\\bacojul15\\Pictures\\nidoking.gif");
final ImageIcon pokemonredIcon = new ImageIcon("C:\\Users\\bacojul15\\Pictures\\red.gif");
String userAnswer = answertextArea.getText().trim();
if (userAnswer.equalsIgnoreCase(answers.get(questionNumber))) {
answerLabel.setText("Correct");
levelScore ++;
triviagui.totalScore ++;
} else {
answerLabel.setText("Incorrect");
}
answertextArea.setText("");
questionNumber++;
if(questionNumber == questions.size()){
JOptionPane.showMessageDialog(null, "Your score for this level was : " + levelScore + " out of 10. \n Your total score is " + triviagui.totalScore, "Scores",JOptionPane.INFORMATION_MESSAGE, pokeballIcon );
if(difficulty == 3){
JOptionPane.showMessageDialog(null, "Good job you beat the game! \n Your total score was " + triviagui.totalScore + " out of 30.", "Thanks for playing!", JOptionPane.INFORMATION_MESSAGE, pokemonredIcon);
triviagui.questionFrame.setVisible(false);
triviagui.mainFrame.setVisible(true);
}
int leveloptionPane = JOptionPane.showConfirmDialog(null,"Would you like to go on to the next level?" , "Next Level?", JOptionPane.YES_NO_OPTION, levelScore, pokemoneggIcon);
if(leveloptionPane == JOptionPane.YES_OPTION){
difficulty++;
triviagui.questionFrame.setVisible(false);
triviagui.questionFrame=new QuestionFrame(difficulty);
triviagui.questionFrame.setVisible(true);
}
if(leveloptionPane == JOptionPane.NO_OPTION){
triviagui.questionFrame.setVisible(false);
triviagui.mainFrame.setVisible(true);
}
return;
}
updateQuestionScore();
}
You simply want to do:
if(something happens) {
return;
}
If you want to jump out from method use
return;
example of something like that:
public void myMethod(){
if(mynumber==5){
doThis();
}else{
return;
}
/*
*do something else <- this wont be executed if number doesnt equal 5
*cause we are already out of method.
*/
}
If you dont want to jump out from whole method bud only form part of it for instance loop.
break;
example of that:
public void myMethod(String[] stringArr){
for(String s:stringArr){
if(s.equals("hello")){
break; //get me out of this loop now !
}else{
s+="alriight";
}
}
}
doSomethingElse();//this will be executed even if you go thru break; you are still inside method dont forget.You are just out of loop
}
There are better uses for that maybe examples aint best bud you will understand how to use it form this:).
When you use break or return.In eclipse for instance you will be shown Where you actually exit. it will highlight "}"
There are several ways to do this:
You can return from a method.
You can break to exit a loop or continue to start the next iteration of the loop.
You can use an 'else' to only execute other code if the first section did not execute.
You can set a boolean flag variable and then check for that elsewhere in your code.
Depending on what you are trying to do each of these is sometimes the best way, sometimes not the best way.