tags:

views:

35

answers:

2

Does anyone have a good example of how to Add/Remove rows from a JTable using a custom table model? The issue I seem to be having is how to have the table keep updating when I add or remove items.

The real simple idea here is to have an add and remove button above my table which allows the user on the fly to change the table.

+2  A: 

Here is example for adding row:

import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;

public class RowAdder extends JFrame {

  final SimpleModel tableData = new SimpleModel();
  JTable table = new JTable(tableData);

  public static void main(String[] args) {
    RowAdder ra = new RowAdder();
    ra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ra.setSize(400, 300);
    ra.setVisible(true);
  }

  public RowAdder() {
    final JTextField textField  = new JTextField();
    setLayout(new BorderLayout());
    add(new JScrollPane(table), BorderLayout.CENTER);
    textField.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        tableData.addText(textField.getText());
        textField.setText("");
      }
    });
    add(textField, BorderLayout.SOUTH);
  }

}
class SimpleModel extends AbstractTableModel {

  Vector textData = new Vector();

  public void addText(String text) {
    textData.addElement(text);
    fireTableDataChanged();
  }

  public int getRowCount() {
    return textData.size();
  }

  public int getColumnCount() {
    return 3;
  }

  public Object getValueAt(int row, int column) {
    return textData.elementAt(row);
  }

}

above ref from : Swing/AddrowstoaTable.htm">http://www.java2s.com/Tutorial/Java/0240_Swing/AddrowstoaTable.htm

Checkout this tutorial about JTable:

http://download.oracle.com/javase/tutorial/uiswing/components/table.html

Specifically for table model check:

http://download.oracle.com/javase/tutorial/uiswing/components/table.html#data

I think this tutorial should answer all your question.

YoK
A: 

You have to notify the JTable object on changes of the underlying table model. The table is not observing the model but waiting for events.

After every change (or set of changes), create a TableModelEvent and call the tables tableChanged method.

Andreas_D