Button to change bg-color in JTable cell

Hello!
I would like to change the background color of a cell with a klick on a button.
There will be 3 colors, and the selected cell are the only one thats going to change.
How do I do that?
Heres my code:
import javax.swing.*;
import java.awt.Color;
import java.awt.Component;
import java.awt.Rectangle;
import javax.swing.JButton;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
public class Kinna extends JFrame {
     private static final long serialVersionUID = 1L;
     private JPanel jContentPane = null;
     private JTabbedPane jTabbedPane = null;
     private JScrollPane jScrollPane = null;
     private JTable jTable = null;
     private JButton jButtonRed = null;
     private JButton jButtonGreen = null;
     private JButton jButtonBlue = null;
     private JButton jButtonNewWeek = null;
     private JButton jButtonDelWeek = null;
      * This method initializes jTabbedPane     
      * @return javax.swing.JTabbedPane     
     private JTabbedPane getJTabbedPane() {
          if (jTabbedPane == null) {
               jTabbedPane = new JTabbedPane();
               jTabbedPane.setBounds(new Rectangle(105, 45, 545, 488));
               jTabbedPane.addTab(null, null, getJScrollPane(), null);
          return jTabbedPane;
      * This method initializes jScrollPane     
      * @return javax.swing.JScrollPane     
     private JScrollPane getJScrollPane() {
          if (jScrollPane == null) {
               jScrollPane = new JScrollPane();
               jScrollPane.setViewportView(getJTable());
          return jScrollPane;
      * This method initializes jTable     
      * @return javax.swing.JTable     
     private JTable getJTable() {
          if (jTable == null) {
               Object[] head = {"Namn", "M�ndag", "Tisdag", "Onsdag", "Torsdag", "Fredag"};
               Object[][] data = {{"Niklas", "9-15", "9-15", "9-15", "9-15","9-15"},
                                        {"Niklas", "9-15", "9-15", "9-15", "9-15","9-15"}};
               jTable = new JTable(data, head);
                  // This table shades every other column yellow
          return jTable;
      * This method initializes jButtonRed     
      * @return javax.swing.JButton     
     private JButton getJButtonRed() {
          if (jButtonRed == null) {
               jButtonRed = new JButton("R�d");
               jButtonRed.setBounds(new Rectangle(15, 30, 76, 31));
               jButtonRed.setText("R�d");
               jButtonRed.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent e) {
          return jButtonRed;
      * This method initializes jButtonGreen     
      * @return javax.swing.JButton     
     private JButton getJButtonGreen() {
          if (jButtonGreen == null) {
               jButtonGreen = new JButton("R�d");
               jButtonGreen.setBounds(new Rectangle(15, 75, 76, 31));
               jButtonGreen.setText("Gr�n");
          return jButtonGreen;
      * This method initializes jButtonBlue     
      * @return javax.swing.JButton     
     private JButton getJButtonBlue() {
          if (jButtonBlue == null) {
               jButtonBlue = new JButton("R�d");
               jButtonBlue.setBounds(new Rectangle(15, 120, 76, 31));
               jButtonBlue.setText("Bl�");
          return jButtonBlue;
      * This method initializes jButtonNewWeek     
      * @return javax.swing.JButton     
     private JButton getJButtonNewWeek() {
          if (jButtonNewWeek == null) {
               jButtonNewWeek = new JButton();
               jButtonNewWeek.setBounds(new Rectangle(270, 0, 91, 31));
               jButtonNewWeek.setText("Ny Vecka");
               jButtonNewWeek.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent e) {
                         System.out.println("actionPerformed()");
                         int i = getJTabbedPane().getSelectedIndex() + 1;
                         String tab = "Index: " + i;
                         getJTabbedPane().addTab(tab, new JLabel("Hello"));
                         getJTabbedPane().setSelectedIndex(getJTabbedPane().getTabCount()-1);
          return jButtonNewWeek;
      * This method initializes jButtonDelWeek     
      * @return javax.swing.JButton     
     private JButton getJButtonDelWeek() {
          if (jButtonDelWeek == null) {
               jButtonDelWeek = new JButton();
               jButtonDelWeek.setBounds(new Rectangle(375, 0, 121, 31));
               jButtonDelWeek.setText("Ta bort vecka");
               jButtonDelWeek.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent e) {
                         System.out.println("actionPerformed()");
                         getJTabbedPane().removeTabAt(getJTabbedPane().getSelectedIndex());
          return jButtonDelWeek;
      * @param args
     public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                    Kinna thisClass = new Kinna();
                    thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    thisClass.setVisible(true);
      * This is the default constructor
     public Kinna() {
          super();
          initialize();
      * This method initializes this
      * @return void
     private void initialize() {
          this.setSize(670, 580);
          this.setContentPane(getJContentPane());
          this.setTitle("JFrame");
      * This method initializes jContentPane
      * @return javax.swing.JPanel
     private JPanel getJContentPane() {
          if (jContentPane == null) {
               jContentPane = new JPanel();
               jContentPane.setLayout(null);
               jContentPane.add(getJTabbedPane(), null);
               jContentPane.add(getJButtonRed(), null);
               jContentPane.add(getJButtonGreen(), null);
               jContentPane.add(getJButtonBlue(), null);
               jContentPane.add(getJButtonNewWeek(), null);
               jContentPane.add(getJButtonDelWeek(), null);
          return jContentPane;
}  //  @jve:decl-index=0:visual-constraint="29,25"

If you have a different color for every cell in the table, then maybe it would be easier to store a custom Object in the TableModel that has two pieces of information:
a) the text to be displayed
b) the background color of the text.
Then you can write a custom renderer that uses both pieces of information to renderer the cell correctly.
Here is an untested example of what the custom renderer might look like:
class ColorRenderer 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);
          CustomObject custom = (CustomObject)value;
          setText( custom.getText() );
          if (!isSelected)
               setBackground( custom.getBackground() );
          return this;
}

Similar Messages

  • HOw can i change the color of a cell

    How can I change the color of a cell when it is selected. I select the cell by pressing enter, then I want the text in the cell to change color to red, but all the cells in the table change color. Please I would be grateful for some help

    Subclass DefaultTableCellRenderer.
    public class MyCellRenderer extends DefaultTableCellRenderer
    Override
    public Componet getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    JLabel lab = new JLabel(String)value);
    lab.setOpaque(true);
    return lab;
    if(isSelected)
    lab.setBackground(Color.red);
    else
    lab.setBackground(Color.white);
    Set the columns in your table:
    table.getCoulumModel.getColumn(0).setCellRenderer(new myCellRenderer());
    table.getCoulumModel.getColumn(1).setCellRenderer(new myCellRenderer());
    etc. for each column in your table.

  • How to change the color of the Cell in Table ?

    Thanks a lot

    Here is the code to change the color of the cell in Table.
    First you need to write a class extending JTextField and implementing TableCellRenderer interface which has only one method as follows
    public class MyCellRenderer extends JTextField implements TableCellRenderer
    public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected, boolean hasFocus,int row, int column)
    setForeground(Color.blue);
    and wherever you create the table you need to set this renderer as the table cell renderer for your table. code follows...
    TableColumnModel tcm = yourtable.getColumnModel();
              Enumeration tce =tcm.getColumns();
              while (tce.hasMoreElements())
                   TableColumn tc=(TableColumn)tce.nextElement();
                   tc.setCellRenderer(new MyCellRenderer());
    this will solve your problem. you need to import the required packages.
    Srinivas.

  • How do you change the colors of individual cells within a 2D array?

    How do you change the colors of individual cells within a 2D array of numeric indicators?
    I want the VI to check a data value and if it is failing, white out a square at a specific index coordinate.  I have it working with color boxes, but I'm not sure how to use the property node function, to change the color of individual cells, by coordinates.
    I have attached the VI using color boxes. If you run the VI, the box corresponding to the Step control should turn white.
    I want to do the same thing, using numeric indicator boxes inside the array.
    Thanks for any suggestions...
    Attachments:
    Fill DME matrix.vi ‏95 KB

    Get rid of all these sequences! That's just bad form.
    Your code has a few logical problems. Why do you create a boolean array if you later only look at the last element (Yes, the FOR loop does nothing useful, except in the last iteration because your outputs are not indexing. All other iterations are useless, you only get the result of the last array element. My guess is that you want to color the index white if at least one of the numbers is out if range. Right?
    It is an absolute nightmare to manage all your numeric labels. Just read them from a 2D array. Now you can simply find the index of the matched elements and don't have to spend hours editing case structure conditions.
    Attached is a simple example how you would do what I meant (LV7.1). Modify as needed.
    Message Edited by altenbach on 04-04-2006 02:04 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    Fill_2DME_matrixMOD.vi ‏70 KB

  • Can we change the color of each cell in TableView in HTMLB

    Hi
    I want to change the cell color in TableView dynamically.
    Can we change the color of each cell in TableView in HTMLB?
    If yes, give the exact solution.
    Regards,
    Nithya

    Hi Nithya,
    You would have to implement your own ICellRenderer, see http://help.sap.com/javadocs/NW04S/SPS09/hb/com/sapportals/htmlb/table/ICellRenderer.html and then use http://help.sap.com/javadocs/NW04S/SPS09/hb/com/sapportals/htmlb/table/TableView.html#setCellRenderer(com.sapportals.htmlb.table.ICellRenderer)
    Also see TableView Cellls and how to add colors to table cells
    Hope it helps
    Detlev

  • Changing background color in JTable, only changes one row at a time...

    I'm trying to change the color of rows when the 5th column meets certain criteria. I think I'm very close, but I've hit a wall.
    What's happening is the row will change color as intended when the text in the 5th column is "KEY WORD", but when I type "KEY WORD" in a different column it will set the first row back to the regular colors. I can easily see why it's doing this, everytime something is changed it rerenders every cell, and the listener only checks the cell that was just changed if it met the "KEY WORD" condition, so it sets every cell (including the previous row that still meets the condition) to the normal colors. I can't come up with a good approach to changing the color for ALL rows that meet the condition. Any help would be appreciated.
    In this part of the CellRenderer:
            if (isSelected)
                color = Color.red;
            else
                color = Color.blue;
            if (hasFocus)
                color = Color.yellow;
            //row that meets special conditions
            if(row == specRow && col == specCol)
                color = color.white; I was thinking an approach would be to set them to their current color except for the one that meets special conditions, but the two problems with that are I can't figure out how to getColor() from the table, and I'm not sure how I would initially set the colors.
    Here's the rest of the relevant code:
        public void tableChanged(TableModelEvent e)
            int firstRow = e.getFirstRow();
            int lastRow  = e.getLastRow();
            int colIndex = e.getColumn();
            if(colIndex == 4)
                String value = (String)centerTable.getValueAt(firstRow, colIndex);
                // check for our special selection criteria
                if(value.equals("KEY WORD"))
                    for(int j = 0; j < centerTable.getColumnCount(); j++)
                        CellRenderer renderer =
                            (CellRenderer)centerTable.getCellRenderer(firstRow, j);
                        renderer.setSpecialSelection(firstRow, j);
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.Component;
    import java.awt.Color;
    public class CellRenderer extends DefaultTableCellRenderer
        int specRow, specCol;
        public CellRenderer()
            specRow = -1;
            specCol = -1;
        public Component getTableCellRendererComponent(JTable table,
                                                       Object value,
                                                       boolean isSelected,
                                                       boolean hasFocus,
                                                       int row, int col)
            setHorizontalAlignment(JLabel.CENTER);
            Color color = Color.green;
            if (isSelected)
                color = Color.red;
            else
                color = Color.blue;
            if (hasFocus)
                color = Color.yellow;
            if(row == specRow && col == specCol)
                color = color.white;
            //setForeground(color);
            setBackground(color);
            setText((String)value);
            return this;
        public void setSpecialSelection(int row, int col)
            specRow = row;
            specCol = col;
    }If I'm still stuck and more of my code is needed, I'll put together a smaller program that will isolate the problem tomorrow.

    That worked perfectly for what I was trying to do, but I've run into another problem. I'd like to change the row height when the conditions are met. What I discovered is that this creates an infinite loop since the resizing triggers the renderer, which resizes the row again, etc,. What would be the proper way to do this?
    Here's the modified code from the program given in the link. All I did was declare the table for the class, and modify the if so I could add the "table.setRowHeight(row, 30);" line.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    public class TableRowRenderingTip extends JPanel
        JTable table;
        public TableRowRenderingTip()
            Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
            Object[][] data =
                {"Buy", "IBM", new Integer(1000), new Double(80.5), Boolean.TRUE},
                {"Sell", "Dell", new Integer(2000), new Double(6.25), Boolean.FALSE},
                {"Short Sell", "Apple", new Integer(3000), new Double(7.35), Boolean.TRUE},
                {"Buy", "MicroSoft", new Integer(4000), new Double(27.50), Boolean.FALSE},
                {"Short Sell", "Cisco", new Integer(5000), new Double(20), Boolean.TRUE}
            DefaultTableModel model = new DefaultTableModel(data, columnNames)
                public Class getColumnClass(int column)
                    return getValueAt(0, column).getClass();
            JTabbedPane tabbedPane = new JTabbedPane();
            tabbedPane.addTab("Alternating", createAlternating(model));
            tabbedPane.addTab("Border", createBorder(model));
            tabbedPane.addTab("Data", createData(model));
            add( tabbedPane );
        private JComponent createAlternating(DefaultTableModel model)
            JTable table = new JTable( model )
                public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
                    Component c = super.prepareRenderer(renderer, row, column);
                    //  Alternate row color
                    if (!isRowSelected(row))
                        c.setBackground(row % 2 == 0 ? getBackground() : Color.LIGHT_GRAY);
                    return c;
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            table.changeSelection(0, 0, false, false);
            return new JScrollPane( table );
        private JComponent createBorder(DefaultTableModel model)
            JTable table = new JTable( model )
                private Border outside = new MatteBorder(1, 0, 1, 0, Color.RED);
                private Border inside = new EmptyBorder(0, 1, 0, 1);
                private Border highlight = new CompoundBorder(outside, inside);
                public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
                    Component c = super.prepareRenderer(renderer, row, column);
                    JComponent jc = (JComponent)c;
                    // Add a border to the selected row
                    if (isRowSelected(row))
                        jc.setBorder( highlight );
                    return c;
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            table.changeSelection(0, 0, false, false);
            return new JScrollPane( table );
        public JComponent createData(DefaultTableModel model)
            table = new JTable( model )
                public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
                    Component c = super.prepareRenderer(renderer, row, column);
                    //  Color row based on a cell value
                    if (!isRowSelected(row))
                        c.setBackground(getBackground());
                        String type = (String)getModel().getValueAt(row, 0);
                        if ("Buy".equals(type)) {
                            table.setRowHeight(row, 30);
                            c.setBackground(Color.GREEN);
                        if ("Sell".equals(type)) c.setBackground(Color.YELLOW);
                    return c;
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            table.changeSelection(0, 0, false, false);
            return new JScrollPane( table );
        public static void main(String[] args)
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        public static void createAndShowGUI()
            JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new JFrame("Table Row Rendering");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add( new TableRowRenderingTip() );
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    }Edited by: scavok on Apr 26, 2010 6:43 PM

  • Changing Row Color In JTable !

    Hi friends
    I have two JTables. The first one has 7 columns and 10 rows (with data) but the second one is empty.
    The user can choose one row from first table and by pressing the ((copy)) button , copy that row to the second table. Is it possible to change the color of those rows(in the first table) that been copied to the second table. I mean if the user choose a row and copy then to the second table, the color of this row wold be changed.
    Can anybody help me with that??
    Thanks

    I think you are heading in the wrong direction here... you want to create a brand new DefaultTableCellRenderer and override the getTableCellRendererComponent method...
    public class MyRenderer extends DefaultTableCellRenderer {
      public Component getTableCellRendererComponent(JTable table, Object value,
                              boolean isSelected, boolean hasFocus, int row, int column) {
                  JLabel lbl = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
                               row, column);
                  //now I can change the background color depending on the row...
                  if (row == xxx) lbl.setBackground(Color.red);
    }Then use your new class on your table...
    <table.setDefaultRenderer(Object.class, new MyRenderer()); //the class must match what you TableModel returns for getColumnClass();Hope this helps,
    Josh Castagno
    http://www.jdc-software.com
    Hope this helps

  • Programatically change( edit?? ) JTable cell value

    If my user changes the value in cell 'A', I'd like to change the value in cell 'B' to the results of a calculation performed using the new value in A with the present ( prior to changing ) value in B.
    Example:
    Cell: suggested_sell_price
    Cell: cost_this_item
    A change in the cost_this_item cell would be reflected in the suggested_sell_price,(upon hitting enter the values are stored in the DB)
    Any suggestions would be greatly appreciated,

    Thanks for the suggestions. I'm posting a test program of what I have at the moment, it has some of the behavior I'm looking for, but I can't seem to get the new value of an aedited cell and set the table model with the new value.
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class TE extends JFrame
         String[] cols = {"VAL_1", "VAL_2", "VAL_3"};
         Object[][] filler = {
                                       {new Double(100.00), new Double(100.00), new Double(100.00)},
                                       {new Double(200.00), new Double(200.00), new Double(200.00)},
                                       {new Double(400.00), new Double(400.00), new Double(400.00)}
         JTable table;
         TE(String title)
                   super(title);
                   this.setDefaultCloseOperation(EXIT_ON_CLOSE);
                   MTM mtm = new MTM(3, cols.length);
                   mtm.setColumnIdentifiers(cols);
                   int nRows = filler.length;
                   for(int i = 0; i < nRows; ++i)
                             mtm.setValueAt(filler[0], 0, i);
                             mtm.setValueAt(filler[1][i], 1, i);
                             mtm.setValueAt(filler[2][i], 2, i);
                   table = new JTable(mtm);
                   table.getColumnModel().getColumn(1).setCellEditor(new SimpleCellEditor());
                   table.getColumnModel().getColumn(2).setCellEditor(new SimpleCellEditor());
                   //table.getColumnModel().getColumn(2).setCellEditor(new SimpleCellEditor());
                   JScrollPane jsp = new JScrollPane(table);
                   Container c = getContentPane();
                   c.add(jsp);
                   setSize(300,300);
                   setVisible(true);
         class MyMouseListener extends MouseAdapter
                   public void mouseClicked(MouseEvent e)
                        if(e.getClickCount() == 2)
                                  table.setValueAt("QQQQQQQ", 1,1);
    class SimpleCellEditor extends AbstractCellEditor implements TableCellEditor, ActionListener
         JTextField tf = new JTextField();
         TableModel tm = table.getModel();
         protected EventListenerList listenerList = new EventListenerList();
         protected ChangeEvent changeEvent = new ChangeEvent(this);
         public SimpleCellEditor()
                   super();                              
                   tf.addMouseListener(new MyMouseListener());
                   tf.addActionListener(this);
    public void addCellEditorListener(CellEditorListener listener) {
    listenerList.add(CellEditorListener.class, listener);
    public void removeCellEditorListener(CellEditorListener listener) {
    listenerList.remove(CellEditorListener.class, listener);
    protected void fireEditingStopped()
              CellEditorListener listener;
              Object[] listeners = listenerList.getListenerList();
              for (int i = 0; i < listeners.length; i++)
                   if (listeners[i] == CellEditorListener.class)
                             listener = (CellEditorListener) listeners[i + 1];
                             listener.editingStopped(changeEvent);
    protected void fireEditingCanceled()
         CellEditorListener listener;
              Object[] listeners = listenerList.getListenerList();
                   for (int i = 0; i < listeners.length; i++)
                   if (listeners[i] == CellEditorListener.class)
                        listener = (CellEditorListener) listeners[i + 1];
                        listener.editingCanceled(changeEvent);
    public void cancelCellEditing()
              fireEditingCanceled();
    public boolean stopCellEditing()
              fireEditingStopped();
              return true;
    public boolean isCellEditable(EventObject event)
              return true;
         public boolean shouldSelectCell(EventObject event)
         return true;
    public Object getCellEditorValue()
         return tf.getText();
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
         if(tf.hasFocus() == true)
                   tf.setBackground(Color.CYAN);
              return tf;
         public void actionPerformed(ActionEvent e)
              int row = table.getSelectedRow();
              int col = table.getSelectedColumn();
              double nVal = 0.00;
              Object currCostVal;
              Object currSellVal;
              Double costVal;
              Double sellVal;
              double newSellVal;
              double currentCost;
              if(table.getSelectedColumn() == 1)
                   currCostVal = table.getValueAt(row, col+1);
                   currSellVal = table.getValueAt(row, col);
                   costVal = new Double(currCostVal.toString());
                   currentCost = costVal.doubleValue();
                   sellVal = new Double(currSellVal.toString());
                   newSellVal = sellVal.doubleValue();
                   nVal = newSellVal*currentCost*100/100;
                   System.out.println("Recommended sell-price after change: " + nVal);
              }else if(table.getSelectedColumn() == 2 )
                        currCostVal = table.getValueAt(row, col);
                        currSellVal = table.getValueAt(row, col-1);
                        costVal = new Double(currCostVal.toString());
                        currentCost = costVal.doubleValue();
                        sellVal = new Double(currSellVal.toString());
                        newSellVal = sellVal.doubleValue();
                        nVal = newSellVal*currentCost*100/100;
                        System.out.println("Recommended sell-price after change: " + nVal);
                        System.out.println("Cost column selected " + nVal);
    }// end simple cell editor
    class MTM extends DefaultTableModel
              MTM(int rows, int cols)
                        super(rows, cols);
    public static void main(String args[])
              TE te = new TE("Test of table cell update");

  • Can't find info button to change calendar color

    Am now using Leopard with iCal and want to change the color of a calendar. There is no info button on the lower right-hand corner. Where is it now?

    I don't have a drop-down menu in the upper right hand corner. In the Get Info window, I must click the 'Edit' button to access the colour option.
    Two other methods to do access this is double clicking on the event which will bring up the Info window (and where you then choose 'Edit') or click on the event (once) and use the Command-E keystroke combination which will bring up the event window immediately in edit mode (the keyboard command for 'Edit Event...' under the 'Edit' menu)

  • Jasper Export to excel: changing background color of the cell/field

    Hi all,
    I have designed a report containing a set of 5 different fields. All these are STRING values.
    Among these are two fields named: BUDGETED and ACTUAL.
    I want to show the data corresponding to ACTUAL in red color if the value of ACTUAL is greater than BUDGETED when exported in excel format.
    The value itself should be displayed in red color or the excel cell should have a color red
    Can someone please help me in this? How can we implement the logic to compare these two values?
    Thanks in advance.

    You are using Jasper and you thought: hey, let me post a question in the Oracle Reports forum?

  • How to change background color to JCheckBox in a JTable?

    Dear Friends,
    I have an JTable in my application. It has four columns. First, third and fourth column contains JCheckBox (JCheckBox is created using Boolean.class), secod column contains values.
    I have to change some of the cell color where JCheckBox is present.
    Could anyone please tell me how to change the color of the cell in the JTable?
    Thanks in advance,
    Sathish kumar D

    You would use a custom renderer.
    To get better help sooner, post a SSCCE that clearly demonstrates your problem.
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    db
    Alternative link: SSCCE
    Edited by: Darryl.Burke

  • How do i change the cell color of each cell in datagrid dynamically

    I have a  datagrid filled in with data..My job is to change the cell color of a particular cell in the datagrid when the user clicks that cell..Please help me asap..I have to change the color of each cell dynamically..

    Pls find the solution of ur problem.Let me know if you have any issue.
    MainApplicaion.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical">
        <mx:Script>
            <![CDATA[
                import mx.collections.ArrayCollection;
                import mx.events.ListEvent;
                [Bindable]
                  private var listDataArrayCollection:ArrayCollection=
                  new ArrayCollection([
                    {seq:'1',color:'0xFF0000', names:'John'},
                    {seq:'2',color:'0x00FF00', names:'Alex'},
                    {seq:'3',color:'0x0000FF', names:'Peter'},
                    {seq:'4',color:'0xFF0000', names:'Sam'},
                    {seq:'5',color:'0x00FF00', names:'Alis'},
                    {seq:'6',color:'0x0000FF', names:'Robin'},
                    {seq:'7',color:'0xFF0000', names:'Mark'},
                    {seq:'8',color:'0x00FF00', names:'Steave'},
                    {seq:'9',color:'0x0000FF', names:'Fill'},
                    {seq:'10',color:'0xFF0000', names:'Abraham'},
                    {seq:'11',color:'0x00FF00', names:'Hennery'},
                    {seq:'12',color:'0x0000FF', names:'Luis'},
                    {seq:'13',color:'0xFF0000', names:'Herry'},
                    {seq:'14',color:'0x00FF00', names:'Markus'},
                    {seq:'15',color:'0x0000FF', names:'Flip'},
                    {seq:'16',color:'0xFF0000', names:'John_1'},
                    {seq:'17',color:'0x00FF00', names:'Alex_1'},
                    {seq:'18',color:'0x0000FF', names:'Peter_1'},
                    {seq:'19',color:'0xFF0000', names:'Sam_1'},
                    {seq:'20',color:'0x00FF00', names:'Alis_1'},
                    {seq:'21',color:'0x0000FF', names:'Robin_1'},
                    {seq:'22',color:'0xFF0000', names:'Mark_1'},
                    {seq:'23',color:'0x00FF00', names:'Steave_1'},
                    {seq:'24',color:'0x0000FF', names:'Fill_1'},
                    {seq:'25',color:'0xFF0000', names:'Abraham_1'},
                    {seq:'26',color:'0x00FF00', names:'Hennery_1'},
                    {seq:'27',color:'0x0000FF', names:'Luis_1'},
                    {seq:'28',color:'0xFF0000', names:'Herry_1'},
                    {seq:'29',color:'0x00FF00', names:'Markus_1'},
                    {seq:'30',color:'0x0000FF', names:'Flip_2'}
                private function onItemClick(event : ListEvent):void
                    var dataObj : Object = event.itemRenderer.data;
                    dataObj.color = "0xFF00FF";
                    event.itemRenderer.data = dataObj;
            ]]>
        </mx:Script>
        <mx:VBox width="300" height="100%"
            horizontalAlign="center"
            verticalAlign="middle">
            <mx:DataGrid id="listComponent" width="50%"
                     height="100%"
                     borderStyle="none"
                     dataProvider="{listDataArrayCollection}"
                     itemClick="onItemClick(event)">
                     <mx:columns>
                     <mx:DataGridColumn width="100" dataField="{data.seq}" headerText="Seq" itemRenderer="SeqItemRenderer" />
                     <mx:DataGridColumn width="100" dataField="{data.names}" headerText="Name" itemRenderer="NameItemRenderer"/>
                     </mx:columns>
                     </mx:DataGrid>
        </mx:VBox>
    </mx:Application
    NameItemRenderer.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml"
        width="100" height="30" horizontalGap="5" horizontalScrollPolicy="off">
    <mx:Script>
        <![CDATA[
            override public function set data(value:Object):void
                 super.data = value;
        ]]>
    </mx:Script>
            <mx:TextInput width="75" height="30"
                 text="{data.names}"
                 editable="false" backgroundColor="{data.color}"/>
        </mx:HBox>
    SeqItemRenderer.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml"
        width="100" height="30" horizontalGap="5" horizontalScrollPolicy="off">
    <mx:Script>
        <![CDATA[
            override public function set data(value:Object):void
                 super.data = value;
        ]]>
    </mx:Script>
            <mx:TextInput width="75" height="30"
                 text="{data.seq}"
                 editable="false" backgroundColor="{data.color}"/>
        </mx:HBox>
    with Regards,
    Shardul Singh Bartwal

  • I failed to  color  JTable cells

    Hello,
    I'm trying to set the background color of JTable cells based on their content.
    For example if I edit a cell and put a R, I'd like to paint the background in Red.
    If I enter B, I want it becomes Blue, and so on.
    I tried to use a few examples found in various fora, but all failed.
    in addition, I do not understand why I should extend JLabel and not another Class ?
    Thanks for help.
    Here is a sample code (in which all cells should become red whatever is typed in).
    import javax.swing.table.*;
    import javax.swing.*;
    public class TableRenderer extends JLabel implements javax.swing.table.TableCellRenderer {
    public java.awt.Component getTableCellRendererComponent
        javax.swing.JTable table,
       Object value,
       boolean isSelected,
       boolean hasFocus,
       int row,
       int column
         setBackground(java.awt.Color.red);   // for the moment All cells will be red
         return this;
       mytable  = new javax.swing.JTable(5,5);
       TableColumn[] column = new TableColumn[5];
       TableColumnModel colModel = mytable.getColumnModel();
       for (int i=0; i <5 ;i++)
                    column[i] = colModel.getColumn( i );
                    column.setCellRenderer(new TableRenderer());

    Finally after many tries I found a good way to do what I wanted.
    If some people are interested, here is the code.
    import java.awt.*;
    import javax.swing.table.*;
    import javax.swing.*;
    class MyClass
    public class TableRenderer extends javax.swing.table.DefaultTableCellRenderer
    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column)
         Component xx = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
            String val = (String) table.getValueAt(row, column);
            if (gegeutil.Gegetools.isEmpty(val)) super.setBackground(Color.white);
            else if(val.equals("Tournament")) super.setBackground(Color.red);
              else if(val.equals("Class"))super.setBackground(Color.orange);
              else if(val == "")           super.setBackground(Color.white);
            else super.setBackground(Color.blue);          
                   return xx;
    public TableRenderer() {
         super();
    JTable table = new JTable(nbrow, nbcolumn);
    table.setDefaultRenderer(Object.class, new TableRenderer());
    }

  • JTable cell render problem, help!

    Hi all,
    I'm trying to change the color of some cells in a JTable. I have the definition of what cell to render in a different color in a Vector. So each time the cell render is called, I check if the cell it's in my vector, and if yes I change the background color to red.
    The problem is, the result are not the desired, some cells are some times in red other times in red! Some one have an idea of what appends?
    Thanks NeuralC
    public Component getTableCellRendererComponentJTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    Component cell = super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column);
    for(int i=0;i<((LinhaRefresh)RefreshOjb.elementAt(row)).Gamas.size();i++){
    if(((column)>=((Gama)((LinhaRefresh)RefreshOjb.elementAt(row)).Gamas.elementAt(i)).inicio) & ((column) <=((Gama)((LinhaRefresh)RefreshOjb.elementAt(row)).Gamas.elementAt(i)).fim)){
    cell.setBackground(Color.red);
    return cell;
    cell.setBackground(Color.white);
    return cell;
    }

    Hi,
    AND symbol is &, and I must use it.
    I haved solved the problem, extending my cell render to a JLabel. With this and making my self the selection color everything works fine.
    Thanks for interrest.
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    JLabel lb = new JLabel((String)value);
    //Component cell = super..;
    setText((String)value);
    if(!isSelected){
    setBackground(Color.white);
    else{
    setBackground(Color.blue);
    for(int i=0;i<((LinhaRefresh)RefreshOjb.elementAt(row)).Gamas.size();i++){
    if(((column)>=((Gama)((LinhaRefresh)RefreshOjb.elementAt(row)).Gamas.elementAt(i)).inicio) & ((column) <=((Gama)((LinhaRefresh)RefreshOjb.elementAt(row)).Gamas.elementAt(i)).fim)){
    if(hasFocus){
    setToolTipText("est� dentro"+column);
    setBackground(Color.red);
    return this;

  • Changing appearance of active spreadsheet cell

    This is a question our school secretary asked of me. She has recently upgraded from an eMac to a new iMac. She works quite a bit in spreadsheets. In a spreadsheet, the active cell is outlined in light blue, which she finds hard to see, especially if it is in the middle of the screen rather than at an edge. She would like to change the appearance to an allover color in just the active cell she is working on.
    I have been unable to find a way for her to do this. I can change the color of the cell, but it remains with the cell instead of moving with the active cell.
    Has anyone found a way to do this?
    Message was edited by: Sara Hartman

    "(W)hat she was hoping was that the cell could be shaded in rather than outlined. Do you know of any way this can be done?"
    Hi Sara,
    Well, I suppose it could be done by re-writing the AppleWorks source code , but that's beyond my meagre talents.
    There's at least a faint possibility it could be done by a talented scripter using AppleScript, but that would depend on a way to tell AppleScript which was the active cell, telling AppleWorks to fill that cell with a colour, detecting when the cell is no longer 'active' and telling AW to then replace the 'highlight colour' with whatever fill state existed before. It's a fairly simple set of steps, but putting it into AppleScript and having the script act continuously and automatically is another matter.
    There are a few scripters who read and participate in this forum, so hope is not lost yet.
    Regards,
    Barry

Maybe you are looking for

  • Can no longer customize Web galleries

    Just reposted on this new forum, when I discovered after over 2 weeks that the other one was read only.  I hope someone here has a clue.  I didn't know if the question was not understandable or that no one bothers to modify the galleries, which now a

  • Information on table type datatypes.

    Hi, I am working with the table type composite datatype. After I insert the values to the table type declared variable how will I be able to print that or use it in further DML operations. example create or replace procedure xxx_proc as type u_rec is

  • Constant Buzzing and Can't make outgoing calls

    For the past month or so, our phone line has had a constant buzzing. Now, we cannot even get a dialtone to make outgoing calls. We do receive calls, but it doesn't do us much good since the buzzing prevents us from talking to anyone anyway.

  • TOOLS missing in Adobe X

    I read an earlier post about this, but I have Windows Vista.  F8 is not bringing up the TOOLS bar.  I see the COMMENT bar and the SHARE bar, but no TOOLS bar.  Please help.

  • Previewing webpage, images are displayed slightly grey!!

    Hi, I have created a web page which illustrates cd covers, when you clck te imag it plays a quicktime .mov file. the thing is the image when in dreamweaver looks fine, crisp and sharp. but when i preview in a browser or upload and view the images loo