Setting a cell renderer for a Cell?

Hi everybody,
I'm sitting here with a problem: I'm trying to set a Cell renderer for a cell.
The problem is in all of the examples that i saw till now this was made only with columns.
Is it possible to set different CellRenderer foor different cells in the same column?

Hi,
if you implement your cellRenderer you return the Object you get for all columns but the one you want to be handled im a special way. As you know the row as well you can return sth different for each row.
Phil

Similar Messages

  • Setting a renderer for an entire table by default

    Is there a way to set another renderer for an entire table, a renderer that extends DefaultTableCellRenderer in particular. I mean I can think of a workaround where I basically go through each column of the JTable and set the default renderer for each column, but that seems like a hack. Shouldn't there be away to set it across the board?
    I don't see a Jtable.setCellRenderer(), I see ways of setting the renderer by Object type, or by column, but what about across the board?

    table.setDefaultRenderer(Object.class, someRenderer);

  • Custom Cell Renderer for JTable

    Help, I'm trying to write a custom renderer for a column of my JTable but can't get it to work.
    Want I want is a cell in that column to be a label with an Icon and text.
    Trying to test with something simple, just changing colors but even that doesn't work. Can anyone see where I've gone wrong.
    table = new JTable(tableModel);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setShowGrid(false);
    TableColumn tc = table.getColumnModel().getColumn(0);
    tc.setCellRenderer(new DefaultTableCellRenderer() {
       public Component getTableCellRendererComponent(JTable table,
                                                   Object value,
                                                   boolean isSelected,
                                                   boolean hasFocus,
                                                   int row,
                                                   int column)
             JLabel label = (JLabel)
                super.getTableCellRendererComponent
                   (table, value, isSelected, hasFocus, row, column);
                label.setForeground(Color.red);
                label.setBackground(Color.black);
                System.out.println("Object: "+ value);
                return label;
    });Thanks,
    Derek

    Hi
    For colors try :
    all your code
    but where you call super.getTableCellRendererComponent(......
    do only setText(value.toString());
    I supose it is Ok just for changing the colors. If you want render
    an Icon plus some text you can put at your model a JLabel and at this
    render do
    setText((JLabel)value.getText());
    setIcon((JLabel)value.getIcon());
    inside a try/catch clause becasue you can put other kind of object at
    model level
    Or pass instances of an special Class with Icon/Text with publics members set/get to acces to text/icon.
    Hope this help

  • A different cell renderer for the root node ??

    Is it possible to use one cell renderer for the root and a different cell renderer for the other nodes ?
    Thanks.

    Well I tried that and it didn't work.I do it without any problems so what how did you do it?
    Hint - in the renderer compare tree.getModel().getRoot() with the value using == .
    >
    Basically I have a checkbox at each node. So, I tried
    setting the checkbox invisible for the root. Hard work! Since you are just wanting to change the rendering rule for the root you should change the renderer.
    >
    But then all the nodes have an invisible
    checkbox.............................

  • JTree: How to set different cell editor for different tree Nodes.

    I have a JTree and I want to set different cell editors for different node depending on some condition. E.g. I want to set ComboBox as editor for leaf node but each leaf node will have its own set of data.
    Any help or pointer?
    Thanks in advance
    Sachin

    take there:
    http://www.mutualinstrument.com/Easy/FAQ/Tree/tree.html

  • 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

  • How to set a cell editable at runtime for jtable

    Hi evry body
    i need to set a cell as editable during runtime and set some value for the cell and make it non editable after setting value
    how can i do it? urgent help appreciated
    regards
    anil

    You could override the methods isCellEditable(...) and setValueAt(...) in your JTable's TableModel to get the effect desired
    // Assuming that each element of the array will be false initially
    boolean[][] valueSet = new boolean[noRows][noCols];
    public boolean isCellEditable(int row, int col) {
      return !valueSet[row][col];
    public void setValueAt(Object obj, int row, int col) {
      super.setValueAt(obj, row, col);
      valueSet[row][col] = true;
    }

  • JTree as cell renderer for JList

    I have an application that requires to display a list of tree-structured data.
    So I've used JTree a the cell renderer for the JList, and I can see a list of trees with that data in.
    However, the Jtree doesn't respond to Mouse messages, even if I dispatch the to it manually. So the tree is essentially dead.
    Does anybody know how to fix this?

    I'm not sure if they have the same thing for lists though.Yes, it is so - a cellrenderer or celleditor is a component, that is only there during it is used - a cellrenderer is there as long as it needs to paint the contents, a celleditor is there, if an edit-process is invoked and it will get messages as long as the editing process continues - after finishing editing, the component is no longer there - normally the renderer is called after that, to render the new contents into the rectangle of that cell, because the contents in its non-editing state may look other than that from the editor during the editing-state.
    greetings Marsian

  • How do I set a BG Image for a specific Table Cell?

    Hello...
    How do I set a Background Image for a specific table cell
    without it affecting the main page background image?
    thanks
    J

    Use CSS -
    td.special { background-image:url(foo.gif); }
    will style this table cell only -
    <td class="special">
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    ==================
    "JSloanSDRE" <[email protected]> wrote in
    message
    news:g2dl7n$pf5$[email protected]..
    > Hello...
    >
    > How do I set a Background Image for a specific table
    cell without it
    > affecting the main page background image?
    >
    > thanks
    > J

  • 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.

  • 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

  • Setting a renderer for an element dynamically at runtime

    Currently i am searching for a UI feature : Generating a HTML table by setting the renderer for each cell dynamically at runtime. E.g. depending on some state dependency(e.g. authorization issue) i want to render information in a cell in one case as a hyperlink or a in the other case as a informational text (instead of the hyperlink).
    My question : is that feature in JSF Framework implemented or adaptable? Viewing some JSP/JSF code, the definition of the renderer seems to me to be determined at compile time, and there is no example how to do as described above.
    Any hint appreciated, Joerg

    I agree with keyurva proposal. This rendererType is dynamically set based on the state.
    2nd is if all the cell are the same component type, you even can extends the component to override the getRendererType() method making to returne a different value based on the state.

  • Iam using a table in numbers to plot daily graph lines. If I fill a cell with a text box  at say zero it plots the graph. I can't actually set the cell value until the actual day but the graph plots it at zero when I don't want it to plot anything. Is tho

    I am using a table in Numbers to plot daily graph lines. Mood swings of how I am on the day, i"m a depressive.
    If I fill a cell with a step box at say zero it plots the graph. I can't actually set the cell value until the actual day but the graph plots it at zero when I don't want it to plot anything. Is there a work around. so thatbgraph only plots on the day?

    The answer is (sort of) in your subject, but edited out of the problem statement in the body of your message.
    When you use a stepper or a slider, the value in the cell is always numeric, and is always placed on the chart if that cell is included in the range graphed by the chart.
    But if you use a pop-up menu cell, you can specify numeric or text values in the list of choices for in the menu. Numeric values will be shown on the chart. Text values will not.
    For the example, the values list for the pop-up menu was:
    5
    3
    1
    Choose
    -1
    -3
    -5
    The first pop-up was set to display Choose, then the cell was filled down the rest of the column. Any text value (including a single space, if you want the cell to appear blank) may be used instead of Choose.
    For charts with negative Y values, the X axis will not automatically appear at Y=0. If your value set will include negative values, I would suggest setting the Y axis maximum and minimum to the maximum and minimum values on your menu list, rather than letting Numbers decide what range to include on the chart. Place a line shape across the chart at the zero level, and choose to NOT show the X axis.
    Regards,
    Barry

  • How do I remove a selected set of cells?

    How do I remove or delete a selected set of cells (ex. rectangle of C1 to E26).
    In Excel, I can delete such a group of cells and all the data to the right of those cells shifts over.
    Is this possible in Numbers or should I just go back to Excel?

    Michael Force wrote:
    Thank you for your attempt to help. This does not work for me, perhaps because I failed to fully understand what Yvan is trying to say. You are saying I need to delete cells at the bottom of the column,
    It's not what I wrote.
    Assuming that you want to remove cells C12 thru C14, I asked you to select cells C15 thru C9999999 then move the selected block to cell C12.
    Old cell C15 will become cell C12
    Old cell C16 will become cell C13
    Old cell C17 will become cell C14
    Your problem is different than the original one which was:
    I want to delete a range of cells in a single column, say for instance 3 cells, and have the entire column shift up 3 cells.
    and I'm not sure that the "Delete cells" function of Excel will do the trick.
    I assumes (because you didn't give the complete info) that you want to remove cells C12 thru C14.
    Select cells C15 thru C40, move the block to C12.
    Old cell C15 will become cell C12
    Old cell C16 will become cell C13
    Old cell C17 will become cell C14
    Old cell 40 will become cell C37
    cells C38, C39, C40 will be empty.
    Yvan KOENIG (from FRANCE lundi 17 novembre 2008 11:59:29)

  • How to set the cell size in a JFrame

    Hello. Is there any way of setting the cell size in a JFrame. The reason why I want to set the cell size is that I want to be sure of their location that when I am placing components on the JFrame. So is there any way of setting the cell size beforehand. Also for the following code.
    JFrame frame = new JFrame("Window");
    frame.setSize(100,100);is the size 100 by 100 is he size of the cell?

    smithbrian wrote:
    When I am placing a component on the grid I want to be sure the component is exactly where I place it. In order to do that I would need to know what is the size of the gird and how to change the size of the gird in the JFrame.What grid?? You're assuming that we know much more about your program than we actually do. We actually know zip. Please read this help site which will help you to avoid similar errors in posting questions here. It has helped me in the past: [smart questions|http://www.catb.org/~esr/faqs/smart-questions.html]

Maybe you are looking for

  • Guest Anchor with web auth using ISE guest portal

    Hello All, Before launching into my exact issues, could anyone confirm if they have completed a wireless Guest anchor setup using 2504 controllers on 7.4 as the anchor (5508 is the foreign) with webauth external redirection at ISE 1.1.3 using ISE Gue

  • Vendor Address DTW

    Hi All when i am uploading Vendor with addresses it make an extra address line named liked 'BillTo'. anyone have any idea about this? Regards Shiv

  • Bill Notifications

    bill

  • How to manually start telnetd service With Solaris 8

    "ps -ef | grep telnetd", shows telnetd daemon is not running (though telnetd is listed and uncommented in /etc/inetd.conf). Checked /etc/services and /etc/hosts, but found no abnormality. How do I manually start up telentd service? Why telnetd failed

  • FCP7 Video Export Glitch

    I keep getting glitches in the video when I export.  After much head scratching, I find that the glitches exist in the original camera masters, although they're not visible when played in FCP.  Is there any way for the export to match what I see in F