开发者

Java ArrayLists into JList

OK so I'm doing a small part of my inventory. I got MOST of it down. I'm trying to add string items to an ArrayList then add that to a JList. However, I'm getting this error when I compile:

C:\Users\Dan\Documents\DanJavaGen\inventory.java:30: cannot find symbol
symbol  : constructor JList(java.util.ArrayList<java.lang.String>)
location: class javax.swing.JList
        list = new JList(arr);

It's probably some rookie mistake I am making ... :/

Code:

import java.applet.Applet;
import java.awt.*;
import javax.swing.*;
import javax.swing.JList;
import java.awt.event.*;
import java.util.ArrayList;
import java.io.*;
import java.util.*;

public class inventory extends JApplet implements MouseListener {

public static String newline;
public static JList list;
int gold = 123;

    public void init() {



ArrayList<String> arr = new ArrayList<String>();
arr.add("Hatchet");
arr.add("Sword");
arr.add("Shield");
arr.add(gold + " Gold");
System.out.println("You have " + arr.size() + " items in your inventory.");
showInventory(arr);



        list = new JList(arr);

        add(list);

        list.addMouseListener(this);

        list.setVisible(true)开发者_运维技巧;

    }

public static void showInventory (ArrayList<String> theList) {
for (int i = 0; i < theList.size(); i++) {
System.out.println(theList.get(i));
}
}


    public void mousePressed(MouseEvent e) { }

    public void mouseReleased(MouseEvent e) {
        Object index = list.getSelectedValue();
       System.out.println("You have selected: " + index);
    }

    public void mouseEntered(MouseEvent e) { }

    public void mouseExited(MouseEvent e) { }

    public void mouseClicked(MouseEvent e) { }




    public void paint(Graphics g) {

    }
}


JList provides a constructor JList(Object[]) which you can call after unpacking your ArrayList<String> using toArray():

list = new JList(arr.toArray())


Try this:

DefaultListModel listModel = new DefaultListModel();
for (int i = 0; i < arrayList().size(); i++)
{
    listModel.addElement(arrayList().get(i));
}
jList1.setModel(listModel);


I had trouble with toArray() and JList for my project as well. Did some research and tried a few things and found something that works. Hope it helps everyone:

ArrayList<String> i = new ArrayList<>();
String[] str = new String[i.size()];
//Assuming there is data in your list
JList<String> list = new JList<>(i.toArray(str));


I had trouble with the toArray() method causing exceptions, so I built a quick generic method to convert. Maybe someone will find it useful as well. I know this is an old post but I'll bet it's still viewed from time to time. Here's the method:

private <T> void populateArrayFromList(T[] arr, ArrayList<T> arrayList) {
    System.out.println("Array size " + arr.length);
    System.out.println("ArrayList size " + arrayList.size());
    for (int i = 0; i < arrayList.size(); i++) {
        arr[i] = arrayList.get(i);
    }
}

Just create the array before you pass it in, like

String[] arr = new String[arrayList.size()];

Then just call it from your code

populateArrayFromList(arr, arrayList);


Constructor Summary
JList() Constructs a JList with an empty, read-only, model.
JList(ListModel dataModel) Constructs a JList that displays elements from the specified, non-null, model.
JList(Object[] listData) Constructs a JList that displays the elements in the specified array.
JList(Vector<?> listData) Constructs a JList that displays the elements in the specified Vector.


I simply implemented the ListModel interface:

    package proba;

    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.util.ArrayList;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.ListModel;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListDataListener;

    public class Proba extends JFrame {
        ArrayList<String> al = new ArrayList<>();
        public Proba() {
            al.add("1111111");
            al.add("2222222");
            al.add("3333333");
            setLayout(new BorderLayout());
            MyListModel lm = new MyListModel();
            JList l = new JList(lm);
            l.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            JScrollPane sp = new JScrollPane(l);
            add(sp, BorderLayout.CENTER);
        }

        class MyListModel implements ListModel {
            @Override
            public int getSize() {
                return al.size();
            }
            @Override
            public Object getElementAt(int index) {
                return al.get(index);
            }
            @Override
            public void addListDataListener(ListDataListener l) {
            }
            @Override
            public void removeListDataListener(ListDataListener l) {
            }
        }

        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    Proba app = new Proba();
                    app.setSize(600, 480);
                    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    app.setVisible(true);
                }
            });
        }
    }


if you are using drag and drop components then, name your list as "itemList" and I suppose that arr is the name of your arraylist which contains some string data then :

`DefaultComboBoxModel model=
new DefaultComboBoxModel(arr.toArray(new String[arr.size()]));
itemList.setModel(model);`

I hope this will work for you.


You can pass Object superclass as type of the JList.

ArrayList<String> arr = new ArrayList<String>();

arr.add("Hatchet");
arr.add("Sword");
arr.add("Shield");

JList<Object> list = JList<Object>(arr.toArray());


if you have a loop in for gaining data in mysql you can put like this

     while(result.next()){
     itemid = result.getInt("id");
     itempice = result.getInt("price");
     itemname = result.getString("itemname");
     arraylist.add(itemname+" Price: "+itempice);
     }
     jList.setListData(arraylist.toArray());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜