Skip to content

How to create an array with random numbers and send it to listener without randomizing it again?

So i’m trying to create a program that create an array of 100 random numbers (without changing everytime user reacts to it), and allow users to check the numbers by entering the index of it. However, the array keep randomizing everytime the user pressed the Show Element button.

I also tried to create the array on the main program, but I then faced the error because the listener can’t access the array. Please enlighten me as I’m new to this Java GUI Programming. Any help is much appreciated.

import java.util.Random;
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.*;

public class P3Q2 extends JFrame {

    private JTextField text1 = new JTextField(10);
    private JTextField text2 = new JTextField(10);
    private int arr[];

    private JButton jbtShow = new JButton("Show Element");

    public P3Q2() {
        JPanel jpTextField = new JPanel();
        jpTextField.setLayout(new GridLayout(3, 2));
        jpTextField.add(new JLabel("Array Index"));
        jpTextField.add(new JLabel("Array Element"));

        JPanel jpButtons = new JPanel();

        add(jpButtons, BorderLayout.SOUTH);

        jbtShow.addActionListener(new ButtonListener());

        setTitle("Display: Show Bounds Error");
        setSize(400, 150);

    private class ButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            try {
                Random rd = new Random(); // creating Random object
                int[] arr = new int[100];
                for (int i = 0; i < arr.length; i++) {
                    arr[i] = rd.nextInt(); // storing random integers in an array

                if (e.getSource() == jbtShow) {
                    int num = Integer.parseInt(text1.getText());
                    int result = arr[num];
                    text2.setText("" + result);
            } catch (ArrayIndexOutOfBoundsException ex) {
                text2.setText("Out of bound!");


    public static void main(String[] args) {
        P3Q2 test = new P3Q2();


In the constructor you are assigning the random numbers to a local variable arr that is overriding the private attribute arr with the same name

Try changing it to:

Random rd = new Random(); // creating Random object
arr = new int[100];
for (int i = 0; i < arr.length; i++) {
    arr[i] = rd.nextInt(); // storing random integers in an array