1

I have a JTable with a default table model which I am using to display a result set. I am using postgreSQL. I am trying to get the table to exclude Primary and foreign keys. So far I have gotten it to exclude the primary keys but I have been unsuccessful in excluding the foreign keys.

This is how I am getting the foreign keys:

public List<String> getFKeyData(String tableName, int i) throws SQLException {
    DatabaseMetaData dm = connection.getMetaData();
    ResultSet rs = dm.getImportedKeys(null, null, tableName);
    ArrayList<String> fkTableData = new ArrayList<>();
    while (rs.next()) {
        fkTableData.add(rs.getString(i));
    }
    return fkTableData;
}

This is how I initially thought to exclude the foreign keys:

int fkSize = databaseConnection.getFKeyData(tableName, 8).size();

for (int i = 0; i <= fkSize - 1; i++) {
    if (databaseConnection.getColumnNames(tableName).indexOf(databaseConnection.getFKeyData(tableName, 8).get(i)) == 1) {
         if (databaseConnection.getColumnNames(tableName).indexOf(databaseConnection.getPKey(tableName)) != 1) {
                if (databaseConnection.getColCount(tableName) >= 1) {
                    model.addColumn(columnNamesV.get(1), cellData1);
                }
            }
      }
}

I now realize this was foolish because although it does exclude the foreign key it is added to the model anyway by the for statement. Does anyone know a way around this?

Dáire
  • 65
  • 1
  • 1
  • 5

2 Answers2

2

Instead of using DefaultTableModel, extend AbstractTableModel, in which you can control the results returned by getColumnCount() and getValueAt().

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • Is there any way to put in a range instead of i for get(i) (ie. i = 1 to fkSize) – Dáire Sep 12 '13 at 10:51
  • It depends on the internal structure of your `TableModel`, for [example](http://stackoverflow.com/a/9134371/230513). – trashgod Sep 12 '13 at 11:45
  • Thanks for all your help I'm sure your way works well but I don't know anything about abstract table models and I didn't want to go messing around with them in this program as it is nearly finished – Dáire Sep 16 '13 at 10:38
0

This is what I wanted. Simple but it works the way I want it to.

    ArrayList fkIndex = new ArrayList();

    for (int i = 0; i <= fkSize - 1; i++){
    fkIndex.add(databaseConnection.getColumnNames(tableName).indexOf(databaseConnection.getFKeyData(tableName, 8).get(i)));
    }

    if (databaseConnection.getColumnNames(tableName).indexOf(
            databaseConnection.getPKey(tableName)) != 1) {
        if (fkIndex.contains(1) == false) {
            if (databaseConnection.getColCount(tableName) >= 1) {
                model.addColumn(columnNamesV.get(1), cellData1);
            }
        }
    }
Dáire
  • 65
  • 1
  • 1
  • 5
  • If you stay with `DefaultTableModel`, you can update the column names as shown [here](http://stackoverflow.com/a/18818681/230513). – trashgod Sep 16 '13 at 12:30