Setting jtables cell color

Hi,
I would like to know if anyone know how to set a specific cell colour in a JTable, or if they know any links to when i can find help...thanks in advance
Rudy

Take a look at TableCellRenderer and its default implementation
HTH
Mike

Similar Messages

  • Problem when setting JTable cell color.

    hello,
    when I setting color for particular table cell, it sets.
    but, when I click another row (another cell) , the color of the previous cell disabled and it visible only when I click that cells row.
    how can I permanatly set the color for the rows depends on input data.
    for example,
    if a device is connected, I want to give the cell color GREEN.
    if device is not connected , i want to give the color as RED.
    thank you.

    but, when I click another row (another cell) , the color of the previous cell disabled and it visible only when I click that cells row.It appears you applied color to cell editor.
    tableObj.getComponentAt(x,y).setForeground(Color.red);
    tableObj.getComponentAt(x,y).setBackground(Color.red); or could be solved properl if you post the code

  • Setting JTable cell editor

    Hallo,
    I have troubles setting jtable cell edtior. when i run code below, editor stays unchnaged.
    Do you know where's the problem, please (except in programmer^_^) ???
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    public class Test extends JFrame {
        JTable table;
        Test() {
            // Create table model
            table = new JTable();
            table.setModel(new DefaultTableModel(
                new Object[][] {
                    { Boolean.TRUE, Integer.valueOf(10) },
                    { "Hallo!", Boolean.FALSE },
                }, new String[] { "Col1", "Col2" }));
            // Setup frame a little
            setLayout(new BorderLayout());
            setBounds(new Rectangle(300,300,200,100));
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            add(table,BorderLayout.CENTER);
             * Two calls below have no effect:-(
             * What did i wrong?
            // set cell editor for all cells
            table.setCellEditor(new DefaultCellEditor(
                    new JComboBox(new String[] { "0", "1" }) ));
            // Use checkbox for booleans
            table.setDefaultEditor(Boolean.class, new DefaultCellEditor(
                    new JCheckBox() ));
            // Use combobox for strings
            table.setDefaultEditor(String.class, new DefaultCellEditor(
                    new JComboBox( new String[] { "Hallo!", "Bye!" } ) ));
        public static void main(String[] arg) {
            Test test = new Test();
            test.setVisible(true);
    }

    Hi again,
    yes it works when i set it for single column, but i'd like to use default editor, because column count is not fixed.
    According to documentation: "Sets a default cell editor to be used if no editor has been set in a TableColumn. If no editing is required in a table, or a particular column in a table, uses the isCellEditable method in the TableModel interface to ensure that this JTable will not start an editor in these columns. If editor is null, removes the default editor for this column class."
    So when i call
    column.setCellEditor(null); in TableColumnModelListener columnAdded event. But still it's not working. See sample below (i've changed it to cell renderer coz result is clear on single view, but problem stays same)
    More over problem seems to be with algoritm that decide which class to use. Object takes preference any time. W/o it npe arries.
    Regards
    Adam
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.DefaultTableModel;
    public class Test extends JFrame {
        JTable table;
        Test() {
            // Create table model
            table = new JTable();
            table.setModel(new DefaultTableModel(
                new Object[][] {
                    { Boolean.TRUE, Integer.valueOf(10) },
                    { "Hallo!", Boolean.FALSE },
                }, new String[] { "Col1", "Col2" }));
            // Setup frame a little
            setLayout(new BorderLayout());
            setBounds(new Rectangle(300,300,200,100));
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            add(table,BorderLayout.CENTER);
            table.setDefaultRenderer(Object.class,new Renderer(Color.YELLOW));
            table.setDefaultRenderer(String.class,new Renderer(Color.BLUE));
            table.setDefaultRenderer(Boolean.class,new Renderer(Color.RED));
            table.setDefaultRenderer(Integer.class,new Renderer(Color.GREEN));
            // use default renderer in all columns
            table.getColumn(table.getColumnName(0)).setCellRenderer(null);
            table.getColumn(table.getColumnName(0)).setCellRenderer(null);       
        public static void main(String[] arg) {
            Test test = new Test();
            test.setVisible(true);
        class Renderer extends DefaultTableCellRenderer {
            Color color;
            Renderer(Color color) { this.color = color; }
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
                super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                setBackground(color);
                setToolTipText("Class is "+value.getClass().getName());
                return this;
    }Message was edited by:
    a3cchan

  • HELP!! set the cell color in jTable

    I need to set the color of a specific cell in jTable, but, I need to retain the old color in the jTable. It must not reset the whole table.
    would anyone help me in this problem... PLSSSSS its urgent

    A flexible variation on this is to specify formatting options in the JTable's client properties:
    // Use some sort of special "key" to indicate the cell and that you want to set the background color
    String key = "background:" + row + "," + column;
    table.putClientProperty(key, Color.green);You can then write a general table cell renderer that looks for these special formatting options and it doesn't disrupt your existing TableModel in any way:
    public class FormattingTableCellRenderer extends DefaultTableCellRenderer
      public Component getTableCellRendererComponent(JTable table, Object value, int row, int column, ...)
        Component component = super.getTableCellRendererComponent(table, value, row, column, ...);
        // See if the JTable specifies any properties to override the default format
        Color backgroundColor = (Color)table.getClientProperty("background:" + row + "," + column);
        if(backgroundColor != null)
          component.setBackground(backgroundColor);
        return component;
    }Any custom cell renderers you have then simply need to extend FormatTableCellRenderer instead of DefaultTableCellRenderer.
    It's very easy to add formatting options other than background, such as font, to the list of recognised attributes. You'll probably need to make some alterations to get it to recognise selection/focus but hopefully you get the idea.
    Hope this helps.

  • How to set JTable cell editable/non-editable dynamically using NetBean?

    I am using NetBean 6.5, create a database desktop application, I using the persistence entity manager to bind my JTable with database.
    Now, I want to set practicular cells which are enable and disable, I tried to create my own table model and override the isEditable() method, which it seems didn't work. I guessed the problem is the persistence connection between my Table and database.
    How can I solve it? Any example? I just googled the web and can't find example which use netbean combined with database. I know that a single JTable would work when creating your own model.
    thx.

    I know what coding i did, Yes u r right but im new to GUI programming only,
    That's why i posted it to forums, I gone through the Control Flow Statements link what u have given.
    U didnt get my question at all.
    Again the problem im facing is the table is already displayed with 2nd column uneditable.
    When some Action done on table, i need to make 2nd column editable at run time.
    Thanks if u provide me the solution instead of deciding what type of programmer im.

  • How to set JTable cells to uneditable

    I was trying to set the cells in my Jtable to uneditable.
    I overrided the isCellEditable method. Here is what I did. But the
    cells remain editable. Any ideas?
    private class MyTableModel extends DefaultTableModel
    public MyTableModel(Vector vectRow,Vector vecColumn)
    super(vecVector,vecColumn);
    public boolean isCellEditable(int row, int col)
    if (col >= 0) {
    return false;
    }

    Just Use:
    public boolean isCellEditable(int r, int c) { return false; }

  • Code to change JTable cell color not working

    My code below is supposed to change the color
    of a single JTable cell however its not working.
    Could anyone please tell me why?
    Here's the code:
    import java.awt.*;
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class ColorTable extends JTable {
    public ColorTable() {
    AbstractTableModel tableModel = new AbstractTableModel() {
    public Class getColumnClass(int column) { return Integer.class; }
    public int getColumnCount() { return 6; }
    public int getRowCount() { return 10;}
    public Object getValueAt(int row,int col) { return new Integer(row * col); }
    setModel(tableModel);
    setDefaultRenderer(Integer.class,new ColorRenderer(Color.cyan));
    this.setRowSelectionAllowed(false);
    this.setCellSelectionEnabled(true);
    addMouseListener(new MouseAdapter() {
    private ColorRenderer renderer;
    private JColorChooser chooser = new JColorChooser();
    public void mousePressed(MouseEvent e) {
    if(e.getModifiers() == MouseEvent.BUTTON3_MASK) {
    System.out.print("rowAtPoint(e.getPoint())=" +rowAtPoint(e.getPoint()));
    System.out.print( "columnAtPoint(e.getPoint()))=" + columnAtPoint(e.getPoint()));
    renderer = (ColorRenderer)getCellRenderer(rowAtPoint(e.getPoint()), columnAtPoint(e.getPoint()));
    // chooser.setColor(renderer.getColor());
    renderer.setColor(chooser.showDialog((Component)e.getSource(),"Choose Cell Color",chooser.getColor()));
    class ColorRenderer extends DefaultTableCellRenderer {
    private Color cellColor;
    public ColorRenderer(Color color) { cellColor = color; }
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    System.out.print("row= " + row + "\n");
    System.out.print("column= " + column + "\n");
    System.out.print("OBJECT VALUE=" + value.toString());
    //Component comp = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    if (isSelected) {
    setOpaque(true);
    setBackground(cellColor);
    else {
    setBackground(Color.white);
    setForeground(Color.black);
    return this;
    public void setColor(Color color)
    cellColor = color;
    ColorTable.this.repaint();
    public Color getColor() { return cellColor; }
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    ColorTable table = new ColorTable();
    panel.add(table);
    frame.getContentPane().add(panel);
    frame.setSize(500,250);
    frame.setVisible(true);

    My code below is supposed to change the color
    of a single JTable cell however its not working.
    Could anyone please tell me why?
    Here's the code:
    import java.awt.*;
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class ColorTable extends JTable {
    public ColorTable() {
    AbstractTableModel tableModel = new AbstractTableModel() {
    public Class getColumnClass(int column) { return Integer.class; }
    public int getColumnCount() { return 6; }
    public int getRowCount() { return 10;}
    public Object getValueAt(int row,int col) { return new Integer(row * col); }
    setModel(tableModel);
    setDefaultRenderer(Integer.class,new ColorRenderer(Color.cyan));
    this.setRowSelectionAllowed(false);
    this.setCellSelectionEnabled(true);
    addMouseListener(new MouseAdapter() {
    private ColorRenderer renderer;
    private JColorChooser chooser = new JColorChooser();
    public void mousePressed(MouseEvent e) {
    if(e.getModifiers() == MouseEvent.BUTTON3_MASK) {
    System.out.print("rowAtPoint(e.getPoint())=" +rowAtPoint(e.getPoint()));
    System.out.print( "columnAtPoint(e.getPoint()))=" + columnAtPoint(e.getPoint()));
    renderer = (ColorRenderer)getCellRenderer(rowAtPoint(e.getPoint()), columnAtPoint(e.getPoint()));
    // chooser.setColor(renderer.getColor());
    renderer.setColor(chooser.showDialog((Component)e.getSource(),"Choose Cell Color",chooser.getColor()));
    class ColorRenderer extends DefaultTableCellRenderer {
    private Color cellColor;
    public ColorRenderer(Color color) { cellColor = color; }
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    System.out.print("row= " + row + "\n");
    System.out.print("column= " + column + "\n");
    System.out.print("OBJECT VALUE=" + value.toString());
    //Component comp = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    if (isSelected) {
    setOpaque(true);
    setBackground(cellColor);
    else {
    setBackground(Color.white);
    setForeground(Color.black);
    return this;
    public void setColor(Color color)
    cellColor = color;
    ColorTable.this.repaint();
    public Color getColor() { return cellColor; }
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    ColorTable table = new ColorTable();
    panel.add(table);
    frame.getContentPane().add(panel);
    frame.setSize(500,250);
    frame.setVisible(true);

  • JTable ..... set background cell color?

    Hi!
    I've read the many examples on here of doing such .... but still dont see how to call the renderer in to do this.
    My app calculates several variables, then posts the answer to my jTable10 answer column(11) .... row after row.
    Now , I want to add this:
    For each answer, I will test to see if (outVal) answer is <4 or >12,
    If true for this test, I need to post the answer and also change the background of that cell to RED color.
    I dont know how to construct the renderer to do this.
    Thanks!

    This is the code that does the calculations for the jTable10 ... and make a call to the render:
    import java.awt.Component;
    import java.text.DecimalFormat;
    import java.util.ArrayList;
    import javax.swing.JTable;
    import javax.swing.RowFilter;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableModel;
    import javax.swing.table.TableRowSorter;
    * @author Richard
    public class MathTapCal {
         public static ArrayList<Double> alist1 = new ArrayList<Double>(100);
        /** Creates a new instance of MathTapCal */
                public MathTapCal() {
            String group;
                    DecimalFormat df= new DecimalFormat("#0.00");
                    int rc;
                    int ampVal;
                    int sor = 0;
                    int tVal = 0;
                    int z = 0;
                    int rowLen;
                    int startVal_A;
                    int arrayVal;
                    int aVal;
                    int split = 0;
                    double tapLoss = 0;
                    double calTapValue;
                    double lenVal;
                    double cabLossVal = 0;
                    double tapVal = 0;
                    double sigOutVal = 0;
                    double calEndVal;
                    double designVal;
                    Object stVal;
                    Object bb;
                    Object valx;
                    Object calTapVal_s;
                    String valxx;
                    String text;
                    String cabLossVal_s;
                    String startVal_x;
                    String rcc;
                    String stVal1;
                    String cc;
                    String splitx;
                    String av;
                    String dd;
                    Double startVal;
                    Double totalLoss;
                    bb = (String)CATV_Cal.jComboBox1.getSelectedItem();// amp db output
                    ampVal = Integer.parseInt((String) bb);
                    startVal_A = ampVal - 12;
                    startVal_x = df.format(startVal_A);
                    startVal = new Double(startVal_A);
                    av = CATV_Cal.jButton6.getText();// row lenght
                    rowLen = Integer.parseInt((String) av);
                    splitx = (String)CATV_Cal.jComboBox2.getSelectedItem();// splitter port size
                    arrayVal = Integer.parseInt((String) splitx);
                    alist1.clear();
               for ( aVal=0; aVal<arrayVal; aVal++ ) {
                    alist1.add(startVal); //load the Array with start vals
                    //CATV_Cal.jTable1.setValueAt(startVal_x ,tVal ,7 );
                    System.out.println("Load startVal>>>>>>>>>>>  !!!!!!!!!!!!!!!"+startVal); 
                    rcc = CATV_Cal.jButton6.getText();// length of table
                    rc = Integer.parseInt(rcc);
                for ( ; ; ){
                    //group = (String)CATV_Cal.jComboBox3.getSelectedItem();  
                    sor = sor +1;// sort table call split leg 1, 2, 3, etc.    
                    text = Integer.toString(sor);
                    TableModel model =  CATV_Cal.jTable10.getModel();
                    JTable table = new JTable(model);
                    TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
                    CATV_Cal.jTable10.setRowSorter(sorter);
                    sorter.setRowFilter(null);
                    //sorter.setRowFilter(RowFilter.regexFilter("^"+group+"$",1));
                    sorter.setRowFilter(RowFilter.regexFilter("^"+text+"$",3));
                    sorter.toggleSortOrder(2);//cable length
                    System.out.println("SOR  !!!!!!!!!!!!!!!"+sor);
                    dd = (String)CATV_Cal.jComboBox2.getSelectedItem();// splitter port size
                    split = Integer.parseInt((String) dd);
                    System.out.println("Splitter Port size>>>>>>>  !!!!!!!!!!!!!!!"+split); 
                for  ( tVal=0; tVal<split; tVal++ ) {
                    System.out.println("Loop tVal  !!!!!!!!!!!!!!!"+tVal);           
                if (z == rc){ // when we reach the end of the rows .... STOP !!
                    System.out.println("QUIT at Row !!!!!!!!!!!!!"+z); 
                return;
                    valx = CATV_Cal.jTable10.getValueAt(tVal,4);// cable length
                    valxx = (valx).toString();
                    lenVal = Integer.parseInt(valxx);
                    cabLossVal = lenVal * .06;//takes the cable lenght and times it by the loss per foot factor
                    cabLossVal_s = df.format(cabLossVal);
                    CATV_Cal.jTable10.setValueAt(cabLossVal_s ,tVal ,5 );
                    System.out.println("Cable Loss >>>>>>> !!!!!!!!!!!!!!!"+cabLossVal); 
                   // CATV_Cal.jTable1.setValueAt(tVal , ,6 ); // test !!.............!!!!only 
                    stVal = alist1.get(tVal);  // get startValue item from Array
                     stVal1 = (stVal).toString();
                    startVal = Double.parseDouble(stVal1);
                    String startVal_s = df.format(startVal);
                    CATV_Cal.jTable10.setValueAt(startVal_s ,tVal ,7 );// sets the start SignalValue box
                    //System.out.println("TVal !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"+tVal);
                    cc = (String)CATV_Cal.jComboBox4.getSelectedItem();// END Design Value
                    designVal = Double.parseDouble(cc);
                    totalLoss = cabLossVal + designVal; // design value = cc
                    System.out.println("totalLoss>>>>>>>>>>  !!!!!!!!!!!!!!!"+totalLoss); 
                    calTapValue = startVal - totalLoss;
                    calTapVal_s = df.format(calTapValue);
                    CATV_Cal.jTable10.setValueAt(calTapVal_s ,tVal ,9 );
                    System.out.println("calTapVal ="+calTapVal_s); 
                    if (calTapValue  <= 5 ){
                        tapVal = 4;
                        tapLoss = 4;
                    if (calTapValue  >= 5 && calTapValue <=7.5){
                        tapVal = 6;
                        tapLoss = 3.5;
                    if (calTapValue  >= 7.5 && calTapValue <=10.5){
                        tapVal = 9;
                        tapLoss = 1.6;
                    if (calTapValue  >= 10.5 && calTapValue <=14){
                        tapVal = 12;
                        tapLoss = 1.5;
                    if (calTapValue  >= 14 && calTapValue <=18){
                        tapVal = 16;
                        tapLoss = 0.7;
                    if (calTapValue  >= 18 && calTapValue <=22){
                        tapVal = 20;
                        tapLoss = 0.7;
                    if (calTapValue  >= 22 && calTapValue <=25.5){
                        tapVal = 24;
                        tapLoss = 0.6;
                    if (calTapValue  >= 25.5 && calTapValue <=28.5){
                        tapVal = 27;
                        tapLoss = 0.6;
                    if (calTapValue  >= 28.5 ){tapVal = 30;tapLoss = 0.6;}
                    CATV_Cal.jTable10.setValueAt(tapVal ,tVal ,8 );// sets the chosen standard "TAP VALUE" 4,6,9,12,16,20,24,27 or 30
                    sigOutVal = startVal - tapLoss;
                    Double sigOutVal_1 = new Double(sigOutVal);
                    alist1.set(tVal,sigOutVal_1);// sets the sigOutVal into the Array replacing the startSigVal there
                    String sigOutVal_s = df.format(sigOutVal);
                    CATV_Cal.jTable10.setValueAt(sigOutVal_s ,tVal ,11 );
                    System.out.println("sigOut ="+sigOutVal_s);
                    calEndVal = calTapValue - 8;// available db for TV
                    String calEndVal_s = df.format(calEndVal);
                    CATV_Cal.jTable10.setValueAt(calEndVal_s ,tVal ,10 );
                    System.out.println("calEndVal ="+calEndVal_s); 
                    z = z +1;  // row count incrementer
                    new CustomTableCellRenderer();// here is my call to the Renderer
    }

  • JTable cell color

    I use the following custom DefaultTableCellRenderer:
    ------------------------CustomTableCellRenderer-------------------
    import java.awt.Component;
    import java.awt.Color;
    import java.awt.Font;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableCellRenderer;
    public class CustomTableCellRenderer extends DefaultTableCellRenderer
         public Component getTableCellRendererComponent( JTable jTable, Object value,boolean isSelected, boolean hasFocus, int row,int col)
         super.getTableCellRendererComponent(jTable, value, false,
         true, row, col);
         setHorizontalAlignment(CENTER);
         if(row!=0 && !(jTable.getValueAt(row-1,col).toString().equals(value.toString()))) {
              setBackground(new Color(255,220,220));
         return this;
    -----------------main class-----------------------------------------------
    TableCellRenderer cell = new CustomTableCellRenderer();
         table.setDefaultRenderer( Object.class, cell );
    The above scheme works fine where I want to color a cell every time a change/transition occurs among the values in a particular column for each column in the table.
    The problem is, in the resulting table, all the cells appear selected and I am unable to select a set of rows or columns by clicking/dragging and trying to create a rectangular rubberband.
    Why is it not allowing me to treat this as a regular JTable instance where upon clicking any cell, the whole row gets selected?
    I suspect the 3rd and 4th arguments in the following statement, I tried all boolean combinations for it, but in vain:
    super.getTableCellRendererComponent(jTable, value, false,
         true, row, col);
    any help?

    You need to override the prepareRenderer method of the TableRenderer with something like this:
            table = new JTable(myTableModel) {
                public Component prepareRenderer(TableCellRenderer renderer, int rowIndex, int colIndex) {
                    Component c = super.prepareRenderer(renderer, rowIndex, colIndex);
                    // Set color lightyellow, lightred (inverted ones) or just like the rest of the cells.
                    String cellContent = myTableModel.getValueAt(rowIndex, 4).toString();
                    if (table.isCellSelected(rowIndex, colIndex)) {
                        // nothing to do or maybe setSelectionBackground or further if/else if/else for selected cells.
                    } else if (colIndex == 4 && cellContent.equals("content1")) {
                        c.setBackground(new Color(255, 220, 200));
                    } else if (colIndex == 4 && cellContent.contains("content2")) {
                        c.setBackground(new Color(255, 255, 220));
                    } else {
                        c.setBackground(table.getBackground());
                    return c;
            };If you don't know that c is a TableCellRenderer component you'll need instanceof check.

  • JTable cell color overriding Boolean values displayed as checkboxes. Fix?

    I have a JTable column of Boolean values that automatically appear as checkboxes. When I apply my DefaultTableCellRenderer to this column, the checkbox disappears and a "false" or "true" appears instead. But if I mouseclick on the cell, the checkbox will appear momentarily.
    Any suggestions for getting the Boolean value displayed as a checkbox and seeing my colors change? (I suppose the easy way is using JCheckBox, but I'm curious if I can do it using Boolean)
    Thanks for the help. Code follows for the cell renderer.
    class ColorRenderer extends DefaultTableCellRenderer{
    public ColorRenderer() {
    super();
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected == true) {
      setBackground(Color.getHSBColor(100, 100, 1));
      setForeground(Color.BLACK);
    } else {
      setBackground(Color.LIGHT_GRAY);
      setForeground(Color.WHITE);
    if (hasFocus == true) {
      setBackground(Color.RED);
      setForeground(Color.WHITE);
    setOpaque(true);
    setValue(value);
    return this;

    Wouldn't extend DefaultTableCellRenderer as that extends a JLabel
    I would extend a JCheckBox and implement TableCellRenderer.

  • Set Cell Color without using DefaultTableCellRenderer

    Hi,
    Is there any possible to set the JTable cell color without using DefaultTableCellRenderer ?. For ex, I have one JTable that having 9 rows and 9 columns. I have to set the cell color in 2nd row & 3rd column.
    Please anyone give me guidance to solve this.
    Thanks & Regards
    S Senthilkumar

    Fine.. Please try to understand my points.
    Because in my application I have JTable that having 10 columns and rows dynamically will come based on the value fetch from arraylist. If I use DefaultTableCellRenderer, for each record its calling CustomTableCellRenderer(). For example arraylist return 10 rows means its looping 100 times(10 rows * 10 columns).
    CustomTableCellRenderrer.java
    ArrayList dataLiveMarket = (ArrayList) new CheckUser().getLiveMarketDetails(unval);
    CustomTableModel modelLiveMarket = new CustomTableModel(dataLiveMarket);
    JTable tableOne = new JTable(modelLiveMarket);
    tableOne.setDefaultRenderer(Object.class, new CustomTableCellRenderer());
    CustomTableCellRenderrer.java
    package com.fxtrading.dao;
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.SwingConstants;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableModel;
    * @author user
    public class CustomTableCellRenderer extends DefaultTableCellRenderer {
        //private TableModel bidLastPrice;
        //int k;
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus,
                int row, int column) {
            Component component =
                    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if (column == 0 || column == 1|| column == 2) {
                setHorizontalAlignment(SwingConstants.LEFT);
            } else if(column == 3 || column == 4 || column == 5 || column == 6 || column == 7 || column == 8){
                setHorizontalAlignment(SwingConstants.RIGHT);
            }else if(column == 9){
                setHorizontalAlignment(SwingConstants.CENTER);
            // Change cell Color - Started
            bidLastPrice = table.getModel();
            int bidLastRowCount =(int)table.getRowCount();
            for(k=0; k<bidLastRowCount; k++) {
                String bidPrice = (String)bidLastPrice.getValueAt(k,4);
                String lastPrice = (String)bidLastPrice.getValueAt(k,8);
                bidPrice = bidPrice.replace(",","").replace("$","");
                lastPrice = lastPrice.replace(",","").replace("$","");
                if(Double.parseDouble(bidPrice)<Double.parseDouble(lastPrice)){
                    if(row == k && column == 4){
                        component.setBackground(Color.RED);                   
                    }else{
                        component.setBackground(Color.WHITE);
                    System.out.println("Row Count -->"+k+" Less ----> Bid Price----> "+Double.parseDouble(bidPrice)+" : Last Price----> "+Double.parseDouble(lastPrice));
                }else{
                    if(row == k && column == 4){                  
                        component.setBackground(Color.GREEN);
                    }else{
                        component.setBackground(Color.WHITE);
                    System.out.println("Row Count -->"+k+" More ----> Bid Price----> "+Double.parseDouble(bidPrice)+" : Last Price----> "+Double.parseDouble(lastPrice));
            // Change cell Color - End
            return component;
    }Thanks & Regards,
    S Senthilkumar

  • How to set JTable column's color?

    How can I set JTable Columns' color? I only found this class DefaultTableCellRenderer
    which can set cell's color.

    rmalina wrote:
    You are going to need to derive a renderer class for your Column from DefaultTableCellRenderer and override the following function with something like this:
    @Override
         public Component getTableCellRendererComponent(JTable jTable, Object oValue, boolean isSelected, boolean hasFocus, int nRow, int nColumn) {
    super.setForeground(Color.GREEN);
    super.setBackground(Color.GREEN);
    }That would set your column to green.
    Edited by: rmalina on Jul 28, 2008 8:47 AMHow can I know I only change the columns' color instead of other cells?

  • NI_Excel.Ivclass:Excel Set Cell Color and Border.vi Error

    Hi
    I was trying to compile a file and I kept getting an error. It zeroed in on the vi that was not compiling. I am attaching the vi to this message. The vi seems to be broken. And I am not sure how to fix this. Can some one please help me out with this. Thanks in advance. 
    I guess it is associated with Report Generation Toolkit. Please let me know if you need any more details.
    This is the error message 'One or more required inputs to this function are not wired or are wired incorrectly. Show the Context Help window to see what the connections to this function should be.'
    Regards
    Mr Miagi
    Solved!
    Go to Solution.
    Attachments:
    Excel Set Cell Color and Border.vi ‏20 KB

    http://forums.ni.com/t5/LabVIEW/Set-excel-cell-color-and-border-broken-can-t-build-application/m-p/1...
    Please do a search.

  • How do you set the font color for a specific entire row inside a JTable?

    How do you set the font color for a specific entire row inside a JTable?
    I want to change the font color for only a couple of rows inside a JTable.
    I've seen some ways to possibly do this with an individual cell.
    Clarification on changing the font color in an individual cell would be helpful too if
    there is no easy way to do this for a row.

    hai,
    Try out with this piece of code.Create your table and assign the renderer to each column in the table.
    CellColorRenderer m_CellColorRenderer = new CellColorRenderer();
    for(int i=0;i<your_JTable.getColumnCount();i++)
    your_JTable.getColumnModel().getColumn(i).setCellRenderer(m_CellColorRenderer);
    class CellColorRenderer extends JLabel implements TableCellRenderer
    CellColorRenderer()     
    setOpaque(true);     
    setHorizontalAlignment(LEFT);
    setVerticalAlignment(CENTER);
    setBackground(Color.white);
    setForeground(Color.black);
    protected void setValue(Object value)
         setText((value == null) ? "" : value.toString());
    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected, boolean hasFocus, int row,int column)
         if(isSelected == true)
              setForeground(Color.red);
         else
              setForeground(Color.black);
         setValue(value);
         return this;
    regards,
    bala

  • JTable cell background color

    Hi All,
    I want to change the background color of the same of the cells in jTabel. How can I do that.
    Like, I want to keep 3 cells in red color. Another 2 cells in in green color, And keep other cell background color to default.
    Also I want to change the background color of the cell, with different selection in other component(like jTree, jList).
    Thank you,
    Avin Patel

    The same cell renderer is used by all cells of the table. You can't just set the background color of a cell once. You have to reset it every time the cell renderer is called (depending on which row/column you are being asked to render). Here is an example:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableCell extends JFrame
         JTable table;
         public TableCell()
              Object[][] data = { {"1", "A"}, {"2", "B"}, {"3", "C"}, {"4", "D"}  };
              String[] columnNames = {"Number","Letter"};
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              table = new JTable( model );
              //  Set default cell renderer
              TableCellRenderer renderer = new TestRenderer();
              table.setDefaultRenderer(Object.class, renderer);
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              TableCell frame = new TableCell();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
         class TestRenderer extends DefaultTableCellRenderer
              public Component getTableCellRendererComponent(
                   JTable table,
                   Object value,
                   boolean isSelected,
                   boolean hasFocus,
                   int row,
                   int column)
                   super.getTableCellRendererComponent(table,
                   value, isSelected, hasFocus, row, column);
                   if (column == 0)
                        setHorizontalAlignment( LEFT );
                        setBackground( Color.blue );
                   else
                        setHorizontalAlignment( RIGHT );
                        setBackground( Color.green );
                   if (row == 1)
                        setBackground( Color.red );
                   return this;
    }

Maybe you are looking for

  • Customer replication from R/3 to CRM as BP

    Customer's already exist in our ECC system. In CRM, we need to create the ECC customer;s as BP in install at role. From some ot the previous threads, I found that PIDE transaction can be used. I assigned the customer account group classification to B

  • Internet Problems Out-of-the-Blue

    Hello. As of a few days ago, my MBP 15in core 2 duo is having problems keeping an internet connection while booted into Windows. While on the mac side, there are no problems at all. I also have an iMac that is partitioned for bootcamp and the windows

  • Syncing "file name", were not copied to the iPad because they could not b

    Hi, This problem has bothered me for a couple of weeks. Copied here is the exact error message iTunes delivers when I try to sync a video library over to my iPad. "Some of the items in the iTunes library, including "file name", were not copied to the

  • Exporting video through quicktime to iPod

    When I try to export a home video to my iPod using quicktime, it pops up a box asking me to purchase quicktime which I already am using. Under "file" I open the file and then when I chose "export" is when it pops up this box. Can someone please advis

  • ALL DRIVER LIKE GRAPHIC,AMD HDMI AUDIO,AND LAN DRIVER

    Dear Sir,                Hi, There is problem in my Laptop HP PAVILION G4  (Windows 7 Ultimate) 32 Bit OS LAN DRIVER AND AMD HDMI OUTPUT DRIVER IS NOT WORKING.WHICH CUSED MY FARNESS FROM INTERNET & MUSIC. SO PLZ HELP ME TO GIVING ME I'S DRIVERS......