gpt4 book ai didi

Java GUI 将 JList 添加到另一个文件中的类

转载 作者:行者123 更新时间:2023-11-29 05:45:51 25 4
gpt4 key购买 nike

我试图调用我在一个类中的 JList 并将其添加到另一个类中但无济于事,因为它告诉我有关静态和非静态函数的信息

我在一个类中有一个名为 finalList 的 ArrayList,其中填充了值,并且已经通过打印列表进行了检查。

然后我在另一个名为 cupboard 的文件中有另一个类,我想在其中将项目放入 JList 中。

    finalList.add(si);

是添加项目的地方,其中 si 是数组项目,finalList 是新数组然后在我的橱柜类文件中,目前我有

    public Cupboard() 
{
cupboardContent = new JList(ShoppingList.finalList.toArray());
}

cupboardContent 是新的 JList,我希望将项目放在其中。

如果有人有任何想法,谢谢。我敢肯定这是直截​​了当的事情,我只是很愚蠢!似乎在将正常流程与 GUI 相结合时,因为我是使用 GUI 的新手,所以我很难建立联系!

//编辑

是的,第一段代码完全可以将项目添加到数组中,但我需要弄清楚如何在新类中调用它。目前,这就是我所拥有的

    public class KitchenCupboard extends JPanel //implements ActionListener
{
private JList cupboardContent;
private JButton usedItem;

ShoppingList items = new ShoppingList();

public KitchenCupboard()
{
System.out.println(ShoppingList.finalList);

cupboardContent = new JList(items.finalList.toArray());
cupboardContent.setVisibleRowCount(10);
cupboardContent.setFixedCellHeight(30);
cupboardContent.setFixedCellWidth(200);
cupboardContent.setFont(new Font ("sansserif", Font.BOLD, 13));
cupboardContent.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
add(new JScrollPane(cupboardContent));
}

ShoppingList中的数组是

    static ArrayList<ShoppingItem> finalList = new ArrayList<ShoppingItem>();

它使用两个类/文件:ShoppingList.java 和 KitchenCupboard.java

最佳答案

因为 finalList 是 ShoppingList 的成员,所以您可以做以下两件事之一。要么:

将 finalList 声明为 ShoppingList 的 static 成员,从而允许您完全按照上面的方式访问它:

cupboardContent = new JList(ShoppingList.finalList.toArray());

或者将对 ShoppingList 对象的引用传递到 Cupboard 的构造函数中,从而允许您通过该引用访问 finalList:

public Cupboard(ShoppingList list) 
{
cupboardContent = new JList(list.finalList.toArray());
}

然后创建一个新的橱柜:

Cupboard c = new Cupboard(<some ShoppingList instance>);

我还可以建议您将生成的数组转换为您需要的类型吗,因为 Java 7 引入了新的基于泛型的 swing 组件,因此 finalList 中的任何内容的数组可能更有用。

关于Java GUI 将 JList 添加到另一个文件中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15888536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com