Dan The Man
Dan The Man

Reputation: 43

Display Array contents in a JComboBox

I have two classes, one with a class that reads text in a file and puts the data into a array and in the main class I want to add the array contents into a JComboBox. But I am getting the error "cannot be resolved to a variable" Any help?

readfiles.java

public class readfiles {
String [] names = new String[15];
int i = 0;
public Scanner readNames;

//Opens the file
public void openFile() {
    try {
        readNames = new Scanner(new File("ChildName.txt"));
    } catch (Exception e) {
        System.out.println("Could not locate the data file!");
    }
}

//Reads the names in the file
public void readFile() {
    while(readNames.hasNext()) {
        names[i] = readNames.next();
        System.out.println(Arrays.toString(names));
        System.out.println(names[i]);
        i++;
    }
}

//Closes the file 
public void closeFile() {
    readNames.close();
}

}

Main.java

   //JComboBox for selecting child
    JLabel selectChildName = new JLabel("Please Select Your Child:");
    sPanel.add(selectChildName);
    JComboBox<String> selectChild = new JComboBox<String>(names); // (names); is the error, cannot be resolved to a variable
                sPanel.add(selectChild);

Upvotes: 0

Views: 242

Answers (2)

Brian Thorpe
Brian Thorpe

Reputation: 327

You won't be able to access the names vairable in the main because its not in main's scope. To access it create an instance of the readfiles class and then get the names by doing instance.names;

for example,

readfiles instance = new readfiles();
instance.openfile();
instance.readfile();
instance.closefile();
JComboBox<String> selectChild = new JComboBox<String>(instance.names);

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

The names variable is a variable of the readFiles class and thus not visible in your Main class. You need to call a getter method on readFiles to get the array when you need it.

Upvotes: 0

Related Questions