Search code examples
javaarraysswingjlist

Getting value of String in Jlist


How can I get the value of an item in this case String item that has been added to a JList? What I meanV

String[] coinNames ={"Quarters","Dimes","Nickels","Pennies"};
JList coinList = new JList (coinNames);
coinList[0] == "Quarters" ???????

Since I clearly can't reference it like a normal array, how might I go about getting the string value of coinlist[0]?


Solution

  • This is a simple example to get just an index to your JList and display all your JList.

    public static void main(String[] args) {
        String[] coinNames ={"Quarters","Dimes","Nickels","Pennies"};
        JList coinList = new JList (coinNames);
        String myCoin = (String) coinList.getModel().getElementAt(0);
        System.out.println(myCoin);
    
        /* LIST AL YOUR COINNAMES */
    
        System.out.println("\nCoinList\n");
    
        for(int i =0; i < coinList.getModel().getSize(); i++){
            System.out.println((String) coinList.getModel().getElementAt(i));
        }
    
        coinNames[0] = "My new Value"; // Edit your CoinNames at index 0
    
        /* LIST AL YOUR NEW COINNAMES */
    
        System.out.println("\nNew coinList edited\n");
    
        for(int i =0; i < coinList.getModel().getSize(); i++){
            System.out.println((String) coinList.getModel().getElementAt(i));
        }
    }