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 8 of 8

Thread: JFrame + JTextField and Random Number Generator

  1. #1
    Junior Member
    Join Date
    Dec 2013
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default JFrame + JTextField and Random Number Generator

    Hello all, I'm having a difficult time putting together my program. It is supposed to have a random number generator using 10 JTextFields through the use of an array. When the new numbers button is pressed it has to generate 10 random numbers between 1 and 100. I have the array setup and my textfields are showing up fine. I am just having a hard time setting up the logic for how the method and the actionlistener button are to work with the JTextField array plus random numbers generated. If I could just get help setting it up for one array object I'm sure I can figure out the rest. Then I can workout how to change the background color accordingly to the random number generated (nums >= 50 get a red background and others a white background)



    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
     
     
    public class TenNumbers
    {
    	public static void main(String [] args)
    	{
    		ManyNumbers mn = new ManyNumbers("Program 7");
    	}
    }
     
    class ManyNumbers extends JFrame
    {
    	public static final int MAX_NUM = 10;
     
    	JTextField [] nums = new JTextField[MAX_NUM];
     
     
    	JButton newNumbers = new JButton("New Numbers");
       //Create objects for the array.
     
     
     
     
     
     
       public ManyNumbers(String s)
    	{
    		super(s);
    		setLayout(new FlowLayout());
     
     
          for (int i=0; i < nums.length; i++)
           {
            nums[i] = new JTextField("0", + 4);  // Create JTextField Objects
            add(nums[i]);
           }
     
          add(newNumbers);
     
          newNumbers.addActionListener(new ButtonHandler());
     
     
     
     
    		// You can use "pack" instead of "setSize" -- pack makes 
    		// the window just the right size for the added components.
    		pack();
    		setVisible(true);
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	}
     
        class ButtonHandler implements ActionListener
         {
         public void actionPerformed(ActionEvent e)
         {
          Random rand = new Random();
     
          int num1 = rand.nextInt(100);
          set(nums[0], num1);
     
     
     
         }
         }
      void set(JTextField field, int num)
       {
     
          if (num >= 50)
             nums[0].setBackground(Color.RED);
             String s = Integer.toString(num);
             nums[0].setText();
     
       }
     }

    I'm having a hard time converting the number to a string and having it show up through the setText() method...


    Thanks for any help or direction!


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,790
    My Mood
    Mellow
    Thanks
    236
    Thanked 717 Times in 703 Posts

    Default Re: JFrame + JTextField and Random Number Generator

    I reformatted your code (your formatting was all over the place) and added comments for improvements. It seems you did have the first one set up, but why do one at a time? Do all 10 in a loop with each button press, right?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
     
     
    public class TenNumbers
    {
        public static void main( String [] args )
        {
            ManyNumbers mn = new ManyNumbers( "Program 7" );
        }
    }
     
    class ManyNumbers extends JFrame
    {
        public static final int MAX_NUM = 10;
     
        JTextField [] nums = new JTextField[MAX_NUM];
     
     
        JButton newNumbers = new JButton( "New Numbers" );
        //Create objects for the array.
     
        public ManyNumbers( String s )
        {
            super( s );
            setLayout( new FlowLayout() );
     
            for ( int i = 0; i < nums.length; i++ )
            {
                nums[i] = new JTextField( "0", + 4 ); // Create JTextField Objects
                add( nums[i] );
            }
     
            add( newNumbers );
            newNumbers.addActionListener( new ButtonHandler() );
            // You can use "pack" instead of "setSize" -- pack makes
            // the window just the right size for the added components.
            pack();
            setVisible( true );
            setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        }
     
        class ButtonHandler implements ActionListener
        {
            public void actionPerformed( ActionEvent e )
            {
                // GB: create a loop here that generates 10 numbers
     
                // GB: don't create a new random object each time. create one
                // in the constructor
                Random rand = new Random();
                int num1 = rand.nextInt( 100 );
     
                // GB: this call needs to increment the index and write the
                // new value to the next element of nums[] each time
                // through the loop
                set( nums[0], num1 );
     
                // GB: end of loop
            }
        }
        void set( JTextField field, int num )
        {
            if ( num >= 50 )
            {
                nums[0].setBackground( Color.RED );
            }
     
            String s = Integer.toString( num );
     
            // GB: complete the setText() call using String s as the argument
            nums[0].setText();
        }
    }

  3. The Following User Says Thank You to GregBrannon For This Useful Post:

    Richard_Harrow (December 7th, 2013)

  4. #3
    Junior Member
    Join Date
    Dec 2013
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: JFrame + JTextField and Random Number Generator

    Thanks a bunch, I'm going to work on it some more and hopefully I can get things to compile ok!

  5. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,790
    My Mood
    Mellow
    Thanks
    236
    Thanked 717 Times in 703 Posts

    Default Re: JFrame + JTextField and Random Number Generator

    Come back when you need more help. No sweat.

  6. #5
    Junior Member
    Join Date
    Dec 2013
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: JFrame + JTextField and Random Number Generator

    Ok so I created an array with random numbers generated and I'm getting everything to work with nums[0], now I'm having a hard time setting it up so all the JTextfields get changed when going through the loop. I know you mentioned incrementing the index by one when going through the loop (and applying the random value to each element?). I tried and tried to setup up the call set(); to work properly in a loop and I'm getting no where. Right now I only have it setup to work with just nums[0].
    Thanks again for any more help.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
     
     
    public class TenNumbers
    {
        public static void main( String [] args )
        {
            ManyNumbers mn = new ManyNumbers( "Program 7" );
     
        }
    }
     
    class ManyNumbers extends JFrame
    {
        public static final int MAX_NUM = 10;
     
        JTextField [] nums = new JTextField[MAX_NUM];
        Random rand = new Random();
        int maxRange = 100;
        int minRange = 1;
        int[] numbers;
     
     
     
        JButton newNumbers = new JButton( "New Numbers" );
        //Create objects for the array.
     
        public ManyNumbers( String s )
        {
            super( s );
            setLayout( new FlowLayout() );
     
     
            for ( int i = 0; i < nums.length; i++ )
            {
                nums[i] = new JTextField( "0", + 4 ); // Create JTextField Objects
                add( nums[i] );
     
            }
     
            add( newNumbers );
            newNumbers.addActionListener( new ButtonHandler() );
            // You can use "pack" instead of "setSize" -- pack makes
            // the window just the right size for the added components.
            pack();
            setVisible( true );
            setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        }
     
        class ButtonHandler implements ActionListener
        {
            public void actionPerformed( ActionEvent e )
            {
     
                numbers = new int[10];
     
                for(int i=0; i<10; i++)
                {
                numbers[i] = rand.nextInt(maxRange - minRange + 1);
     
                set(nums[0], numbers[0]);
                }
     
     
     
                // GB: create a loop here that generates 10 numbers
                // GB: don't create a new random object each time. create one
                // in the constructor
     
     
                // GB: this call needs to increment the index and write the
                // new value to the next element of nums[] each time
                // through the loop
     
                // GB: end of loop
            }
        }
        void set(JTextField field, int x)
        {
            if (x >= 50 )
            {
                nums[0].setBackground( Color.RED );
            String s = Integer.toString(x);
     
            // GB: complete the setText() call using String s as the argument
            nums[0].setText(s);
     
            }
            else
            {
                nums[0].setBackground( Color.WHITE );
                String s = Integer.toString(x); 
                nums[0].setText(s); 
            }
     
        }    
    }

  7. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,790
    My Mood
    Mellow
    Thanks
    236
    Thanked 717 Times in 703 Posts

    Default Re: JFrame + JTextField and Random Number Generator

    General comments:

    1. I really like the way you have this program set up, with the main() method enclosed in a simple, top-level public class that does nothing but start the program contained in another class. This makes running your code very simple, but it also will serve you well when you move to GUIs.

    2. Get in the habit of adding access modifiers to your variables and methods. Start with private unless you know the method is to be used by other classes, like getter (accessor) and setter (mutator) methods.

    3. And I badger everybody, so you get it too: comment your code.

    Now to answer you question.

    Everywhere you have an array specifying the zero index is wrong. Well, it's right if you only ever want to deal with the first item in the array, but you don't. To fix it, those zeros should be generalized to multiple solutions, so they should be indexed with a variable rather than a constant. Here's what you need to do:

    1. In the actionPerformed() method of ButtonHandler, move this line:

    set(nums[0], numbers[0]);

    outside the for loop, remove the first parameter completely, and pass only the array name of the second parameter. In other words, outside the for loop the line should become:

    set( numbers );

    That new statement will pass the entire array of random numbers (numbers) to the method set().

    2. Modify the set() method to accept one array, the array of random numbers:

    private void set(int[] x)

    Notice that the 'field' variable was never used inside the set() method. It isn't needed.

    3. Add a for loop around the existing body of the set() method from 0, inclusive, to the length of nums, not inclusive, using the loop variable of your choice (I'll call it 'i').

    4. In the body of set(), change references to x to x[i] and nums[0] to nums[i]

    The changes in the set() method will iterate the array of text fields (nums) and assign each to the corresponding random number in the x[] array, setting the background color appropriately.

    If you have any questions about these changes, please ask.

  8. #7
    Junior Member
    Join Date
    Dec 2013
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: JFrame + JTextField and Random Number Generator

    Quote Originally Posted by GregBrannon View Post
    General comments:

    1. I really like the way you have this program set up, with the main() method enclosed in a simple, top-level public class that does nothing but start the program contained in another class. This makes running your code very simple, but it also will serve you well when you move to GUIs.

    2. Get in the habit of adding access modifiers to your variables and methods. Start with private unless you know the method is to be used by other classes, like getter (accessor) and setter (mutator) methods.

    3. And I badger everybody, so you get it too: comment your code.

    Now to answer you question.

    Everywhere you have an array specifying the zero index is wrong. Well, it's right if you only ever want to deal with the first item in the array, but you don't. To fix it, those zeros should be generalized to multiple solutions, so they should be indexed with a variable rather than a constant. Here's what you need to do:

    1. In the actionPerformed() method of ButtonHandler, move this line:

    set(nums[0], numbers[0]);

    outside the for loop, remove the first parameter completely, and pass only the array name of the second parameter. In other words, outside the for loop the line should become:

    set( numbers );

    That new statement will pass the entire array of random numbers (numbers) to the method set().

    2. Modify the set() method to accept one array, the array of random numbers:

    private void set(int[] x)

    Notice that the 'field' variable was never used inside the set() method. It isn't needed.

    3. Add a for loop around the existing body of the set() method from 0, inclusive, to the length of nums, not inclusive, using the loop variable of your choice (I'll call it 'i').

    4. In the body of set(), change references to x to x[i] and nums[0] to nums[i]

    The changes in the set() method will iterate the array of text fields (nums) and assign each to the corresponding random number in the x[] array, setting the background color appropriately.

    If you have any questions about these changes, please ask.
    Success! It's working perfectly now! Now I'm just going through and adding in all the comments. Thank you so much, this was great practice for me as I have my last exam coming up next week (GUI and arrays). Thank you again sir.

  9. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,790
    My Mood
    Mellow
    Thanks
    236
    Thanked 717 Times in 703 Posts

    Default Re: JFrame + JTextField and Random Number Generator

    You're welcome. Good luck on your exam!

Similar Threads

  1. Random Number Generator
    By Rugby_Thompson in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 5th, 2013, 12:58 AM
  2. Random Number Generator Always gives 0
    By tlckl3m3elmo in forum What's Wrong With My Code?
    Replies: 2
    Last Post: March 11th, 2012, 03:09 PM
  3. Random math problem generator?
    By CamCompetes in forum Member Introductions
    Replies: 1
    Last Post: March 9th, 2012, 01:42 PM
  4. random number generator
    By java3 in forum Loops & Control Statements
    Replies: 4
    Last Post: February 21st, 2011, 11:00 AM
  5. [SOLVED] Random number method implementation
    By big_c in forum Java Theory & Questions
    Replies: 2
    Last Post: April 15th, 2009, 01:10 PM