Java ArrayList 转换为 JList

发布于 2024-09-10 09:56:34 字数 1666 浏览 4 评论 0原文

好的,我正在做库存的一小部分。我把大部分都记下来了。我正在尝试将字符串项添加到 ArrayList,然后将其添加到 JList。但是,我在编译时遇到此错误:

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

这可能是我犯的一些菜鸟错误...:/

代码:

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

    }
}

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

    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

亽野灬性zι浪 2024-09-17 09:56:34

JList 提供了一个构造函数 JList(E[]),您可以在使用 toArray(T[ 解压 ArrayList后调用该构造函数])

list = new JList<>(arr.toArray(new String[arr.size()]))

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()]))
差↓一点笑了 2024-09-17 09:56:34

试试这个:

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

Try this:

DefaultListModel listModel = new DefaultListModel();
for (int i = 0; i < arrayList().size(); i++)
{
    listModel.addElement(arrayList().get(i));
}
jList1.setModel(listModel);
一枫情书 2024-09-17 09:56:34

我的项目中的 toArray() 和 JList 也遇到了麻烦。做了一些研究并尝试了一些事情,发现了一些有效的方法。希望对大家有帮助:

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 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));
昨迟人 2024-09-17 09:56:34

我在使用 toArray() 方法时遇到了导致异常的问题,因此我构建了一个快速通用方法来进行转换。也许有人也会发现它很有用。我知道这是一篇旧帖子,但我敢打赌它仍然时不时地被浏览。方法如下:

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);
    }
}

只需在传入数组之前创建数组,就像

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

然后从代码中调用它一样

populateArrayFromList(arr, arrayList);

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);
爱你是孤单的心事 2024-09-17 09:56:34

构造函数摘要
JList() 使用空的只读模型构造 JList
JList(ListModel dataModel) 构造一个 JList,显示指定的非空模型中的元素。
JList(Object[] listData) 构造一个 JList,显示指定数组中的元素。
JList(Vector listData) 构造一个 JList,显示指定 Vector 中的元素。

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.

笑忘罢 2024-09-17 09:56:34

我只是实现了 ListModel 接口:

    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);
                }
            });
        }
    }

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);
                }
            });
        }
    }
狼性发作 2024-09-17 09:56:34

如果您使用拖放组件,则将列表命名为“itemList”,我认为 arr 是包含一些字符串数据的数组列表的名称:

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

我希望这对您有用。

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.

清风无影 2024-09-17 09:56:34

您可以将 Object 超类作为 JList 的类型传递。

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

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

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

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());
别理我 2024-09-17 09:56:34

如果你有一个循环来获取 mysql 中的数据
你可以这样放

     while(result.next()){
     itemid = result.getInt("id");
     itempice = result.getInt("price");
     itemname = result.getString("itemname");
     arraylist.add(itemname+" Price: "+itempice);
     }
     jList.setListData(arraylist.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());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文