Question

I need to fill a Swing table with some data from MySQL DB. The problem is that the table does not display all the columns (i.e. a.aircraftType and b.aircraftCategory). In Debug mode I checked that the query returns correct data. So, why finally some columns are not displayed?

    private JTable tbArrivals;
    private QueryTableModelFS mdArrivals;


    mdArrivals = new QueryTableModelFS();       
    tbArrivals = new JTable(mdArrivals);

    private void fillArrivals() {
            mdArrivals.setHost(url); mdArrivals.setDB(db); mdArrivals.setLogin(login); mdArrivals.setPassw(passw);

            String query;

            query = "SELECT a.id,a.flightNum_arr,a.from_ICAO,a.ETA,a.pkId,a.aircraftType,b.aircraftCategory " +
                    "FROM flightschedule a, aircrafts b " +
                    "WHERE a.aircraftType = b.aircraftType;";
            mdArrivals.setQuery(query);
    }


  public void setQuery(String query) {
    cache = new Vector();
    try {
      // Execute the query and store the result set and its metadata
      Connection con = getConnection();
      Statement statement = con.createStatement();
      ResultSet rs = statement.executeQuery(query);
      ResultSetMetaData meta = rs.getMetaData();
      colCount = meta.getColumnCount();
      // Rebuild the headers array with the new column names
      headers = new String[colCount];
      for (int h = 1; h <= colCount; h++) {
        headers[h - 1] = meta.getColumnName(h);
      }
      while (rs.next()) {
        String[] record = new String[colCount];
        for (int i = 0; i < colCount; i++) {
          record[i] = rs.getString(i + 1);
        }
        cache.addElement(record);
      }
      fireTableChanged(null);         
      rs.close();
      if (con.getAutoCommit() != false) {
        con.close();
      }         
    } catch (Exception e) {
      cache = new Vector();
      e.printStackTrace();
    }
  }
Was it helpful?

Solution

I can't tell what how your TableModel works (it looks like you might be using the DefaultTableModel), but I would suggest using Vectors instead of Arrays to get the data from your ResultSet. Right now your code is very confusing. In one loop you are using (i - 1) to access the data. In the next loop you are using (i + 1). I know the reason is because Arrays are 0 based and the ResultSet is 1 based.

When you use a Vector your loops can just start with 1 and then you just use the addElement() method to add the data to the Vector so your code is not concerned with matching indexes.

See Table From Database Example in Table From Database.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top