我有一个类保存菜单项的属性。我需要填充三个JLists。我该怎么办? [英] I have a class which holds attributes for a menu item. I need to populate three JLists. How can I do so?
问题描述
菜单项 MenuItem
类中的属性包括名称,价格,卡路里和描述。三个 JList
组件称为 startersList
, mainsList
code> dessertsList ,并且在 JFrame
中调用 foodOptionGUI
The attributes in the MenuItem
class for the menu item's include name, price, calories and description. The three JList
components are called startersList
, mainsList
and dessertsList
, and are in a JFrame
called foodOptionGUI
目前我已使用以下内容填充列表:
At the moment I have populated the lists through using:
startersList.setListData(starters);
(这只是一个临时修复)
(This is only a temporary fix)
我的问题是我不知道如何列出所有的起动器,主菜和甜点,包括他们的名字,价格,卡路里和描述,分成三个单独的名单。
My problem is I'm not sure how to list all the starters, mains and desserts including their name, price, calories and description, into the three separate lists.
public class MenuItem {
private String name;
private String price;
private String descriptions;
private int calories;
public MenuItem(String Name, String Price, String desc, int cal) {
name = Name;
price = Price;
descriptions = desc;
calories = cal;
}
public String getPrice(){
return price;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getDescriptions(){
return descriptions;
}
public void setDescriptions(String desc){
this.descriptions = desc;
}
public int getCalories(){
return calories;
}
public void setCalories(int cal){
this.calories = cal;
}
public String toString(){
return name + ", " + price + ", " + calories + ", " + descriptions ;
}
}
推荐答案
startersList.addMenuItem("soup", "3", "300", "soup of the day");
但它的错误和不工作
But its wrong and doesnt work
好,a JList
没有addMenuItem方法。
Well a JList
doesn't have an "addMenuItem" method.
您可以向 ListModel
中添加数据。然后将 ListModel
添加到 JList
。
You add data to the ListModel
. Then you add the ListModel
to the JList
.
阅读如何使用列表中的Swing教程中的部分演示代码你可以下载。
Read the section from the Swing tutorial on How to Use Lists for demo code you can download.
在示例代码 String
中,数据被添加到 ListModel
。在你的情况下,你想要添加一个 MenuItem
对象到模型,所以你首先需要创建一个实例 MenuItem
对象,然后再将其添加到模型中。
In the demo code String
data is added to the ListModel
. In your case you want to add a MenuItem
object to the model, so you first need to create an instance of each MenuItem
object before you add it to the model.
因此,教程和代码的基本区别是:
So the basic difference in the code from the tutorial and your code will be:
listModel = new DefaultListModel();
listModel.addElement( new MenuItem(values for item 1) );
listModel.addElement( new MenuItem(values for item 2) );
list = new JList(listModel);
这篇关于我有一个类保存菜单项的属性。我需要填充三个JLists。我该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!