I have a JFrame
Form which has JTextField
s, JCombobox
etc. and I am able to receive those values to variables and now I want to add the received data to JTable
in new row when user clicks Add or something like that.
I have created JTable
using net-beans the problem is what would be the code to add data from those variable to the rows of table. A basic example would be appreciated. I have tried numerous example and have added the code to ActionListener
of the JButton
but nothing Happens.
The Examples I tried are. How to add row in JTable? and How to add rows to JTable with AbstractTableModel method?
Any Help would be appreciated.
To get the value from a particular grid cell, you can use the wValue property of the JTable object. The property has the Row and Column parameters which specify the row and the column that contain the cell.
addRow(new Object[]{"Column 1", "Column 2", "Column 3"}); You can also remove rows with this method. +1 This is a good answer; however, note that the DefaultTableModel is only one of many models. However, it is the easiest to use and I would recommend sticking to it unless you have to use another.
We can add or insert a JButton to JTable cell by customizing the code either in DefaultTableModel or AbstractTableModel and we can also customize the code by implementing TableCellRenderer interface and need to override getTableCellRendererComponent() method.
Peeskillet's lame tutorial for working with JTables in Netbeans GUI Builder
Add a button to the frame somwhere,. This button will be clicked when the user is ready to submit a row
Events -> Action -> actionPerformed
You should see code like the following auto-generated
private void jButton1ActionPerformed(java.awt.event.ActionEvent) {}
The jTable1
will have a DefaultTableModel
. You can add rows to the model with your data
private void jButton1ActionPerformed(java.awt.event.ActionEvent) {
String data1 = something1.getSomething();
String data2 = something2.getSomething();
String data3 = something3.getSomething();
String data4 = something4.getSomething();
Object[] row = { data1, data2, data3, data4 };
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(row);
// clear the entries.
}
So for every set of data like from a couple text fields, a combo box, and a check box, you can gather that data each time the button is pressed and add it as a row to the model.
you can use this code as template please customize it as per your requirement.
DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();
list.add(textField.getText());
list.add(comboBox.getSelectedItem());
model.addRow(list.toArray());
table.setModel(model);
here DefaultTableModel
is used to add rows in JTable
,
you can get more info here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With