Java ArrayLists into JList
Asked Answered
O

9

13

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) {

    }
}
Orchidaceous answered 16/7, 2010 at 23:37 Comment(0)
B
27

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

list = new JList<>(arr.toArray(new String[arr.size()]))
Bramblett answered 16/7, 2010 at 23:50 Comment(4)
Great post ... but now I have a new error... see my new topic :|Orchidaceous
Do not ask why but this only works if you declare a generic variable of JList. Not JList<MyType> but JList, otherwise I get a lot of troubleSchoolmistress
You get runtime type errors because I messed up here and didn't provide a type safe solution. You need to provide an array of target type to ArrayList.toArray. I am a bit embarassed that I missed that. https://mcmap.net/q/903448/-arraylist-toarray-not-converting-to-the-correct-typeSupercool
I've corrected my error above.Supercool
H
6

Try this:

DefaultListModel listModel = new DefaultListModel();
for (int i = 0; i < arrayList().size(); i++)
{
    listModel.addElement(arrayList().get(i));
}
jList1.setModel(listModel);
Harryharsh answered 21/4, 2017 at 3:37 Comment(0)
J
2

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);
Jule answered 30/4, 2014 at 12:17 Comment(0)
A
2

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));
Accord answered 17/5, 2015 at 21:52 Comment(0)
S
0

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.

Store answered 16/7, 2010 at 23:41 Comment(0)
C
0

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);
                }
            });
        }
    }
Coss answered 9/11, 2017 at 8:52 Comment(0)
M
0

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.

Monogamist answered 15/1, 2019 at 9:18 Comment(0)
P
0

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());
Pallor answered 5/2, 2019 at 9:15 Comment(0)
R
0

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());
Reisfield answered 23/3, 2019 at 13:59 Comment(1)
where you got setListData function ?Darlenadarlene

© 2022 - 2024 — McMap. All rights reserved.