Can I ask for some advice / help please, I am writing a UI that upon the user making a selection from a drop down list it then populates details about the selection in text boxes. I am writing this as three classes the main class, the UI (User Interface class) and a third class was to hold StringArrays[ ] for various models of car for example.

My issue is I am struggling to access the StringArrays elements from the other class.The code below has it in the same class and this works.

I have done this with sortedList -within the code below- without problem but ideally wanted to use StringArrays and as a seperate class.

Is it possible to explain to me how I access an element of a StringArray from another class. If I try to basically access an element from the StringArray in a seperate class from the UI it advises that it does not see the variable Anglia(see below)

my main class as follows (All works)

package brandspecer;

/**
 *
 * @author Ian
 */
public class Main {
    
   
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       UI tester = new UI(); 
    }
    
}

MY UI Code not finished but all working and what's there functions.

package brandspecer;

/**
 *
 * @author Ian
 */
   
    /** Creates a new instance of UI */
   
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java .awt.event.*;
/**
 *
 * @author Ian
 */
public class UI {
    JList jlist;
    JLabel jlab;
    JTextField jtxt1;
    JTextField jtxt2;
    
    JScrollPane jscrlp;
    JButton jbtnBuy;
    String speed = new String("   Speed ");
    String choice;
    String ABIB[] = new String[] {"Cort","Ford","Cortina","1979","GREY","2.0","OHV","15 to 17s","116" };// The StringArray can be used with the UI class
    
    sortedList model = new sortedList();// This works and calls a sortedList from another class.
    // fill model
    JList list = new JList(model);
    
    /** Creates a new instance of UI */
    public UI() {
        // Create JFrame container to begin.
        JFrame jfrm = new JFrame("UI Demo");
        
        // Specify a layout.
        jfrm.getContentPane().setLayout(new FlowLayout());
        
        // Set initial size of frame.
        jfrm.setSize(220, 350);
        
        // Terminate the program when user closes the application.
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        
        
        //Set the list selection mode to single selection.
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        //Add list to a scroll pane.
        jscrlp = new JScrollPane(list);
        
        // Set the preffered size of the scroll pane.
        jscrlp.setPreferredSize(new Dimension(197, 120));
        
        // Make a label that displays the selection.        
        jlab = new JLabel("   Please  select  a  make   ");
        
        //Add a selection listener for the list.
        list.addListSelectionListener(new ListSelectionListener()
        {
            public void valueChanged(ListSelectionEvent le)
            {
                //get the index of the item selected.
                int idx = list.getSelectedIndex();
                //Display selection.
                if(idx != -1)
                    jlab.setText("Current selection " + model.getElementAt(idx));
                else
                    jlab.setText("  Please select a make  ");
            
            }
        }  );
        
        
        
        jbtnBuy = new JButton("Choose Brand"); 
        jbtnBuy.addActionListener( new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                int idx = list.getSelectedIndex();
                if(idx != -1)
                    jlab.setText("You selected " + model.getElementAt(idx));
                if(idx == 0)
                {
                 jtxt1.setText("Info 1 = "+ ABIB[7]);
                 jtxt2.setText("Info 2 = " + ABIB[6]);
                }
                else
                    jlab.setText("No Make selected");
            }
        });
        
        //Create JTextField for answer.
        jtxt1 = new JTextField(speed,15);
        jtxt2 = new JTextField(" ",15);
        jfrm.getContentPane().add(jscrlp);
        jfrm.getContentPane().add(jbtnBuy);
        jfrm.getContentPane().add(jlab);
        jfrm.getContentPane().add(jtxt1);
        jfrm.getContentPane().add(jtxt2);
        
    jfrm.setVisible(true);
        }
    }

And finally my StringArray class code (I have not added the code for the SortedList class shown in the UI code above as this works and is not in question)

package brandspecer;
import javax.swing.*;
import java.util.*;
/**
 *
 * @author Ian
 */
public class StringArrays 
{
        
      public String Anglia[];


   
    /** Creates a new instance of StringArrays */
    public StringArrays() 
    {
        
       String Anglia[]={"Anglia","933cc","109E","39 - 48","4 cyl SV","Petrol","2 door","0-60 (N/A)","55,807" }; 
    }
    
  // its this string I want to access.  
}

Your public variable is an instance variable, so you need an instance of StringArrays to access it OR you can make it static and access it via the class name, ie

// instance version - how to reference
 StringArrays sa = new StringArrays();
 ... sa.Anglia;

// static version - how to reference
  StringArrays.Anglia;

Either way you have a serious bug in your code. You declare the public array on line 11, but in the constructor (line 19) you declare another array with the same name - this "hides" the public one, and is discarded at the end of the constructor, leaving the public variable un-initialised.

Thank you for the reply and apologies for the bug I have been chopping and changing lines of code and had not finished my housekeeping.
I think I understand the header code you have noted & was looking at the instance version but its the body code that then goes onto access the elements of the StringArray I am getting lost with.

// instance version - how to reference
 StringArrays sa = new StringArrays();
 ... sa.Anglia;

Any further help appreciated

Ian

// instance version - how to reference
StringArrays sa = new StringArrays();
for (i=0; i<sa.Anglia.length; i++)
   System.out.println(sa.Anglia[i]);

OR

String[] localRefToArrayInOtherlass = new StringArrays().Anglia;
for (i=0; i<localRefToArrayInOtherlass .length; i++)
   System.out.println(localRefToArrayInOtherlass[i]);

...

Thank you again for the response but this is the approach I had thought was correct and had already followed. This, even using your code snippet, errors as it does not recognize the variable Anglia. I'm clearly doing this wrong but I cannot see why at the moment.

Ian

// instance version - how to reference
StringArrays sa = new StringArrays();
for (int i=0; i<sa.Anglia.length; i++)
   System.out.println(sa.Anglia[i]);

...

This is going to be some silly typo thing, so
Can you post the most recent def of the StringArrays class and the full compiler error message with the exact line it's referring to?

This is going to be some silly typo thing, so
Can you post the most recent def of the StringArrays class and the full compiler error message with the exact line it's referring to?

James I know your right it will be a dumb error on my part, thank you for looking at this.
in the UI code i have updated it to use code in your format as suggested

/*
 * UI.java
 *
 * Created on 26 October 2010, 13:01
 *
 * General Practice for UI project
 */

package brandspecer;

/**
 *
 * @author Ian
 */
   
    /** Creates a new instance of UI */
   
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java .awt.event.*;
import java.util.*;
/**
 *
 * @author Ian
 */
public class UI {
    JList jlist;
    JLabel jlab;
    JTextField jtxt1;
    JTextField jtxt2;
    
    JScrollPane jscrlp;
    JButton jbtnBuy;
    String speed = new String("   Speed ");
    String choice;
    String ABIB[] = new String[] {"Cort","Ford","Cortina","1979","GREY","2.0","OHV","15 to 17s","116" };
    
    sortedList model = new sortedList();
    StringArrays sa = new StringArrays();
   
    // fill model
    JList list = new JList(model);
    
    /** Creates a new instance of UI */
    public UI() {
        // Create JFrame container to begin.
        JFrame jfrm = new JFrame("UI Demo");
        
        // Specify a layout.
        jfrm.getContentPane().setLayout(new FlowLayout());
        
        // Set initial size of frame.
        jfrm.setSize(220, 350);
        
        // Terminate the program when user closes the application.
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        
        
        

        
        
        
        
        
        //Set the list selection mode to single selection.
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        //Add list to a scroll pane.
        jscrlp = new JScrollPane(list);
        
        // Set the preffered size of the scroll pane.
        jscrlp.setPreferredSize(new Dimension(197, 120));
        
        // Make a label that displays the selection.        
        jlab = new JLabel("   Please  select  a  make   ");
        
        //Add a selection listener for the list.
        list.addListSelectionListener(new ListSelectionListener()
        {
            public void valueChanged(ListSelectionEvent le)
            {
                //get the index of the item selected.
                int idx = list.getSelectedIndex();
                //Display selection.
                if(idx != -1)
                    jlab.setText("Current selection " + model.getElementAt(idx));
                else
                    jlab.setText("  Please select a make  ");
            
            }
        }  );
        
        
        
        jbtnBuy = new JButton("Choose Brand"); 
        jbtnBuy.addActionListener( new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                int idx = list.getSelectedIndex();
                if(idx != -1)
                    jlab.setText("You selected " + model.getElementAt(idx));
                if(idx == 0)
                {
                 for (int i=0; i<sa.Anglia.length; i++)

                    System.out.println(sa.Anglia[i]); 

                   // jtxt1.setText("Info 1 = "+ Anglia[1]); //code taken out
                 //jtxt2.setText("Info 2 = " + ABIB[6]);//code taken out
                }
                else
                    jlab.setText("No Make selected");
            }
        });
        
        //Create JTextField for answer.
        jtxt1 = new JTextField(speed,15);
        jtxt2 = new JTextField(" ",15);
        jfrm.getContentPane().add(jscrlp);
        jfrm.getContentPane().add(jbtnBuy);
        jfrm.getContentPane().add(jlab);
        jfrm.getContentPane().add(jtxt1);
        jfrm.getContentPane().add(jtxt2);
        
    jfrm.setVisible(true);
        }
    }

The StringArrays code is as follows

package brandspecer;

import javax.swing.*;
import java.util.*;
/**
 *
 * @author Ian
 */
public class StringArrays 
{
        
    StringArrays Anglia = new StringArrays();
    
    /** Creates a new instance of StringArrays */
    StringArrays() 
    {
        
       String Anglia[]={"Anglia","933cc","109E","39 - 48","4 cyl SV","Petrol","2 door","0-60 (N/A)","55,807" }; 
    }
    
    
}

The Netbeans error is as follows it is currently not stating the variable error but has changed as below

init:
deps-jar:
Compiling 2 source files to C:\Documents and Settings\Ian\BrandSpecer\build\classes
C:\Documents and Settings\Ian\BrandSpecer\src\brandspecer\UI.java:108: cannot find symbol
symbol  : variable length
location: class brandspecer.StringArrays
                 for (int i=0; i<sa.Anglia.length; i++)
C:\Documents and Settings\Ian\BrandSpecer\src\brandspecer\UI.java:110: array required, but brandspecer.StringArrays found
                    System.out.println(sa.Anglia[i]); 
Note: C:\Documents and Settings\Ian\BrandSpecer\src\brandspecer\sortedList.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
2 errors
BUILD FAILED (total time: 2 seconds)

You changed
public String Anglia[];
to
StringArrays Anglia = new StringArrays();

While that's not necessarily a bad thing to do, it does invalidate all the code that assumed Anglia was an array of Strings.

And, the declaration of a new Anglia variable in the constructor is still a major error - its scope is limited to the constructor and it is lost as soon as the constructor is finished.


Thank you James, if you stick your head outside you may hear the sound of a penny dropping in Berkshire! I re arranged the code layout and variable declaration for StringArrays as you hinted at and it now works as I had hoped.

Best wishes

Ian

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.