0

i'm new to java i create java application using netbean ..i created javatable (tb1 is variable name)..i have add 2 rows and 2 columns ..i have 1 button ..everything i wanna do is when i clicked a button change the background color of first column of the table..it works..but problem is to change the color i have to click on the table ..then i click wherever of the table background color change..i don't know what's the problem..this is my code any help??

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

import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

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

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
    }

    /**
     * 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();
        tb1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

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

        tb1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"madhawa", "123"},
                {"sonic", "234"}
            },
            new String [] {
                "name", "password"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tb1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 403, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(18, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(108, 108, 108))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addContainerGap(37, Short.MAX_VALUE))
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        TableColumn col = tb1.getColumnModel().getColumn(0);
DefaultTableModel model3 = (DefaultTableModel)tb1.getModel();
col.setCellRenderer(new CustomRenderer());
    }                                        

    /**
     * @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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tb1;
    // End of variables declaration                   
}
class CustomRenderer extends DefaultTableCellRenderer 
{
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        setForeground(Color.red); 
        setBackground(Color.YELLOW);
        return c;
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • Ew, a GUI builder. My suggestion: don't use a GUI builder. – Josh M Nov 18 '13 at 04:45
  • josh M why did you say that ..explain –  Nov 18 '13 at 04:57
  • You are obviously encountering problems, perhaps this is due to lack of readability in code. I don't know about you, but to me, that code looks extremely messy and I'd imagine it would be quite difficult to make some changes. Also, I could go on a rant about how GUI builders are bad (in your case), but I'm not sure you would stop using them. To say the least, you're new to Java and you are using a GUI builder, therefore **you have no idea what any of that code means**. – Josh M Nov 18 '13 at 04:59
  • i was shocked ..i coded only button action performed and CustomRenderer class .. –  Nov 18 '13 at 05:16
  • I know you did. That's the problem. – Josh M Nov 18 '13 at 05:27

1 Answers1

0

Basically, the table doesn't know anything has changed, so it's not been updated. Try adding a repaint request to the end of the button actionPerformed method, for example...

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    TableColumn col = tb1.getColumnModel().getColumn(0);
    DefaultTableModel model3 = (DefaultTableModel) tb1.getModel();
    col.setCellRenderer(new CustomRenderer());
    tb1.repaint();
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • 1
    [how to refresh Cell background without using JTable.repaint()](http://stackoverflow.com/questions/16814512/tablecellrenderer-and-how-to-refresh-cell-background-without-using-jtable-repain) – mKorbel Nov 18 '13 at 07:21
  • @mKorbel I had thought about this to, but as I saw it, the OP wasn't changing the state of the model, so without adding a purpose build method in the model to trigger a model update, this was the easiest solution I could come up with – MadProgrammer Nov 18 '13 at 20:43