dimanche 28 juin 2015

Populate a JCombo Box with each element of Array in Java

Please forgive me, I'm new to Java.

Basically I'm trying to display every element of an Array (i.e. peopleInfo[0], peopleInfo[1], and peopleInfo[2] ) into a JComboBox. I have added elements to the Array from a text file. However when I try to display the elements of the array in the JComboBox only the first element is displayed which is not what I want.

I have attempted to correct this by using a for loop however when I did this it didn't seem to correct my problem however I don't know whether I coded it correctly.

My code currently is:

private JComboBox mainComboBox;
private JComboBox subComboBox;
private Hashtable subItems = new Hashtable();

public SplitFile() throws FileNotFoundException, IOException
{

    BufferedReader bReader = new BufferedReader(new FileReader("organisms.txt"));

    bReader.readLine(); // this will read the first line


    String line = null;
    while ((line = bReader.readLine()) != null){

        //removes the first space 
        String test = line.replaceFirst("\\s+", "");

        //used regex lookaround to split wherever there are 3 capital letters present, or where any of the tree are present
        String[] peopleInfo = test.split("(\\p{Upper}(?=\\p{Upper})\\p{Upper}\\p{Upper})|(?=Chromalveolata)|(?=Metazoa)|(?=Mycetozoa)|(?=Viridiplantae)|(?=Viruses)|\\;");

        //creates arrays for id, organism and tree
        String id = ">" + peopleInfo[0];
        String organism = peopleInfo[1];
        String tree = peopleInfo[2].replaceAll(";", "").replaceAll("\\d+.*", "");
       System.out.println(tree);
       ArrayList<String> testArray = new ArrayList<String>();
    String[] items = { tree , "Color", "Shape", "Fruit" };


    mainComboBox = new JComboBox( items );
    mainComboBox.addActionListener( this );

    getContentPane().add( mainComboBox, BorderLayout.WEST );

    //  Create sub combo box with multiple models

    //this code displays values dependent on what element is selected from the mainComboBox

    subComboBox = new JComboBox();
    subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
    getContentPane().add( subComboBox, BorderLayout.EAST );

    String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
    subItems.put(items[1], subItems1);

    String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
    subItems.put(items[2], subItems2);

}}

@Override
public void actionPerformed(ActionEvent e)
{
    String item = (String)mainComboBox.getSelectedItem();
    Object o = subItems.get( item );

    if (o == null)
    {
        subComboBox.setModel( new DefaultComboBoxModel() );
    }
    else
    {
        subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
    }
}

Any help would be much appreciated!

Thanks :)

Aucun commentaire:

Enregistrer un commentaire