项目无法添加到jList中。

huangapple go评论74阅读模式
英文:

Item Cannot added in to the jList

问题

// 以下是要翻译的内容:

我正在使用Java创建一个简单的库存系统当我添加产品名称价格数量后点击添加按钮产品信息应该被添加到JList中但实际上它没有被添加进去出现了错误

**java.lang.ClassCastException: 无法将javax.swing.JList$3转换为javax.swing.DefaultListModel**

DefaultListModel model;
String panme = (txtpname.getText());
int price = Integer.parseInt(txtprice.getText());
int qty = Integer.parseInt(txtqty.getText());
int tot = qty * price;

model = (DefaultListModel)jList1.getModel();

model.addElement(new Object[]
        {
            panme ,
            price,
            qty,
            tot, 
        });
}
英文:

i am creating simple inventry system in Java.when i add the productname,price,qty click add button product information should added into the JList.how it didn't added. got the Error.

java.lang.ClassCastException: javax.swing.JList$3 cannot be cast to javax.swing.DefaultListModel

 DefaultListModel model;
 String panme = (txtpname.getText());
                int price = Integer.parseInt(txtprice.getText());
                int qty = Integer.parseInt(txtqty.getText());
                int tot = qty * price;
            
                 
                model = (DefaultListModel)jList1.getModel();
                
                model.addElement(new Object[]
                        {
                            panme ,
                            price,
                            qty,
                            tot, 
                        });
        }                                        

答案1

得分: 1

如果您创建一个JList,可以使用空构造函数或使用数组或向量,那么将创建一个只读的ListModel

如果您希望能够修改ListModel,则需要将DefaultListModel明确添加到JList中:

JList list = new JList(new DefaultListModel());

然后在您的上述方法中,您将能够将该模型作为DefaultListModel访问。

话虽如此,您不应该对此使用JList,因为您正在添加多个属性。相反,您应该使用JTable,它允许您添加可以按行/列显示的数据。

阅读 Swing 教程中关于如何使用表格的章节,获取更多信息。

英文:

If you create a JList an empty constructor or using an Array or Vector, then a read only ListModel is created.

If you want to be able to modify the ListModel then you need to specifically add a DefaultListModel to the JList:

JList list = new JList( new DefaultListModel() );

Then in your above method you will be able to access the model as a DefaultListModel.

Having said that, you should NOT be using a JList for this since you are adding multiple properties. Instead you should use a JTable which allows you to add data that you can display in rows/columns.

Read the section from the Swing tutorial on How to Use Tables for more information.

huangapple
  • 本文由 发表于 2020年9月12日 12:49:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/63856910.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定