简体   繁体   中英

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. 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. 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 ). 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! It's working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM