Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    }
}
like image 855
test Avatar asked Jul 16 '10 23:07

test


2 Answers

Try this:

DefaultListModel listModel = new DefaultListModel();
for (int i = 0; i < arrayList().size(); i++)
{
    listModel.addElement(arrayList().get(i));
}
jList1.setModel(listModel);
like image 194
Lakshan Avatar answered Oct 02 '22 16:10

Lakshan


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

list = new JList(arr.toArray())
like image 33
Alain O'Dea Avatar answered Oct 02 '22 15:10

Alain O'Dea