[英]add items to a list box in Java/NetBeans
I'm using NetBeans to teach myself some java, and have covered most of the basics and I'm now trying to import data from a database and display some of it in a list box. 我正在使用NetBeans来教自己一些Java,并且涵盖了大多数基础知识,现在我正尝试从数据库中导入数据并在列表框中显示其中的一些数据。 My issue is with putting the data in a list box.
我的问题是将数据放在列表框中。 I have a form with various buttons and stuff on it, and I've dragged a list box from the Swing Controls pane in NetBeans onto the form.
我有一个带有各种按钮和内容的表单,并且已经从NetBeans的Swing控件窗格中将一个列表框拖到该表单上。 I've deleted the elements in it, and as far as I can find, google seems to point me towards creating a Default list model, filling it, and then using that to populate my list box like so:
我已经删除了其中的元素,据我所知,谷歌似乎将我指向创建默认列表模型,填充它,然后使用它来填充我的列表框,如下所示:
DefaultListModel listModel;
listModel = new DefaultListModel();
try{
con = DriverManager.getConnection( host, uName, uPass );
stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );
String SQL = "SELECT * FROM `items`";
items_rs = stmt.executeQuery( SQL );
while(items_rs.next()){
int sn_col = items_rs.getInt("Serial_num");
String sn = Integer.toString(sn_col);
listModel.addElement(sn);
}
JList serialNumbers = new JList(listModel);
}
catch(SQLException err) {
JOptionPane.showMessageDialog(this,err.getMessage());
}
Only, it doesn't work. 只是,它不起作用。 I've tested the above in a different project where I don't drag and drop the box onto the form, and instead add it using code and it seems to work fine (based on this example: http://www.java2s.com/Tutorial/Java/0240__Swing/UsingJList.htm ).
我已经在另一个项目中测试了上述内容,在该项目中,我没有将框拖放到表单上,而是使用代码添加了它,并且看起来效果很好(基于此示例: http://www.java2s。 com / Tutorial / Java / 0240__Swing / UsingJList.htm )。 Anyone able to tell me how to do it with a drag and drop list box?
有人能告诉我如何使用拖放列表框吗?
Finally found the answer I was after. 终于找到了我想要的答案。 Turns out I needed one line changed:
原来我需要更改一行:
serialNumbers.setModel(listModel);
Intead of 的
JList serialNumbers = new JList(listModel);
And hey presto! 嘿,presto! It's working.
工作正常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.