Hi all, this is my first post as a user, however ive been using this site to aid me in some of my programming assignments.

I have become a little stuck with one program that i am trying to create which is a random number generator for 6 numbers. Ive done the core code so far which covers the algorithms, but i am confused on how to add code which i think covers the gui aspect of the program.

The bit im stuck on states the class should display a logo, a button and a text box to contain the six numbers. The numbers should only be generated when the button is pressed.

This is my code so far

import java.util.*;

public class LotteryNumbers
{
    int[] LotteryNumbers = new int[49];
    int i;
    Random rgen = new Random();  

    //Creating an Array of 50 integers
     public void createNumbers()  
    {
        for (i=0; i < LotteryNumbers.length; i++) 
        {   
            LotteryNumbers[i] = i + 1;
        }
    }

    //Shuffling the numbers in the array
    public void shuffleNumbers()
    {
        for (int j=0; j < LotteryNumbers.length; i++) 
        {
            int randomPosition = rgen.nextInt(LotteryNumbers.length);
            int temp = LotteryNumbers[j];
            LotteryNumbers[j] = LotteryNumbers[randomPosition];
            LotteryNumbers[randomPosition] = temp;
        }
    }

    //Sorting the numbers in the array
    public void sortNumbers()
    {
        for(int i=0; i < LotteryNumbers.length-1; i++) 
        {
            for(int j=0; j < LotteryNumbers.length-1-i; j++) 
            {
                if(LotteryNumbers[j] > LotteryNumbers[j+1]) 
                {
                    int temp = LotteryNumbers[j];
                    LotteryNumbers[j] = LotteryNumbers[j+1];
                    LotteryNumbers[j+1] = temp;
                }
            }
        }
    }

    // Printing the numbers out
    public void printnumbers( int j, int [] LotteryNumbers)
    {
        for (j = 0; j<= 6 && j >= 1; j++)
        {
            System.out.println("Lotto number: " + j + ":" + LotteryNumbers);
        }
    }
}

Here is a small sample Swing GUI I made to get you started:

Untitled95

import java.awt.BorderLayout;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

/**
 *
 * @author David
 */
public class SwingGuiTest {

    private JFrame frame;

    public SwingGuiTest() {
        initComponents();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SwingGuiTest();
            }
        });
    }

    private void initComponents() {
        frame = new JFrame();
        //set what to do when frame X is pressed
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);


        //create componnets
        JButton button = new JButton("Button");
        JTextField tf = new JTextField(6);
        JLabel l = null;
        try {
            l = new JLabel(new ImageIcon(new URL("http://www.percona.com/live/nyc-2012/sites/default/files/daniweb_logo.png?1344973349")));
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }

        //add componnets to frame
        frame.add(l, BorderLayout.NORTH);
        frame.add(tf, BorderLayout.CENTER);
        frame.add(button, BorderLayout.SOUTH);

        //size and show frame
        frame.pack();
        frame.setVisible(true);
    }
}

Hope it helps

thanks for the quick reply, il give it a try and let you know how i get on.

Ok, i have managed to do 95% of what i needed. All the GUI and coding is in place, however whenever i run the programme, it should display the 6 lotto numbers in the label but it doesnt. Instead it gives out a horrible box of code which i have no clue as to what it is.

I am currently using Bluej IDE.

import java.util.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; 

public class LotteryGenerator implements ActionListener

{       
        private JFrame frame = new JFrame("Lottery Generator Program");
        private JPanel panel = new JPanel(); 
        private JButton GenerateLottoNums = new JButton("Generate Numbers");
        private String lottoNums = "";
        private JTextField LotteryText = new JTextField(50);
        ImageIcon Lottery = new ImageIcon("Lottery.png");
        private JLabel label = new JLabel(Lottery);


        public static void main (String[] args)
        {
            LotteryGenerator gui = new LotteryGenerator();
        }

        public void LotteryGenerator()
        {
           //Defining the Window
            frame.add(panel);
            frame.setSize(500, 300);
            frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
            frame.setVisible(true);
            GenerateLottoNums.addActionListener(this);

            //Adding the button, label and image to the panel
            panel.add(label);
            panel.add(GenerateLottoNums);
            panel.add(LotteryText);
        }

        int[] LotteryGenerator = new int[49];
        int i = 0;

        //Creating an Array of 50 integers
        public void createNumbers()  
        {
            for (i=0; i < LotteryGenerator.length; i++) 
            {   
                LotteryGenerator[i] = i + 1;
            }
        }

        //Shuffling the numbers in the array
        public void shuffleNumbers()
        {
            int ShuffleLength; 
            int Index; 
            int Position;
            ShuffleLength = LotteryGenerator.length;
            for (int j=0; j < LotteryGenerator.length; j++) 
            {
               Index = (int) (Math.random() * ShuffleLength);
               Position = LotteryGenerator[Index];
               System.out.println(Position + ":" + LotteryGenerator[Position]);
               LotteryGenerator[Index] = LotteryGenerator[--ShuffleLength];
            }
        }

        //Sorting the numbers in the array
        public void sortNumbers()
        {
            for(int i=0; i < LotteryGenerator.length-1; i++) 
            {
                for(int j=0; j < LotteryGenerator.length-1-i; j++) 
                {
                    if(LotteryGenerator[j] > LotteryGenerator[j+1]) 
                    {
                        int temp = LotteryGenerator[j];
                        LotteryGenerator[j] = LotteryGenerator[j+1];
                        LotteryGenerator[j+1] = temp;
                    }
                }
            }        

        }

        // Printing the numbers out
        public void showNums()
        {
            for (int j = 0; j < 6; j++)
            {
                lottoNums += " " + LotteryGenerator[j] + " ";
            }
            LotteryText.setText(lottoNums);
        }

        public void actionPerformed(ActionEvent e)
        {
            createNumbers();
            shuffleNumbers();
            sortNumbers();
            showNums();
        }
}

it gives out a horrible box of code

Please copy and paste the full text of any error messages generated by the program. I assume that is the "horrible box" that you are seeing.

On windows To copy the contents of the command prompt window:
Click on Icon in upper left corner
Select Edit
Select 'Select All' - The selection will show
Click in upper left again
Select Edit and click 'Copy'

Paste here.

Please copy and paste the full text of any error messages generated by the program. I assume that is the "horrible box" that you are seeing.

On windows To copy the contents of the command prompt window:
Click on Icon in upper left corner
Select Edit
Select 'Select All' - The selection will show
Click in upper left again
Select Edit and click 'Copy'

Paste here.

Apologies, i should have done so beforehand. Below is all the contents of the error box.

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 49
    at LotteryGenerator.shuffleNumbers(LotteryGenerator.java:67)
    at LotteryGenerator.actionPerformed(LotteryGenerator.java:103)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6505)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6270)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4861)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.java:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2719)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:723)
    at java.awt.EventQueue.access$200(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:682)
    at java.awt.EventQueue$3.run(EventQueue.java:680)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:696)
    at java.awt.EventQueue$4.run(EventQueue.java:694)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:693)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 49
    at LotteryGenerator.shuffleNumbers(LotteryGenerator.java:67)
    at LotteryGenerator.actionPerformed(LotteryGenerator.java:103)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6505)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6270)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4861)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.java:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2719)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:723)
    at java.awt.EventQueue.access$200(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:682)
    at java.awt.EventQueue$3.run(EventQueue.java:680)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:696)
    at java.awt.EventQueue$4.run(EventQueue.java:694)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:693)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)

java.lang.ArrayIndexOutOfBoundsException: 49
at LotteryGenerator.shuffleNumbers(LotteryGenerator.java:67)

At line 67 the code uses an index (49) that is past the end of the array.
Remember that the range of indexes for an array go from 0 to the array length-1
The max index for a 49 element array is 48.

I managed to fix that horrible error in my previous message and have managed to do quite a fair bit and feel like im near the end now. One last minor problem i have is the sorting algorithm of my code, for some reason it doesnt rearrange the numbers instead it looks as though it skips that and displays the shuffled numbers.

The whole purpose of this program was to create an array of 49 integers whilst only displaying 6, shuffle numbers 1-49, sort the numbers and display numbers 1-6.

Ive be trying to fix the sorting algorithm for a while and cant seem to get it to work.

lotto

    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    import java.util.*;
    public class lotteryGenerator implements ActionListener
    {
    private JFrame frame = new JFrame("Lottery Generator Program");
    private JPanel panel = new JPanel();
    private JButton generateLottoNums = new JButton("Generate Numbers");
    private String lottoNums = "";
    private JTextField lotteryText = new JTextField(20);
    ImageIcon Lottery = new ImageIcon("Lottery.jpg");
    private JLabel label = new JLabel(Lottery);
    public static void main (String[] args)
    {
    lotteryGenerator gui = new lotteryGenerator();
    }
    public void lotteryGenerator()
    {
    //Defining the Window
    frame.add(panel);
    frame.setSize(300, 300);
    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    generateLottoNums.addActionListener(this);
    //Adding the button, label and image to the panel
    panel.add(label);
    panel.add(generateLottoNums);
    panel.add(lotteryText);
    }
    int[] lotteryGenerator = new int[49];
    int i = 0;
    Random rgen = new Random();
    //Creating an Array of 50 integers
    public void createNumbers()
    {
    //Creating an Array of 50 Integers
    for (i=0; i < lotteryGenerator.length; i++)
    {
    lotteryGenerator[i] = i + 1;
    }
    }
    public void shuffleNumbers()
    {
    //Shuffling the numbers in the array
    for (int i=0; i < lotteryGenerator.length; i++)
    {
    int randomPosition = rgen.nextInt(lotteryGenerator.length);
    int temp = lotteryGenerator[i];
    lotteryGenerator[i] = lotteryGenerator[randomPosition];
    lotteryGenerator[randomPosition] = temp;
    }
    }
    //Sorting the numbers in the array
    public void sortNumbers()
    {
    int sortingNumbers;
    int length = 0;
    sortingNumbers = length - 1;
    for (int i = 0; i <= 6; i++)
    {
    for (int j = 0; j < sortingNumbers; j++)
    {
    for (int k = 0; k < sortingNumbers; k++)
    {
    if (lotteryGenerator[k] < lotteryGenerator[k + 1])
    {
    int temp;
    temp = lotteryGenerator[k];
    lotteryGenerator[k] = lotteryGenerator[k + 1];
    lotteryGenerator[k + 1] = temp;
    }
    }
    }
    }
    }
    public void showNums()
    {
    for (int i = 0; i < 6; i++)
    {
    lottoNums += " " + lotteryGenerator[i] + " ";
    }
    lotteryText.setText(lottoNums);
    }
    public void actionPerformed(ActionEvent e)
    {
    createNumbers();
    shuffleNumbers();
    sortNumbers();
    showNums();
    }
    }

The posted code doesn't display anything when compiled and executed.
Are you sure that you have posted the correct code?

ive edited the post and pasted the exact code from my compiler again, ive done the same thing everytime ive posted on here

Copy the above code into an empty folder, compile and execute it and tell me what happens.
What you have posted does not display anything.

To see if the methods are changing the contents of the array, print the array out at the beginning and end of the method by using the Arrays toString() method to format the contents of the array:
System.out.println("before shuffle"+Arrays.toString(lotteryGenerator));

it should be ok now, hopefully, ive reposted it and whenever i copy and paste what i posted, it compiles and executes

The code still does nothing when executed. Did you copy the posted code to an empty folder and compile and execute it to see what it does? Don't mix it in with anything else.

How are compiling and executing the code?

it is definately something to do with the sorting algorithm, i applied that println code before and after the shuffle algorithm and there were no problems with that.

i did the same with the sorting algorithm and it just seemed to ignore it.

it just seemed to ignore it.

Please explain. Did the printlns execute before and after the sort?

Add some more printlns to the sort method code to print out the values of all the variables used to control the sorting.

the printlns did execute before and after the sort code.

after the shuffle code it would produce something like this
[30, 41, 4, 45, 13, 42, 8, 39, 10, 14, 12, 26, etc...]

and this would continue within the sort code method even when i added more printlns, it kept producing the same result throughout.

Add some more printlns to the sort() method code to print out the values of all the variables used to control the sorting. For example those that control the looping.

The code you have posted does not display anything when compiled and executed.
How are you compiling and executing it? Are there other java files that you have not posted?

How are you compiling and executing it? Are there other java files that you have not posted?

Im currently using an IDE called Bluej and compiling and executing it through that. The same code i posted in my very first post was off the same IDE.

Il check out the rest of the printlns an get back to you on that.

im still getting the same values throughout the sort code.

import java.awt.event.ActionListener; 
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.util.*;

public class lotteryGenerator implements ActionListener

{       
        private JFrame frame = new JFrame("Lottery Generator Program");
        private JPanel panel = new JPanel(); 
        private JButton generateLottoNums = new JButton("Generate Numbers");
        private String lottoNums = "";
        private JTextField lotteryText = new JTextField(20);
        ImageIcon Lottery = new ImageIcon("Lottery.jpg");
        private JLabel label = new JLabel(Lottery);


        public static void main (String[] args)
        {
            lotteryGenerator gui = new lotteryGenerator();
        }

        public void lotteryGenerator()
        {
           //Defining the Window
            frame.add(panel);
            frame.setSize(300, 300);
            frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
            frame.setVisible(true);
            generateLottoNums.addActionListener(this);

            //Adding the button, label and image to the panel
            panel.add(label);
            panel.add(generateLottoNums);
            panel.add(lotteryText);
        }

        int[] lotteryGenerator = new int[49];
        int i = 0;
        Random rgen = new Random();

        //Creating an Array of 50 integers
        public void createNumbers()  
        {
            //Creating an Array of 50 Integers            
            for (i=0; i < lotteryGenerator.length; i++) 
            {   
                lotteryGenerator[i] = i + 1;
            }
        }

        public void shuffleNumbers()
        {
            //Shuffling the numbers in the array
            for (int i=0; i < lotteryGenerator.length; i++) 
            {
                int randomPosition = rgen.nextInt(lotteryGenerator.length);
                int temp = lotteryGenerator[i];
                lotteryGenerator[i] = lotteryGenerator[randomPosition];
                lotteryGenerator[randomPosition] = temp;
            }      

        }     

       //Sorting the numbers in the array

        public void sortNumbers()
        {
            int sortingNumbers;
            int length = 0;
            sortingNumbers = length - 1;
            System.out.println("before sort"+Arrays.toString(lotteryGenerator));
            for (int i = 0; i <= 6; i++)
            System.out.println("before sort"+Arrays.toString(lotteryGenerator));
            {
                System.out.println("before sort"+Arrays.toString(lotteryGenerator));
                for (int j = 0; j < sortingNumbers; j++)
                {
                    System.out.println("before sort"+Arrays.toString(lotteryGenerator));
                    for (int k = 0; k < sortingNumbers; k++)
                    {
                        if (lotteryGenerator[k] < lotteryGenerator[k + 1])
                        {
                            int temp;
                            temp = lotteryGenerator[k];
                            lotteryGenerator[k] = lotteryGenerator[k + 1];
                            lotteryGenerator[k + 1] = temp;
                        }
                    }
                }
            }

        }

        public void showNums()
        {         
            for (int i = 0; i < 6; i++)
            {
                lottoNums += " " + lotteryGenerator[i] + " ";
            }
                lotteryText.setText(lottoNums);   
        }

        public void actionPerformed(ActionEvent e)
        {
            createNumbers();
            shuffleNumbers();
            sortNumbers();
            showNums();
        }
}

The method public void lotteryGenerator() that fills the JFrame and sets it visible is not called anywhere in the posted code. How does your version of the code work?
There must be some other code somewhere with a constructor for your class that calls the above method.

What prints out from your printlns? Are they all executing?

the public void lotteryGenerator() is called under public static void main (String[] args) however even when i removed it from there, it still compiled.

as for the printlns it still produces the same values from the shuffle code.

What statement in the main() method calls the lotteryGenerator() method? The code you posted does NOT call that method. It calls the constructor for the class.

Do all the println statements execute? You need to change what is printed by each println statement so you can tell which one has executed. There are 4 identical println statements that you won't be able to tell which one has printed and which one has not.
Add a different id number to each:
System.out.println("1before sort"+Arrays.toString(lotteryGenerator));

...
System.out.println("2before sort"+Arrays.toString(lotteryGenerator));

What about: Add some more printlns to the sort() method code to print out the values of all the variables used to control the sorting. For example those that control the looping.

What did you see with these print outs?

ok i added the println statements into the sorting code and out of the 4 only 2 produced the values. The only println statements to produce any code was;

System.out.println("1before sort"+Arrays.toString(lotteryGenerator));
System.out.println("2before sort"+Arrays.toString(lotteryGenerator));

    public void sortNumbers()
    {
        int sortingNumbers;
        int length = 0;
        sortingNumbers = length - 1;

        System.out.println("1before sort"+Arrays.toString(lotteryGenerator));  
        for (int i = 0; i <= 6; i++)
        {
            System.out.println("2before sort"+Arrays.toString(lotteryGenerator));  
            for (int j = 0; j < sortingNumbers; j++)
            {
                System.out.println("3before sort"+Arrays.toString(lotteryGenerator));
                for (int k = 0; k < sortingNumbers; k++)
                {
                    System.out.println("4before sort"+Arrays.toString(lotteryGenerator));
                    if (lotteryGenerator[k] < lotteryGenerator[k + 1])
                    {
                        int temp;
                        temp = lotteryGenerator[k];
                        lotteryGenerator[k] = lotteryGenerator[k + 1];
                        lotteryGenerator[k + 1] = temp;
                    }
                }
            }
        }

    }

What about this: Add some more printlns to the sort() method code to print out the values of all the variables used to control the sorting. For example those that control the looping.

What statement in the main() method calls the lotteryGenerator() method? The code you posted does NOT call that method. It calls the constructor for the class.
Your IDE is doing some magic to allow this class to execute as you see it. The posted code does NOT display anything when it executes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.