获取Jlist中String的值

Getting value of String in Jlist

在这种情况下,如何获取已添加到 JList 的字符串项目的项目值?我是什么意思V

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

既然我显然不能像普通数组那样引用它,我该如何获取 coinlist[0] 的字符串值?

coinList.getModel().getElementAt(0);

请阅读手册:http://docs.oracle.com/javase/8/docs/api/javax/swing/JList.html#getModel--

编辑:或者简单地看一下年度页面操作中的示例:http://docs.oracle.com/javase/8/docs/api/javax/swing/JList.html

 // Create a JList that displays strings from an array

 String[] data = {"one", "two", "three", "four"};
 JList<String> myList = new JList<String>(data);

 // Create a JList that displays the superclasses of JList.class, by
 // creating it with a Vector populated with this data

 Vector<Class<?>> superClasses = new Vector<Class<?>>();
 Class<JList> rootClass = javax.swing.JList.class;
 for(Class<?> cls = rootClass; cls != null; cls = cls.getSuperclass()) {
     superClasses.addElement(cls);
 }
 JList<Class<?>> myList = new JList<Class<?>>(superClasses);

 // The automatically created model is stored in JList's "model"
 // property, which you can retrieve

 ListModel<Class<?>> model = myList.getModel();
 for(int i = 0; i < model.getSize(); i++) {
     System.out.println(model.getElementAt(i));
 }

这是一个简单的示例,仅获取 JList 的索引并显示所有 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));
    }
}