2

I have a code for making table and sort the data that input there. What if I want to add some action using button to add the row than fill the data and can delete the row too. Here is my code:

public class TableSortDemo extends JPanel {
    private boolean DEBUG = false;

    class MyTableModel extends AbstractTableModel {
        private String[] columnNames = {"Nama",
                                        "NIM",
                                        "IPK"};
        private Object[][] data = {
        {"", new Integer(0),new Double(0)}
        };

        public boolean isCellEditable(int row, int col) {
            if (col < 2) {
                return false;
            } else {
                return true;
            }
        }
        public void setValueAt(Object value, int row, int col) {
            if (DEBUG) {
                System.out.println("Setting value at " + row + "," + col
                                   + " to " + value
                                   + " (an instance of "
                                   + value.getClass() + ")");
            }

            data[row][col] = value;

        }

        private void printDebugData() {
            int numRows = getRowCount();
            int numCols = getColumnCount();

            for (int i=0; i < numRows; i++) {
                System.out.print("    row " + i + ":");
                for (int j=0; j < numCols; j++) {
                    System.out.print("  " + data[i][j]);
                }
            }
        }
    }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

1
  1. For JTable based on AbstractTableModel is required to override

  2. I'd be use DefaultTableModel (see my post, how easy everything could be), strongly recomend for newbee

  3. everything is described in JTable tutorial, rest is (correctly) in concrete APIs

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
0

Firstly, why don't you use an ArrayList to represent your entities being displayed in the rows. Instead of :

private Object[][] data = {
{"", new Integer(0),new Double(0)}
};

Have something like :

private ArrayList<Thing> myThings;

It makes things soooo much simpler.

If you want to add or remove rows, then just add two methods to the table model such as :

public void addThing(Thing t) {..}
public void removeThing(Thing t) {..}

And follow it up with a fireTableDateChanged();

Oliver Watkins
  • 12,575
  • 33
  • 119
  • 225