简体   繁体   中英

How to add a double type value to a JTable row?

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)     
{                                         
    try {

        Connection c = DBconnection.conn();
        PreparedStatement ps = c.prepareStatement("SELECT * from menu where items=?");
        ps.setString(1, (String) jComboBox2.getSelectedItem());
        ResultSet rs = ps.executeQuery();           
        DefaultTableModel tbn = (DefaultTableModel) jTable1.getModel();

        Vector v = new Vector<>();
        v.add(jComboBox2.getSelectedItem());
       v.add(qty.getText());

After this line i need to add price which is type double,I'm fetching it from database.And I need to know how to do it.Please someone help

        tbn.addRow(v);

Here I'm calculating total.
double total=0;

        for(int i=0; i<jTable1.getRowCount(); i++)
        {
            double amount = Double.parseDouble(String.valueOf(jTable1.getValueAt(i, 2)));
            jTable1.getValueAt(i,1));
            total+=amount;
        }
        Ltot.setText(String.valueOf(total));
    } catch (Exception ex) {
        Logger.getLogger(pos.class.getName()).log(Level.SEVERE, null, ex);
    }


}                         *emphasized text*

Autoboxing should let you add the double easily:

v.add(price);

double is a primitive type , and you can't add those to Vector s, but Java has an object type corresponding to each primitive, and so it converts price into an instance of Double on the spot, and adds that instance to your Vector .

Quick sidenote: this means, among other things, that you'll pay a small price in heap space because of the new object you've created, so be a bit mindful of this if you do it a lot.

Also: DefaultTableModel is very no-frills as TableModel s go. But it can be very easy to prototype in. When you have some spare time, and if you need to improve on this code, I encourage you to look for implementations of TableModel that you'll find more suitable in various ways, such as letting you pull values out of an existing data structure instead of putting them into brand new Vector s. A good next step, for example, is to write your own implementation of TableModel for this specific table.

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