简体   繁体   中英

How to add continuously data from JTextField to JTable

I want to add continuously data from JTextFields to a Jtable . When I click add button, the text from the JTextFields have to be inserted in the Jtable.

This code generates only one row when I click the add button. I want the row to be added to the previous rows inserted.

    public void actionPerformed(ActionEvent arg0) {
        DefaultTableModel model = new DefaultTableModel();
        table_1.setModel(model);
        model.addColumn("Product Name");
        model.addColumn("Product Price");
        model.addColumn("Quantity"); 
        String name = jFrame_pName.getText().trim();
        String price = jFrame_pPrice.getText().trim();
        String quantity = jFrame_quantity.getText().trim();
        String st[] = {name, price, quantity};
        model.addRow(st);
    }

Do I need to add an EventHandler to my table? Thank you. Please help me with my assignment.

Move this part:

    DefaultTableModel model = new DefaultTableModel();
    table_1.setModel(model);
    model.addColumn("Product Name");
    model.addColumn("Product Price");
    model.addColumn("Quantity"); 

to your constructor and define model as an instance member. Don't create table model for each button click. Below part is enough for actionPerformed .

public void actionPerformed(ActionEvent arg0) { 
    String name = jFrame_pName.getText().trim();
    String price = jFrame_pPrice.getText().trim();
    String quantity = jFrame_quantity.getText().trim();
    String st[] = {name, price, quantity};
    model.addRow(st);
}

Edit:

If you share your full code, I can tell you where to put the above parts. But for now, below example code can guide you.

public class TableClass {
     DefaultTableModel model;

     public TableClass() {
        model = new DefaultTableModel();
        table_1.setModel(model);
        model.addColumn("Product Name");
        model.addColumn("Product Price");
        model.addColumn("Quantity"); 


        JButton addButton = JButton("Add");
        addButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                 String name = jFrame_pName.getText().trim();
                 String price = jFrame_pPrice.getText().trim();
                 String quantity = jFrame_quantity.getText().trim();
                 String st[] = {name, price, quantity};
                 model.addRow(st);
            }
        })
     }
}

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