Question

I'm java beginner and have face to difficult when use java table custemrenderer ..i have database named "info" which consist with 3 column call "pvalue", "pbankmoney" ,"minvalue" ..i make java app for view them on java table ..but i want to make row background color different only if "bankmoney" < "minvalue"(bankmoney low than minvalue)..so i use java custemrenderer ..but i have some problems ..firstone is using table CustomTableCellRenderer how can i change row color ..i explain what i mean .. when i say jTable1.getColumnModel().getColumn(0).setCellRenderer(new CustomTableCellRenderer());
CustomTableCellRenderer class only recieved column 0 values at certain row then can i compare difference between 2 column there ... but i think there is a way to do that using custom render i want to change color of a first 2 columns not in a single cell..

then i use another Boolean variable to accomplish my goal ..i set a variable call 'tabledif" at very beginning ..and check difference and change it to true or false and then renderclass check it and change column color ..ya it's not work ..i figure out that variable is change correctly according to difference with minvalue and bankmoney value..but when i request Boolean value of my "rowidenty" class it give false every time it is the value i initiated ..why this Boolean problem happen ? IMPORTANT

1)i want to change first 2 column color according to difference between 2 values(get from a database) using java custemrender .

2)i want to know why the boolean value is always give false which is initial value even already i have change to true ?????

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tablerowcustemrender;

import java.awt.Color;
import java.awt.Component;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Vector;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

/**
 *
 * @author Madhawa
 */
public class rowidenty extends javax.swing.JFrame {

    public boolean tabledif=false;
    /**
     * Creates new form rowidenty
     */
    public rowidenty() {
        initComponents();
     jTable1.setShowGrid(true);
     jTable1.setShowVerticalLines(true);
     //jTable1.setGridColor(Color.gray);
    }

        public void search()
    {
       try{
           DefaultTableModel dm = (DefaultTableModel) jTable1.getModel();  
           Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
           Connection con = DriverManager.getConnection("jdbc:odbc:info");
           java.sql.Statement st=con.createStatement();
           ResultSet rs=st.executeQuery("select * from Table1");
           while(rs.next()){
               String tablename=rs.getString("pname");
               int tablemin= rs.getInt("minvalue");
               int tablemoney=rs.getInt("pbankmoney");
               if(tablemoney < tablemin)
               {
               tabledif=true;
               }
               else
               {
                   tabledif=false;
               }
               System.out.println(tablename+"  "+tablemoney+"  "+tablemin);
                       Vector<Object> data = new Vector<>(); 
                       data.add(tablename);  
                       data.add(tablemoney);  
                       data.add(tablemin);
                       dm.addRow(data); 

                       jTable1.getColumnModel().getColumn(0).setCellRenderer(new CustomTableCellRenderer());
                       jTable1.getColumnModel().getColumn(1).setCellRenderer(new CustomTableCellRenderer());
           }
        }
        catch(Exception e){
            System.out.println(e);
        }


    }
///////////////////////////////////////////////////////////////////





    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("action");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTable1.setBackground(new java.awt.Color(0, 204, 204));
        jTable1.setBorder(javax.swing.BorderFactory.createMatteBorder(5, 5, 5, 5, new java.awt.Color(255, 0, 102)));
        jTable1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "name", "money", "value"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTable1.setGridColor(new java.awt.Color(255, 204, 0));
        jTable1.setRowHeight(35);
        jTable1.setRowMargin(10);
        jTable1.setSelectionBackground(new java.awt.Color(255, 51, 153));
        jScrollPane1.setViewportView(jTable1);

        jButton2.setText("hide");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("show");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("bool");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("jButton5");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 504, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(45, 45, 45)
                .addComponent(jButton2)
                .addGap(27, 27, 27)
                .addComponent(jButton3)
                .addGap(116, 116, 116)
                .addComponent(jButton4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton5)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(45, 45, 45)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(jButton4)
                    .addComponent(jButton5))
                .addGap(31, 31, 31))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        search();
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        jTable1.getColumnModel().getColumn(2).setMinWidth(0);
        jTable1.getColumnModel().getColumn(2).setMaxWidth(0);
    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        jTable1.getColumnModel().getColumn(2).setMinWidth(150);
        jTable1.getColumnModel().getColumn(2).setMaxWidth(150);
         jTable1.getColumnModel().getColumn(2).setMaxWidth(150);
         jTable1.repaint();

    }                                        

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        tabledif=true;
    }                                        

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        System.out.println("hey  "+tabledif );
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(rowidenty.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(rowidenty.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(rowidenty.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(rowidenty.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new rowidenty().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration                   



      public class CustomTableCellRenderer extends DefaultTableCellRenderer{
  public Component getTableCellRendererComponent (JTable table, 
Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
  Component cell = super.getTableCellRendererComponent(
   table, obj, isSelected, hasFocus, row, column);


rowidenty rowidenty1=new rowidenty();

if (rowidenty1.tabledif) {
    cell.setBackground(Color.cyan);
} else {
    cell.setBackground(Color.lightGray);
}


  System.out.println(obj+"  renderer   "+column+" bool "+rowidenty1.tabledif);
  return cell;
  }
      }
}
Was it helpful?

Solution

Creating a brand new instance of rowidenty in the cell render basically disconnects you from the data in the table...

public class CustomTableCellRenderer extends DefaultTableCellRenderer{
    public Component getTableCellRendererComponent (JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
        Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, column);

        // This is your problem....
        rowidenty rowidenty1=new rowidenty();

        if (rowidenty1.tabledif) {
            cell.setBackground(Color.cyan);
        } else {
            cell.setBackground(Color.lightGray);
        }


        System.out.println(obj+"  renderer   "+column+" bool "+rowidenty1.tabledif);
        return cell;
    }
}

Instead, you need to be either using the obj value or asking the table for more information about the row

Updated....

Try and remember, each row needs to be checked individually, so it's pointless trying to maintain some kind of flag, unless you have one for each row.

Instead, you need to extract the values you need for the row each time CustomTableCellRenderer is called and update the background based on your needs...

public class CustomTableCellRenderer extends DefaultTableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable table,
                    Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
        Component cell = super.getTableCellRendererComponent(
                        table, obj, isSelected, hasFocus, row, column);

        TableModel model = table.getModel();
        int money = (int) model.getValueAt(row, 1);
        int min = (int)model.getValueAt(row, 2);

        if (money < min) {
            cell.setBackground(Color.cyan);
        } else {
            cell.setBackground(Color.lightGray);
        }

        return cell;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top