Search code examples
javaarraysawtjcomponentsettext

Stupid For loop implementation


Using java.awt and javax.swing I've been making a small GUI which will show multiple entries in a JPanel. After successfully displaying a single entry with default text, I started trying to implement a for loop to create multiple entries from a handful of arrays and am having difficulty loading the text strings that label each component. After adding the for loop and arrays I now just get a single black border around a small space with no data.

Here's the code that I'm working with specifically:

package myInterfaceComponents;

import java.awt.*;

public class ListOfEntries extends JComponent {
   //instance variables
      //worked until arrays added
      String[] telephones = {"5551234567", "5557654321", "5555671234"};
      String[] names = {"Emily", "Billy Bob", "Wiley Coyote"};
      String[] periods = {"2p - 3p", "1a - 5a", "4:30p - 11p"};
   private JLabel telephone = new JLabel(); 
   private JTextField name = new JTextField();
   private JButton period = new Button();
   private StatusCombo serviceCycle = new StatusCombo();
   private AreaCombo area = new AreaCombo();

   //constructors
   public ListOfEntries() {
      setLayout(new GridLayout(2, 3));

      for (int x = 0; x == 2; x++) {         //worked until added
         telephone.setText(telephones[x]);   //worked until added
         name.setText(names[x]);             //worked until added
         period.setText(periods[x]);         //worked until added
         add(telephone);         
         add(name);
         add(area);
         add(period);
         add(serviceCycle); }                //worked until add: "}"

   Border line = BorderFactory.createLineBorder(Color.BLACK);
   Border titled = BorderFactory.createTitledBorder(line, "Day: DD MMM YYYY");
   setBorder(visible);
   setVisible(true); }
}

Obviously I'm doing something wrong with the arrays, or setting the components, but after multiple attempts & google searches I'm missing something. Any help is much appreciated.


Solution

  • I haven't actually tried running your program, but I did notice your loop:

    for (int x = 0; x == 2; x++) {         //worked until added
             telephone.setText(telephones[x]);   //worked until added
             name.setText(names[x]);             //worked until added
             period.setText(periods[x]);         //worked until added
             add(telephone);         
             add(name);
             add(area);
             add(period);
             add(serviceCycle); } 
    

    In this loop, you are initializing the counter variable "x" to 0, but then in the next statement you have: x == 2, which will run the loop only when x is equal to 2, and since x was initialized to be 0, this loop will never run. Try changing the statement x == 2 to x < 2 and see if this helps at all.