Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: JOption to JFrame HELP...messed my program up

  1. #1
    Junior Member
    Join Date
    Dec 2010
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default JOption to JFrame HELP...messed my program up

    hi everyone,

    i am creating a word guess game for my degree and instead of reading the assignment brief properly i created it in jopton panes and had it working 110%, HOWEVER this was short lived until last week until i found out that it had to be in JFrames.

    I thought it would be an easy fix but really it isnt once i got going.

    I didnt pay much attention to creating jframes because i was to busy thinking i was getting ahead creating it in joption panes and now i am really stuck.

    If someone could have a look at this code for me, if someone can tell me why it runs but when the start button is clicked on it doesnt work that would be a great help or even show me a quick example piece of code that i could change mine to because i honestly dont know what i am doing with JFrames.

    word guess game jframes.txt

    i cant thank anyone enough for helping


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: JOption to JFrame HELP...messed my program up

    Please post your code in the forum that you want looked at.

  3. #3
    Junior Member
    Join Date
    Dec 2010
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: JOption to JFrame HELP...messed my program up

    hi, thanks for replying.

    my code is in my first post in a text file

    sorry i am kind of new to the forum but i attached it in a text file and inserted it to my first post

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: JOption to JFrame HELP...messed my program up

    import java.awt.*;
    import javax.swing.*;
     
    import java.awt.event.*;
    import java.util.Random;
    import java.util.Scanner;
     
     
    	public class WordGuessGame
    	{
            JFrame frame;
            JPanel panel;
            JLabel label;
            JTextArea input;
            String word;
     
            JButton checkletter; 
            JButton giveup;
     
            public static void main(String[]args)
            {
                    WordGuessGame app = new WordGuessGame();
                    app.start();
            }
     
            public void start()
            {       
                    frame = new JFrame();
                    panel = new JPanel();
                    frame.getContentPane().add(BorderLayout.NORTH, panel);
                    frame.setVisible(true);
                    frame.setSize(500,300);
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    panel.setLayout(new FlowLayout());
     
     
     
                    label = new JLabel(" Word Guessing Game");
                    panel.add(label);
     
                    checkletter = new JButton("Start");
                    panel.add(checkletter);
     
     
                    input = new JTextArea("");
                    panel.add(input);
     
                    giveup = new JButton("Give up!");
                    panel.add(giveup);
     
     
     
            }
     
    		//create an inner listener class for the first button 
    		class startListener implements ActionListener 
    		{
    			String guess;
    			int wrongGuess;
    			Random generator = new Random();
     
    			JLabel invalidLbl;
    			JLabel guessedLbl;
     
    			public void actionPerformed(ActionEvent event) 
    			{
    				//string array of words
    				String [] words = {"paprika", "savvy", "knickknack", "cyclists", 
    						"daydreamt", "cushion", "karaoke", "parlour", "cormac", 
    						"riverrock", "storage", "chemistry", "cockatoo", "fujitsu"};
     
    			char userGuess, again;//declare variables 
     
    				//start do loop
    				do {
     
    					int num = words.length;//words that are available 
    					word = selectRandomWord(words, num);//selects a random word from array
     
    					int word_length = word.length();//finds length of word
    					guess = initialise(word_length);//creates dashes to display depending on length of word
    					wrongGuess = 0;//user wrong guesses
     
    					boolean[] history = new boolean[26];//stores users guesses in array so not repeated again
    					System.out.println(guess);//outsputs the current users guess
     
    					//while loop to repeat the users guess until lives run out
    					while(wrongGuess <10 && !guess.equals(word))
    					{
    						userGuess = getGuess(guess, wrongGuess);//gets the users next guess
     
     
     
    						if (userGuess < 'a' || userGuess > 'z')//ensures that guess is a letter
    							invalidLbl.setText(invalidLbl.getText() +("Invalid guess " + userGuess));//display output if guess is not a letter and displays what they entered
     
    						else if (history[userGuess - 'a'])//checks history array to ensure guess has already not be used
    							guessedLbl.setText(guessedLbl.getText() +("You already guessed " + userGuess));//display output if guess has been entered before
     
    						else
    						{
    							history[userGuess - 'a'] = true;//enters letter as guessed to histroy array
    							if(inWord(userGuess, word))	//checks if guess letter is in word and enters in to display
    								guess = fillInGuess(userGuess, guess, word);//adds the guessed letter to variable
     
    							else//wrong guess
    								wrongGuess++;//chnages amount of wrong guesses (adds on, loses a life)	
    						}
     
    						//if statement which displays answer is number of wrong guesses is reached
    						if(wrongGuess==10)
    							JOptionPane.showMessageDialog(null, "The answer was: " + word);//output to user is maximum guesses has been reached
     
    					}again=goAgain();// opens goAgain method
    				} while (again=='Y');//repeats if answer to restart game is "Y"
    			}//close playgame method
     
     
    			//start goAgain method
    			public char goAgain()
    			{
    				//display output to prompt user to go again, if yes do loop is repeated above
    				return JOptionPane.showInputDialog("Do you want to play again?  (Y/N)").toUpperCase().charAt(0);
    			}
     
    			//select random word method
    			public String selectRandomWord(String[] words, int num)
    			{
    				//selects a random word from array
    				return words[generator.nextInt(num)];
    			}
     
    			//start initialise method
    			public String initialise(int word_length)
    			{
    				//sets the number of "-" to be displayed depending on length of word 
    				String temp="";
    				for(int i=0;i<word_length;i++)
    					temp+="-";
    				return temp;
    			}
     
    			//start getGuess method
    			public char getGuess(String currentGuess, int numWrong)
    			{
    				//output on optionpane to prompt user to enter another guess and shows how many wrong guesses made
    				return JOptionPane.showInputDialog("Your current guess is " +
    				currentGuess + "\n\n"+ numWrong + "/10" + " wrong guesses so far\n"
    				+ "\nEnter your next guess").toLowerCase().charAt(0);
    			}
     
    			//start inWord method
    			public boolean inWord(char userGuess, String word)
    			{
    				//checks if users guess is a charactor in the word 
    				boolean returnvalue=false;//if not returns as false
    				for(int i=0;i<word.length();i++)
    					if(userGuess==word.charAt(i))
    						returnvalue=true;//is yes returns as true
    				return returnvalue;
    			}
     
    			//start method fillInGuess
    			public String fillInGuess(char userGuess, String guess, String word)
    			{
    				//fills in the correctly guessed charactor to the position in the word to display in panel
    				String temp="";
    				for(int i=0;i<word.length();i++)
    				{
    					if(guess.charAt(i)!='-')
    						temp=temp+guess.charAt(i);
    					else if(word.charAt(i)!=userGuess)
    						temp=temp+"-";
    					else temp=temp+userGuess;
    				}
    				return temp;	
    			}//ends fillInGuess method			
    			}
     
     
     
    		//end class
     
     
     
    	}

    Where do you add the action listener to any buttons?
    Last edited by Norm; December 20th, 2011 at 07:57 PM.

  5. #5
    Junior Member
    Join Date
    Dec 2010
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: JOption to JFrame HELP...messed my program up

    oh sorry i thought i attached it wrong.

    can you help with my code as you can see some of the joption outputs are still in there but i created a new class and tried my best at creating it in jframes but i have a hit a wall

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: JOption to JFrame HELP...messed my program up

    Using a GUI is sort of the opposite of using prompts with JOptoinPanes.
    You present the GUI to the user, he fills in data or checks some options and presses a button.
    The program then collects the data and does its processing, displays some results and returns to the java program to wait for more user input. You want to keep the processing in the listeners as short as possible.

    Using JOptionPane for error messages can be ok.

    How is the program supposed to work? When I start it all I get is a grey window and a button.

  7. #7
    Junior Member
    Join Date
    Dec 2010
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: JOption to JFrame HELP...messed my program up

    it is supposed to start with a screen saying current guess which would be " - - - - -" then when the users guesses a letter the sapce should be updated if guessed correctly if not there should be an output also saying the number of guesses made (could be known as lives) once reaching 10 the game should automatcally stop and tell the user the word and ask if he wants to play again.

    i have completly hit a wall because when we were getting lectures on jframes i was hard at the program putting option panes in...

  8. #8
    Junior Member
    Join Date
    Dec 2010
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: JOption to JFrame HELP...messed my program up

    Quote Originally Posted by Norm View Post
    Using a GUI is sort of the opposite of using prompts with JOptoinPanes.
    You present the GUI to the user, he fills in data or checks some options and presses a button.
    The program then collects the data and does its processing, displays some results and returns to the java program to wait for more user input. You want to keep the processing in the listeners as short as possible.
    basically all the code i have put in the actionlistener for the start button is ALL the code i have in my orginal program using joption

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: JOption to JFrame HELP...messed my program up

    You are going to have to redesign the logic to use fields in the GUI instead of the option pane prompts.
    There won't be a loop inside of your code. The "loop" will be sort of like this:
    you present the user with some data and fields, he enters data and presses a button, you do something with the data, show some results in some fields in the GUI and then exit back to the JVM. Then the JVM waits for the user to respond. When the user has entered data, and presses a button the execution goes around again as above.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: JOption to JFrame HELP...messed my program up

    basically all the code i have put in the actionlistener for the start button is ALL the code i have in my orginal program using joption
    The loop will have to come out of the listener. You can not loop inside of the listener. The looping will be as I described in the last post.

Similar Threads

  1. Need help correcting a JFrame program for class!
    By AlexAndAHalf in forum What's Wrong With My Code?
    Replies: 9
    Last Post: November 23rd, 2011, 04:03 AM
  2. Help with JFrame program that calculates average
    By ePerKar3 in forum AWT / Java Swing
    Replies: 3
    Last Post: November 4th, 2011, 08:48 AM
  3. [SOLVED] I have a problem with this Joption programme.
    By Leprechaun_hunter in forum What's Wrong With My Code?
    Replies: 7
    Last Post: April 12th, 2011, 03:31 AM
  4. Imitating a JFrame extended program with JPanel; help needed...
    By emigrant in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 15th, 2010, 02:30 PM
  5. JOption Pane help
    By dallas1125 in forum AWT / Java Swing
    Replies: 5
    Last Post: November 18th, 2009, 05:08 PM