-3

I'm using netbeans and there is a table there. I just want to add data to it using a textfield and a button click. I'm just exploring. Please help.

user3260589
  • 168
  • 1
  • 3
  • 12

2 Answers2

1

Example:

Create the columns:

String[] columnNames = {"School Name",
                    "Module Name",
                    "Grade",
                    "# of Years",
                    "Graduaded"}

Add data:

Object[][] data = {
{"Some High School", "Computing",
 "A", new Integer(5), new Boolean(false)},
{"Some other High school", "Maths"
 "A", new Integer(3), new Boolean(true)},
};

Constructor:

JTable table = new JTable(data, columnNames); 

I'm not using any IDE. I hope that this gives you an insight though. More info at:http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#simple

Stelios Voskos
  • 526
  • 5
  • 16
1

If you want to add rows dynamically, you want to make use of the DefaultTableModel. By default on NetBeans, the TableModel given to JTables are DefaultTableModel. You can its methods and API here.

What you want to do is use the methos addRow(...), which will update your table for you every time you add a row.

You can use the graphical design view to set the headers.

  1. Highlight/select the table from design view.
  2. Go to the properties window on the right.
  3. Click the ... on the right of the model property
  4. In the Table Setting tab set the rows to 0 and the number of columns you want. You can click on each column to give it a title header.

When you want to add rows dynamically, say after entering text in a few fields you can do something like this

private void jButton1ActionPerformed(java.awt.event.ActionEvent e) {

    DefaultTableModel model = (DefaultTableModel)jTable2.getModel();
    String firstName = jTextField1.getText();
    String mi = jTextField2.getText();
    String lastName = jTextField3.getText();

    String[] row = {firstName, mi, lastName};
    model.addRow(row);
}
Paul Samsotha
  • 197,959
  • 33
  • 457
  • 689