Aleksandar Stojanovic Aleksandar Stojanovic - 1 year ago 68
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.price,sale.quantity,,, from sale "
+ " join product on sale.product = "
+ " join employee on sale.salesman = "
+ " join buyer_seller on sale.buyer =;");
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() {
protected Object doInBackground() throws Exception {
MyShopRepository repo = MyShopRepository.getInstance();
List<Sale> allSale = repo.getSales();
return allSale;
protected void done() {
try {
List<Sale> res = (List<Sale>)get();
DefaultTableModel dtm = (DefaultTableModel)jTable1.getModel();
int redova = dtm.getRowCount();
for(int i=0;i<redova;i++){
for(Sale s : res){
dtm.addRow(new Object[]{,,s.price,s.quantity,,,
} catch (InterruptedException | ExecutionException ex) { }

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 Source

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(){
    protected void setValue(Object value) {
        setText((value == null || value.toString().equalsIgnoreCase("null")) ? "" : value.toString());
table.setDefaultRenderer(Object.class, renderer);