Setting table cell background

Friends,
I have a JTable with 5 rows and 4 columns now I want to set the Background color of cells as I select the set of cells it changes the background color.
the problem in the below code is I have to select the individual cells to set the bg. can anyone tell what I should add to set bg of all the selection + I am unable to see the cell selection.
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
* This is like TableDemo, except that it substitutes a
* Favorite Color column for the Last Name column and specifies
* a custom cell renderer and editor for the color data.
public class TestClass extends JPanel implements MouseListener {
     private boolean DEBUG = false;
     private JTable table;
     private Color defColor = Color.WHITE;
     private Color selColor = Color.GRAY;
     private Color[][] color = {
          {defColor, defColor, defColor, defColor, defColor},
          {defColor, defColor, defColor, defColor, defColor},
          {defColor, defColor, defColor, defColor, defColor},
          {defColor, defColor, defColor, defColor, defColor},
          {defColor, defColor, defColor, defColor, defColor}
     public TestClass() {
          super(new GridLayout(1,0));
          table = new JTable(new MyTableModel());
          table.setRowSelectionAllowed(false);
          table.setCellSelectionEnabled(true);
          table.addMouseListener(this);
          table.setPreferredScrollableViewportSize(new Dimension(500, 70));
          //Create the scroll pane and add the table to it.
          JScrollPane scrollPane = new JScrollPane(table);
          //Set up renderer and editor for the Favorite Color column.
          table.setDefaultRenderer(String.class,
                                         new ColorRenderer(color));
          //Add the scroll pane to this panel.
          add(scrollPane);
     class MyTableModel extends AbstractTableModel {
          private String[] columnNames = {"First Name",
                                                  "Favorite Color",
                                                  "Sport",
                                                  "# of Years",
                                                  "Vegetarian"};
          private Object[][] data = {
          public int getColumnCount() {
               return columnNames.length;
          public int getRowCount() {
               return data.length;
          public String getColumnName(int col) {
               return columnNames[col];
          public Object getValueAt(int row, int col) {
               return data[row][col];
           * JTable uses this method to determine the default renderer/
           * editor for each cell.  If we didn't implement this method,
           * then the last column would contain text ("true"/"false"),
           * rather than a check box.
          public Class getColumnClass(int c) {
               return getValueAt(0, c).getClass();
          public boolean isCellEditable(int row, int col) {
               return false;
          public void setValueAt(Object value, int row, int col) {
               if (DEBUG) {
                    System.out.println("Setting value at " + row + "," + col
                                           + " to " + value
                                           + " (an instance of "
                                           + value.getClass() + ")");
               data[row][col] = value;
               fireTableCellUpdated(row, col);
               if (DEBUG) {
                    System.out.println("New value of data:");
                    printDebugData();
          private void printDebugData() {
               int numRows = getRowCount();
               int numCols = getColumnCount();
               for (int i=0; i < numRows; i++) {
                    System.out.print("    row " + i + ":");
                    for (int j=0; j < numCols; j++) {
                         System.out.print("  " + data[i][j]);
                    System.out.println();
               System.out.println("--------------------------");
      * Create the GUI and show it.  For thread safety,
      * this method should be invoked from the
      * event-dispatching thread.
     private static void createAndShowGUI() {
          //Make sure we have nice window decorations.
          JFrame.setDefaultLookAndFeelDecorated(true);
          //Create and set up the window.
          JFrame frame = new JFrame("TableDialogEditDemo");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          //Create and set up the content pane.
          JComponent newContentPane = new TestClass();
          newContentPane.setOpaque(true); //content panes must be opaque
          frame.setContentPane(newContentPane);
          //Display the window.
          frame.pack();
          frame.setVisible(true);
     public static void main(String[] args) {
          //Schedule a job for the event-dispatching thread:
          //creating and showing this application's GUI.
          javax.swing.SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                    createAndShowGUI();
     /* (non-Javadoc)
      * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
     public void mouseClicked(MouseEvent e) {
          if (table.getSelectedColumn() > 0) {
               if (color[table.getSelectedRow()][table.getSelectedColumn()] == selColor) {
                    color[table.getSelectedRow()][table.getSelectedColumn()] = defColor;
               } else {
                    color[table.getSelectedRow()][table.getSelectedColumn()] = selColor;
          } else {
          ((MyTableModel)table.getModel()).fireTableStructureChanged();
     /* (non-Javadoc)
      * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
     public void mouseEntered(MouseEvent e) {
     /* (non-Javadoc)
      * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
     public void mouseExited(MouseEvent e) {
     /* (non-Javadoc)
      * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
     public void mousePressed(MouseEvent e) {
     /* (non-Javadoc)
      * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
     public void mouseReleased(MouseEvent e) {
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.border.Border;
import javax.swing.table.TableCellRenderer;
import java.awt.Color;
import java.awt.Component;
public class TableCellColorRenderer extends JLabel
                           implements TableCellRenderer {
    Color[][] colorBG = null;
    public TableCellColorRenderer(Color[][] color) {
        this.colorBG = color;
        setOpaque(true); //MUST do this for background to show up.
    public Component getTableCellRendererComponent(
                            JTable table, Object color,
                            boolean isSelected, boolean hasFocus,
                            int row, int column) {
          setBackground(colorBG[row][column]);
        return this;

I would guess that it's because you set the background to Color.WHITE
I'm not sure why you're passing in an array of Color objects ... typically you'd either pick the color based on the value of the cell, or use standard colors.
Finally, your getTableCellRendererComponent() should check the isSelected argument, and use a different color to highlight the selection.

Similar Messages

  • How to set table cell renderer in a specific cell?

    how to set table cell renderer in a specific cell?
    i want set a cell to be a button in renderer!
    how to do?
    any link or document can read>?
    thx!

    Take a look at :
    http://www2.gol.com/users/tame/swing/examples/SwingExamples.html
    It is very interesting, and I think your answer is here.
    Denis

  • Table cell background  color in PDF

    I have a requirement to generate a PDF from a stoplight report.
    The stoplight report colors were implemented by setting the background color in table cells
    via css (background-color: red;). Its working in the browser but when I generate a pdf the cells show up with grey backgrounds. How can I generate a pdf with the correct colors?
    Thanks for your help.
    I'm using Apex 3.1 and pdf generation functionality that comes with Apex. I don't have BI Publisher.

    Hi David.
    At this time you don't get WYSIWYG reports in PDF.
    You're limited to the Column Colour settings you can specify in the Print Attributes of the report region but these would apply to all columns in the report and would not be dynamic.
    This may be something that is addressed in a future version of APEX.
    If anyone else knows different, feel free to chip in.
    Regards
    Simon

  • Setting Table Cell Renderer for a row or cell

    I need to make a JTable that has the following formats:
    Row 1 = number with no decimals and columns
    Row 2 = number with no decimals and columns
    Row 3 = percent with 4 decimals
    I can use a table cell renderer to set each COLUMN as one or the other formats like this:
    NumDispRenderer ndr = new NumDispRenderer();
    for(int i = 1;i<dates.size();i++) {
    table.getColumnModel().getColumn(i).setCellRenderer(ndr);
    Where NumDispRenderer is a class as follows:
    public class NumDispRenderer extends DefaultTableCellRenderer {
    public Component getTableCellRendererComponent (JTable table, Object value,boolean isSelected, boolean isFocused, int row, int column) {
    Component component = super.getTableCellRendererComponent (table,value,isSelected,isFocused,row,column);
    if (value != null && value instanceof Double) {
    DecimalFormat df = new DecimalFormat("###,###");
    String output = df.format(value);
    ((JLabel)component).setText(output);
    ((JLabel)component).setHorizontalAlignment(JLabel.RIGHT);
    } else {
    ((JLabel)component).setText(value == null ? "" : value.toString());
    return component;
    This is fine for the first two rows, but the third row (which is also an instance of Double) I would like to format differently.
    The tutorial and other postings have not given a solution to this problem. Any suggestions would be very appreciated.

    Hi,
    the method getTableCellRendererComponent() of your renderer gets the row as a parameter. So just create the label depending on that value. For 0<=row<=1 you create the label as is, and for row=2 you create another label with the Double formatted as you wish.
    Andre

  • Setting table/cell strokes to overprint

    is there a way to ad line in following script to set cell strokes in overprint?
    this script has been very useful to me (thanks to Jongware (http://forums.adobe.com/message/2818852#2818852)) but it's missing the overprint feature for strokes.
    table = app.selection[0];
    if (table.hasOwnProperty("baseline"))
    table = table.parent;
    if (table instanceof Cell)
    table = table.parent;
    if (table instanceof Column)
    table = table.parent;
    if (table instanceof Row)
    table = table.parent;
    if (!(table instanceof Table))
    alert ("Echt niet in een tabel!");
    exit(0);
    color = table.cells[0].characters[0].fillColor;
    black = app.activeDocument.swatches.item("Black");
    table.cells.everyItem().properties = {
    topEdgeStrokeColor:color,
    bottomEdgeStrokeColor:color,
    leftEdgeStrokeColor:color,
    rightEdgeStrokeColor:color };
    for (aCell=0; aCell<table.cells.length; aCell++)
    if (table.cells[aCell].fillTint == 50)
      table.cells[aCell].fillColor = color;
    tia, Pascal

    Hey!
    It's easy to solve your problem.
    In red is what you have to add...
    table =  app.selection[0];
    if  (table.hasOwnProperty("baseline"))
    table = table.parent;
    if  (table instanceof  Cell)
    table = table.parent;
    if  (table instanceof  Column)
    table = table.parent;
    if (table instanceof Row)
    table = table.parent;
    if (!(table instanceof  Table))
    alert ("Echt niet in een tabel!");
    exit(0);
    color =  table.cells[0].characters[0].fillColor;
    black =  app.activeDocument.swatches.item("Black");
    table.cells.everyItem().properties  = {
    topEdgeStrokeColor:color,
    bottomEdgeStrokeColor:color,
    leftEdgeStrokeColor:color,
    rightEdgeStrokeColor:color,
    bottomEdgeStrokeOverprint:true,
    leftEdgeStrokeOverprint:true,
    rightEdgeStrokeOverprint:true,
    topEdgeStrokeOverprint:true};
    for (aCell=0;  aCell<table.cells.length; aCell++)
    if (table.cells[aCell].fillTint == 50)
       table.cells[aCell].fillColor = color;
    tomaxxi

  • Set Table Row Background image

    Hi all,
    I'd like to set a Table row background image, but I only find a way to set a background image for each column, is there any way to set an image  as background for a whole row?

    Hi Pakojones,
    Based on my test, it is not support to make the image tile in a row. The BackgroundRepeat values of tablix is Repeat, RepeatX, RepeatY, or Clip. In SSRS, just chart BackgroundRepeat can be set to Fit.
    Reference: http://technet.microsoft.com/en-us/library/dd239334.aspx
    In SSRS, we can put tablix in a rectangle, then add background image for the rectangle. We can tile the image over the whole tablix. If we want to make the image tile in a row, we can put the single row in a rectangle to work around it. In this situation,
    we have to seamless paste the tablix in the end.
    Alternatively, since the issue is by design, I recommend you that submit this suggestion at
    https://connect.microsoft.com/SQLServer/ . If the suggestion mentioned by customers for many times, the product team may consider to add the feature in the next SQL Server version. Your feedback is valuable
    for us to improve our products and increase the level of service provided.
    Regards,
    Alisa Tang 
    Alisa Tang
    TechNet Community Support

  • Setting table cell data dynamically

    All
    If I have the server sending me data. And I want to lookup the row in a tableView to update it. When I try the following the screen does not refresh.
    ObservableList<DataRow> dataList = getTable().getItems();
    marketDataEvent.setNewValue(newValue);
    Do I need to call refresh on the table?

    No need. Found at the cells need to be set as SimpleDoubleProperty, and you need a getter on the SimpleDoubleProperty field.

  • Tables/Cells/Background images

    Hello, this is probably a very minor issue but I am new to Dreamweaver so please bear with me (I am fairly technologically inclined and have a solid understanding of InDesign and Photoshop so I'm not a total beginner!).  I am trying to prepare an html email and from Google research I decided to construct a layout in a table with a top banner cell then two cells in the inside and a bottom banner cell (ie top banner, two columns, bottom banner if that makes sense).  I can't for the life of me figure out how to get a background image within an individual cell within the table.  I have looked up many articles on this and it looks so simple - select the cell, then in the Bg field you can either select a color or click the folder icon and choose a graphic.  I only have one Bg field and that is to select a color, no option no matter how I click, to get a Bg image.  Help please help!  Thank you!!!

    HTML emails can be very challenging if you've never done one before.  Suggest you read this over first.
    http://alt-web.blogspot.com/2010/02/html-emails-and-newsletters.html
    Nancy O.
    Alt-Web Design & Publishing
    Web | Graphics | Print | Media  Specialists
    http://alt-web.com/
    http://twitter.com/altweb
    http://alt-web.blogspot.com

  • Guide to set the cell background color and foreground color

    hi all,
    I am using a tool called POI for excel from java. IF any body know POI please tell me the various colors --------> equivalent Short number. I need the color and equavlent number for better usage.
    please respond as early as possible.

    Hi
    Use the class HSSFColor at org.apache.poi.hssf.util and the inner classes defined, for example (sample form jakarta.poi):
    style.setFillForegroundColor(HSSFColor.ORANGE.index);
    or for a cell
    cell.setFillForegroundColor(HSSFColor.ORANGE.index);
    If you need know what index for a color may be at source code you can see the implementation.
    Hope this helps

  • Set cell background color conditionally?

    I want to set a cells' background colors conditionally, e.g., if the computer value is between 5 to 9, make the background red. Is there any way to do that?

    That is a good question. It would appear it does not work. A way around it is to put 1:00 (1 hour duration, not 1 o'clock) in a cell and a 1:30 in another then reference those cells as your two conditions.
    This is not the only place where the duration format is not fully implemented.

  • Is it possible to change cell Background color?

    I want to change table cell background color.
    Can anyone help me with code example?

    Hi,
    tanusree wrote:
    I want to change table cell background color.
    Can anyone help me with code example?You can find code example in the java tutorial.
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
    exacting
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#renderer
    greetings
    Axel

  • Tutorial for hyperlinking table cell

    Anyone know where i might find a tutorial. Google bringing up
    nothing
    I want to be able to hyperlink table cells and change table
    cell background
    color on mouse over etc.
    I am really struggling with this therefore need a tutorial
    TIA

    Why do you need to hyperlink the *cell*?
    If you put a normal hyperlink in the cell, and use CSS to
    make that <a> tag
    display:block, then it will fill the cell, and make the whole
    thing
    clickable. Further it allows you to use the pseudo-class of
    a:hover to
    change the background color....
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.dreamweavermx-templates.com
    - Template Triage!
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    http://www.macromedia.com/support/search/
    - Macromedia (MM) Technotes
    ==================
    "Andrew" <[email protected]> wrote in message
    news:e7bgvq$eog$[email protected]..
    > Anyone know where i might find a tutorial. Google
    bringing up nothing
    >
    > I want to be able to hyperlink table cells and change
    table cell
    > background color on mouse over etc.
    >
    > I am really struggling with this therefore need a
    tutorial
    >
    > TIA
    >

  • Background to change colour of table cell?

    I have my buttons that change the backgrou color on hover but
    they dont do
    the full table cell only around the text.
    How would i get it to fill the cell?. Ive tried differnt
    padding options
    but non work.
    .buttons a:hover {
    background-color: #CC3333;
    display: block;
    TIA

    Mike wrote:
    > I have my buttons that change the backgrou color on
    hover but they dont do
    > the full table cell only around the text.
    >
    > How would i get it to fill the cell?. Ive tried differnt
    padding options
    > but non work.
    >
    > .buttons a:hover {
    > background-color: #CC3333;
    > display: block;
    >
    Then you have your code set up incorrectly because the css
    that you have
    provided should work.
    Can you provide a link to the page in question or supply the
    full
    code/css of the table in which these links are inserted.

  • Changing Cell Background in Keynote '08 Tables

    Hello,
    I am wondering if it is possible to change an individual cells background color in a presentation. My vision is that if the table is up that I would be able to click and see one single cell change from white to blue lets say. Is this possible?

    I will start by saying that I am using Keynote '09, but this should work the same in '08.
    You can't use any actions to change the color of a chart cell, but there is an easy workaround.
    Make your chart and make sure that you have the cell background set to White. Then duplicate the chart and change the background color of the cells you want changed. Line it up with the first chart and send to the back. Then go the the Action Tab of the inspector (3rd Tab) and create a build out of disappear to the chart with all white background. When you click it will look like you colored the the cell.

  • Custom Table Cell Renderer Unable To Set Horizontal Alignment

    Hello,
    I have a problem that I'm at my wit's end with, and I was hoping for some help.
    I need to render the cells in my table differently (alignment, colors, etc) depending on the row AND the column, not just the column. I've got this working just fine, except for changing the cell's horizontal alignment won't work.
    I have a CustomCellRenderer that extends DefaultTableCellRenderer and overrides the getTableCellRendererComponent() method, setting the foreground/background colors and horizontal alignment of the cell based on the cell's value.
    I have a CustomTable that extends JTable and overrides the getCellRenderer(int row, int column) method to return a private instance of this CustomCellRenderer.
    This works fine for foreground/background colors, but my calls to setHorizontalAlignment() in the getTableCellRendererComponent() seem to have no effect, every cell is always displayed LEFT aligned! It's almost like the cell's alignment is determined by something else than the table.getCellRenderer(row,column).getTableCellRendererComponent() method.
    I've also tried setting the renderer for every existing TableColumn in the TableModel to this custom renderer, as well as overriding the table's getDefaultColumn() method to return this custom renderer as well for any Class parameter, with no success.
    No matter what I've tried, I can customize the cell however I want, EXCEPT for the horizontal alignment!!!
    Any ideas???
    Here's the core custom classes that I'm using:
    class CustomTable extends JTable {
    private CustomRenderer customRenderer = new CustomRenderer();
    public CustomTable() {
    super();
    public TableCellRenderer getCellRenderer(int row, int column) {
    return customRenderer;
    } // end class CustomTable
    class CustomRenderer extends DefaultTableCellRenderer {
    public CustomRenderer() {
    super();
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    if (row % 2 == 0) {
    setForeground(Color.red);
    setHorizontalAlignment(RIGHT);
    } else {
    setForeground(Color.blue);
    setHorizontalAlignment(LEFT);
    return this;
    } // end class CustomRenderer
    Even worse, I've gotten this to work fine in a trivial example I made to try and re-create the problem. But for some reason, this same thing is just not working for horizontal alignment in my actual project?!?
    Anyone have any ideas how the cell's horizontal alignment set in the getTableCellRendererComponent() method is being ignored or overwritten before the cell is being displayed???
    Thanks, any help is appreciated,
    -Alex Blume

    Ok, so I've looked into their source and I think I know where and what the trouble is. The JTable.java has a method called:
    3658> public TableCellRenderer getCellRenderer(int row, int column) {
    3659> TableColumn tableColumn = getColumnModel().getColumn(column);
    3660> TableCellRenderer renderer = tableColumn.getCellRenderer();
    3661> if (renderer == null) {
    3662> renderer = getDefaultRenderer(getColumnClass(column));
    3663> }
    3664> return renderer;
    3665> }
    starting at line 3658 of their source code. It retrieves the TableCellRenderer on line 3660 by calling the tableColumn's getCellRenderer method. This is found in the TableColumn.java class:
    421> public TableCellRenderer getCellRenderer() {
    422> return cellRenderer;
    423> }
    See the problem? Only ONE cell Renderer. It's referring to a variable found at line 140 which is of type TableCellRenderer ... well actually it's created as a DefaultTableCellRenderer at some point since TableCellRenderer is an interface.
    Basically the fix is this:
    In the TableColumn.java file, a collection (Vector, LinkedList, whatever) needs to keep track of each cell's renderer. This will solve the solution. Of course this will be something that you or I can make.
    What's funny is the contradiction in documentation between JTable's and TableColumn's getCellRenderer() method. First, if we look at TableColumn's documentation it states:
    "Returns the TableCellRenderer used by the JTable to draw values for this column."
    Based on that first statement, the getCellRenderer() method in TableColumn is doing its job exactly. No lies, no contradictions in what it does.
    However, that method is called up inside of the JTable's getCellRenderer() method which says a completely different thing which is:
    "Returns an appropriate renderer for the cell specified by this row and column."
    Now we have a problem. For the cell specified. It appears that the rush to push this out blinded some developer who either:
    1) mis-interpreted what the JTable getCellRenderer() method was supposed to do and inadvertently added a feature or;
    2) was in a 2 a.m. blitz, wired on Pepsi and adrenalin and wrote the bug in.
    Either way, I'm really hoping that they'll fix this because it will take care of at least 2 bugs. Btw, anyone interested in posting a subclass to solve this problem (subclass of TableColumn) is more than welcome. I've spent much too much time on this and my project is already behind so I can't really afford any more time on this.
    later,
    a.

Maybe you are looking for

  • Iphone wont pull emails from exchange

    We are running exchange 2010, i have a iphone 3g. The account verifies fine. but when i got to pull emails it doesnt do anything. and if i try to send a email it says it cant comunicate with the server. I set up a 3gs just like i tried to set mine up

  • Build to Flash - won't support video for menu backgrounds?

    I spent hours on a project that includes After Effects motion menu components included as a video background with a loop point. What looks great in preview and on DVD apparently falls a part in Flash. Flash doesn't show the video background in the ma

  • Line is breaking in Spool output - KSB1

    Hi All, I am running the transaction KSB1 which is calling report RKAEP000 to display the output. The output format is fine while displaying it in ALV but in Spool the format is not correct. It is dispaying two line for a single line i.e. line is get

  • Macbook Pro Safari pop up's

    Over the last couple of weeks pop up's have started appearing on every new page I open in Safari, the same happens with Chrome, when I search on Google another page opens with adverts and the google search is pushed down below a series of adverts.  A

  • Is there a purpose for safari extensions?

    is there a purpose for safari extensions? is it okay to have them turned off? What important features do they add to safari?