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!