Aleksandar Stojanovic Aleksandar Stojanovic - 2 months ago 29
Java Question

How to add data from a DB to jTable in Java Swing when tables contain null values using joins?

Ok so i have a method that gets data from DB and puts it into a List like this :

public List<Sale> getSales() throws SQLException{
List<Sale> res = new ArrayList<Sale>();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("select sale.id,product.name,sale.price,sale.quantity,sale.total,employee.name,buyer_seller.name from sale "
+ " join product on sale.product = product.id "
+ " join employee on sale.salesman = employee.id "
+ " join buyer_seller on sale.buyer = buyer_seller.id;");
while(rs.next()){
res.add(new Sale (rs.getInt(1),new Product(-1,rs.getString(2),new Category(-1,"",""),new Manufacturer(-1,"",""),0.0,-1),rs.getDouble(3),rs.getInt(4),rs.getDouble(5),new Employee(-1,rs.getString(6),"","",new JobCategory(-1,"",""),"",""),new BuyerSeller(-1,rs.getString(7),"","","")));
}
return res;
}


and then i have a method that fills the jTable with that data :

public void fillSales(){
jLabel1.setText("Podaci se ucitavaju iz baze...");
SwingWorker sw = new SwingWorker() {
@Override
protected Object doInBackground() throws Exception {
MyShopRepository repo = MyShopRepository.getInstance();
List<Sale> allSale = repo.getSales();
return allSale;
}
@Override
protected void done() {
super.done();
try {
List<Sale> res = (List<Sale>)get();
DefaultTableModel dtm = (DefaultTableModel)jTable1.getModel();
int redova = dtm.getRowCount();
for(int i=0;i<redova;i++){
dtm.removeRow(0);
}
for(Sale s : res){
dtm.addRow(new Object[]{
s.id,s.product.name,s.price,s.quantity,s.total,s.salesman.name,s.buyer.name
});
}
jLabel1.setVisible(false);
} catch (InterruptedException | ExecutionException ex) { }
}
};
sw.execute();
}


This works just fine, but when I delete some rows from the tables they are set to null and I don't get them shown in the jTable. How can I add them too to the jTable with just an empty cell if its value is null ?

Answer

On the database side, if you are not seeing rows because you are attempting to join across tables with null values, then use a LEFT JOIN rather than JOIN

On the UI side, a DefaultTableCellRenderer will return an empty string for any null objects. If you are still seeing null in the JTable, then most likely this is being returned by your database as a String value of "null". To get around a String value of null, you can extend DefaultTableCellRenderer and override the setValue method to take "null" String values into account. For example:

DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(){
    @Override
    protected void setValue(Object value) {
        setText((value == null || value.toString().equalsIgnoreCase("null")) ? "" : value.toString());
    } 
};
table.setDefaultRenderer(Object.class, renderer);
Comments