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();
}
}
Related
I am trying to make it so that instead of hitting the enter key in my java program to make the enter action occur, I can instead hit the enter key while a custom method is running. At this point, I have looked into Hashmaps but am pretty confused if this going to do what I want. Any help would be greatly appreciated. It seems like this should be an easy thing to do, but for some reason I am just not getting a solution to it.
So, I am thinking my code will be something like this. Essentially, I am making a game of Hot Potato and I need to have the players take turn entering a character (e, d, and c for team 1 and o, k, and n for team 2). This will be involving a GUI interface as well. A have a while loop that will end once a timer reaches zero. What I would like is for the players to be able to put in a letter into a JTextField in the GUI and then simply press spacebar (as they will be sharing a keyboard). Once they enter the right letter (I made it randomized), they can hit spacebar and they will have "tossed the potato" to the other player.
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE)
{
KeyEvent.VK_ENTER;
}
}
I am working all of this out of the actionPerformed(ActionEvent ev) method. The fuller code looks like this. The if statement is commented out because I would like the game to start when the main button is pressed, but right now I get a ton of compilation errors when I uncomment the JButton and have it working with the String text that is the dialogue from the text you enter into a JTextField.
public void actionPerformed(ActionEvent ev) {
Object eventSource = ev.getSource();
String text = entryText.getText(); // text entered into JText
//JButton eventButton = (JButton) eventSource;
System.out.println(text);
//if (eventButton.equals(main))
{
int totalTime = 1000*(HotPotato.randNum());
long startTime = System.currentTimeMillis();
System.out.println(totalTime/1000);
Boolean p1Start = false;
String input = "";
while (System.currentTimeMillis() - startTime <= totalTime)
{
p1Start = !p1Start;
char a = HotPotato.randLetterBoth(p1Start);
String aString = String.valueOf(a);
while (!input.equals(aString))
{
System.out.print(aString); // temporary, shows test letter
input = theKeyboard.next();
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE)
{
KeyEvent.VK_ENTER;
}
}
}
}
if (p1Start)
{
System.out.print("Team 2 Wins!");
}
else
{
System.out.print("Team 1 Wins!");
}
setLabels();
myPicture.makeHotPotatoOn(myHotPotato.state());
myPicture.repaint();
}
}
So, I've been stumped on this piece of code for about a week now, I want to have the code sending an error message when the user chooses 'No' or 'Cancel' however I get an error which tells me that NO and CANCEL are not variables. Does anyone have any suggestions as to how I can overcome this problem?
int mc = JOptionPane.QUESTION_MESSAGE;
int bc = JOptionPane.YES_NO_CANCEL_OPTION;
int ch = JOptionPane.showConfirmDialog (null, "Select:", "Title", bc, mc);
if (bc == NO)
{
JOptionPane.showInputDialog("Sorry, you cannot continue without agreeing to the rules.");
}
else if (bc == CANCEL)
{
JOptionPane.showInputDialog("Sorry, you cannot continue without agreeing to the rules.");
}
else
{
JOptionPane.showInputDialog("Thank you, you may continue!");
}
This is all explained in the JOptionPane Javadoc.
In the code that you've given, the button that you've clicked is identified by the return value from showConfirmDialog, which you've assigned to ch, not bc. In your case, the logic should be
if (ch == JOptionPane.NO_OPTION) {
...
}
else if (ch == JOptionPane.CANCEL_OPTION) {
...
}
else {
...
}
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.
is there any other way to return from the top of the code?
I already tried using Scanner and it worked but now I want to use YES_NO_OPTION in JOption but i dont have any idea to return from the top of the code using this method.
This is the last part of the program:
int selectedOption = JOptionPane.showConfirmDialog(null,"Continue?","Choose",JOptionPane.YES_NO_OPTION);
if (selectedOption == JOptionPane.YES_OPTION) {
//What should i put here inside the bracket?
}
if (selectedOption == JOptionPane.NO_OPTION) {
JOptionPane.showMessageDialog(null,"Thank you for using");
}
and What should i put in the top of the code to read my Command inside the Bracket?
any help will be appriciated.
It seems like you want a loop:
int selectedOption = JOptionPane.YES_OPTION; // by default
while (selectedOption == JOptionPane.YES_OPTION) {
// do your stuff
selectedOption =
JOptionPane.showConfirmDialog(null,"Continue?","Choose",JOptionPane.YES_NO_OPTION);
}
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("")