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

Similar Messages

  • 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

  • How to set fire action event for particular rows in a table

    HI All,
    I have a requirement in which I want to set fire action event for particular rows in a table based on some condition.
    The table has columns like fullname,employee id etc.
    So i want to set fire action event for particulars rows only which will saisfy some condition.

    Atanu,
    Your approach(setting fire action for few rows) seems not possible. Better to go ahead with workaround.
    Do you want this functionality in processRequest(while page loading) or processFromRequest(on some event) method ? Give more explanation regd. your requirement ?
    In either case loop through the rows and when your condition is met write the action to be performed in controller.
    Regards,
    Anand

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

  • 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

  • JTable: Custom cell renderer on T(row, col)

    Sorry if this was posted before, but the whole Search function doesn't seem to work these days (hasn't been working for a week now). Anyways:
    I know how to create custom cell renderers. My problem lies with which cells I want to apply that cell renderer to. It seems I am limited in setting a cell renderer to a whole column, which I don't want.
    For instance, I'd like to apply cell renderer R1 to (0,0) but not to (1,0) and not to (3,0). Instead I want cell renderer R2 on (2,0) and (3,0).
    Example of my table:
    |--icon--|--filename--|--extension--|
    |   R1   |  file1.txt |     txt     |
    |   R2   |  img1.jpg  |     jpg     |
    |   R1   |  file2.txt |     txt     |
    |   R2   |  img2.jpg  |     jpg     |
    |-----------------------------------|Is there any possibility this can be achieved? I am probably overlooking some method or class, but I don't know which. Some pointers or clues in the right directions are appreciated.
    Thanks

    Camickr, again you've been a great help. Works great, but a NullPointerException is being thrown and I can't find out what points to a null object.
    Code is this:
        public TableCellRenderer getCellRenderer(int row, int column) {
            if (getValueAt(row, 3).equals("jpg") && column == 0) {
                return new IconCellRenderer(Klue.iconAdd);
            } else {
                return super.getCellRenderer(row, column);
        }Solution is catching the NullPointerException in this method, but I'd rather have an if statement checking for it. But what to check? Any ideas?

  • Custom Cell Renderer for JList

    I'm getting some strange behaviour from my custom cell renderer.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class TestRenderer implements ListCellRenderer {
      private JPanel jpCell = new JPanel();
      public Component getListCellRendererComponent
          (JList list, Object value, int index, boolean isSelected,
           boolean cellHasFocus) {
        jpCell.add(new JLabel("Render"));
        return jpCell;
    import javax.swing.*;
    import java.awt.*;
    public class TestPanel extends JFrame {
         public TestPanel() {
              JList jlst = new JList(new String[]{"Value", "Value2", "Value3"});
              jlst.setCellRenderer(new TestRenderer());
              JPanel panel = new JPanel();
              panel.add(jlst);
              add(panel);
         public static void main(String[] args) {
              TestPanel frame = new TestPanel();
              frame.setSize(300, 300);
              frame.setLocationRelativeTo(null);
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.setVisible(true);
    }As you will see the renderer displays the string several times in each cell depending on which layout manager I use. However, if I replace the JPanel with a JLabel and set the String as text on the label the String is only printed once per cell. I can't see to find the reason for this.
    Edited by: 811488 on 18-Nov-2010 09:44
    Edited by: 811488 on 18-Nov-2010 09:45
    Edited by: 811488 on 18-Nov-2010 09:45

    So getListCellRendererComponent returns a component whose paintComponent method is called with the Graphics object of the JList Yes, except that the paint(...) method is called. There is a difference. paintComponent() only paints the component. In the case of a JPanel you would get a boring gray colored component. paint() will paint the component and its children and the Border of the component as well. So you get a much more exiting component.
    Read the section from the Swng tutorial on [url http://download.oracle.com/javase/tutorial/uiswing/painting/index.html]Custom Painting for more information.
    So the state of the cell is not the state of the cell Renderer Component meaning the image rendered onto the cell only reflects the state of the Cell Renderer Component at the time the cell was rendered.Yes which is why this method should be efficient because repainting is consistently being done for all the cells. For example every time row selection changes multiple rows need to be repainted. Think of this same concept when you use a JTable which also contains multiple columns for each row.
    That is why you should not be adding/removing components in the rendering code.
    It makes sense except that if this was the case the first version of the Render that I posted should have been rendered first with one "Render" then two then three, shouldn't it?Yes, except that you can't control when or how often the rendering is done. Add the following to the renderer:
    System.out.println(index + " : " + jpCell.getComponentCount());You will see that rendering is done multiple times. The JList tries to determine its preferred width. To do this it loops through all the items in the list and invokes the renderer to get the width of the largest renderer. Well the largest width is the last renderer because 3 labels have been added to the panel. So that width becomes the preferred width of the list. Then the GUI is displayed and the list is painted. Every time the renderer is called an new label is added, but after the 3rd label there is no room to paint the label so it is truncated.
    Change your code to the following:
    //add(panel);
    add(jlst);Now change the width of the frame to see what happens.
    Given all the help you have received, I expect to see many "helpfull answers" selected as well as a "correct answer" (if you want help in the future that is).

  • Setting Non-Editable property for selected Rows in jTable

    Hi,
    I want particular rows to be set non-editable within a jTable. For example. If I have seven rows as follows:
    1
    2 - (Non-editable)
    3
    4
    5 - (Non-editable)
    6
    7
    I want to set non-Editable property to the second & Fifth Rows(say) alone. Other Rows, I may edit.
    How can I do this?
    Thanks in adv.

    TableModel has method
    boolean isCellEditable(int rowIndex,
    int columnIndex)
    so you need to make your table model return false for these rows.

  • Drop Down List in a table - different options for each row

    How can i have a drop down list in a table with different options for each row?
    My requirement is this.. I want to display, say employee dtails in a table, and one column is employee hobbies, whcih can have multiple values and each employee may have a different list of hobbies. So how can we populate the drop down for each row, with different options?

    Hey. Uh, this probably isn't the answer you were looking for, but it sounds like you've got a problem with your database design there. Generally speaking, your tables shouldn't have multi-valued fields, in the relational model anyway (sql). Instead, you should look at adding a separate table like EMPLOYEE_HOBBIES. Then you have a foreign key using the employees primary key as the foreign key in the employee_hobbies table, see what I mean? I might have misunderstood your explanation though, I'm not sure.
    Alternatively, you could just have hobbies as a big freeform varchar field, and don't bother to make people separate their hobbies into different fields (you'd have to abandon the drop-down listbox idea in this case). If there's no really important reason to make the distinction, then it's probably easier just to not do it.

  • Item renderer for specific rows

    I need to have a checkbox item renderer for a spark datagrid column. I am using the following to get an item renderer into column:
    var checkBoxRenderer:ClassFactory = new ClassFactory(GridCheckBoxItemRenderer);
    column.itemRenderer = checkBoxRenderer;
    My question is if I need to show a checkbox for specific rows can I do that without going into GridCheckBoxItemRenderer's source code?
    Thanks

    Hi Zolotoj ,
    Please go through following links :
    http://stackoverflow.com/questions/1952940/show-itemrenderer-in-specific-datagrid-rows-oth ers-empty
    http://www.flexer.info/2009/01/09/different-rows-in-datagrid-programmatically-added-itemre nderers-classfactory-and-ifactory/
    It will provide you some idea to how to proceed further for this problem.
    Thanks and Regards,
    Vibhuti Gosavi | [email protected] | www.infocepts.com

  • Info on cell editors for specific rows

    Hi all,
    Could anyone tell me how to return different components to be the editors for different rows in a table.
    I have certain rows that will use a checkbox editor and certain rows that will use a formatted textfield editor. I have coded an outline to my custom editor which extends Component and implements TableCellEditor. Any help would be greatly appreciated.
    Regards
    Alan

    Override getCellEditor() for the JTable
        public TableCellEditor getCellEditor(int row, int column) {
            if(row==rowOfmyChoice) //Or whatever Logic You want
                      return new MyCellEditor()
            return super.getCellEditor(row,column);
        }

  • Various cell renders for cells (not for columns only) in JTable

    Hello, I need to create a property list with some various values (strings, colors, booleans) just like in Netbeans do. I will use JTable component, but I found I cannot have various cell editors for cells. In JTable cell editors can be only changed for COLUMNS. What sould I do?
    ps - is there any JPropertyPanel avaiable for free on the web?

    I had a similar problem recently whilst working on a Swing GUI designer (you're not doing the same are you? ;o). Presuming you already know how to create TableCellEditors you can use a very simple hack to achieve your goal.
    Either extend the JTable class and override the getCellEditor(int row, int column) method, or override the same method when constructing the JTable (this is what I did). You would need to write something like:
    JTable myTable = new JTable(){
        public TableCellEditor getCellEditor(int row, int column) {
            TableModel model = getModel();
            Object data = model.getValueAt(row, column);
            return getDefaultEditor(data.getClass());
    }The getCellEditor method is called by JTable whenever a cell is to edited, normally it would check to see if the TableColumn has an editor associated with it and return that, if there wasn't one it would get the class of data for the column and return the default editor for that type of class, which is similar to what it does here except it returns the default editor for the class of an individual item of datum.
    Now all you need to do is associate your TableCellEditors with the class types they are to edit with the setDefaultEditor(Class c, TableCellEditor editor) method of JTable. If, for instance, you had an editor for the Color class you would have a line something like:
    myTable.setDefaultEditor(Color.class, new ColorCellEditor());Good luck, and I hope this helps.
    MS.

  • Updating A Table in a for each row trigger

    I have a trigger,
    create or replace trigger ins_ibpm_temp_trig
    after update of ethic_dt on ethics_approval_info for each row
    My issue is that I need to update the ethics_approval_info for each record based on the ethics date that was updated. I am getting the error
    ORA-04091: table ORACLETEST.ETHICS_APPROVAL_INFO is mutating, trigger/function may not see it.
    So the issue here of course is that I am trying to update a table, that is already in the middle of updating. Is there any way to get around this?

    Try these links
    Link1
    Link2
    Regards,
    Abdetu..

  • Skinning Cell Renderer for ComboBox

    How does one change styles for the CellRenderer of a
    ComboBox?
    Flash help gives a nice example on how to skin CellRenderer
    styles for Datagrid and TileList components, but doesn't mention
    anything on how to do the same for a ComboBox.
    The code example for Datagrid and TileList doesn't work for
    ComboBox.

    Hi camickr - I apologize for initiating new threads. Although I am aware that I should reply to follow-up, to me these was a totally different question from the others, although the context was the same.
    I'll be more careful though !
    Thanks for your reply. Actually I got the two (Boolean and Object) renderers working. The problem I am having now is that before I implented the rendering piece, once I clicked on a row, it got highlighted, however now, after implementing these, that doesn't happen anymore. How can I get it to behave as before, where it highlighted a particular row ?
    Here is the code. Thanks again !
        table.setDefaultRenderer(Boolean.class, new TableRenderer());
       table.setDefaultRenderer(Object.class, new TableTextRenderer());
    //cell renderers
    class TableRenderer extends JCheckBox implements TableCellRenderer {
        public Component getTableCellRendererComponent(JTable table,
                                Object value, boolean isSelected,
                                boolean hasFocus, int row, int column ) {
            setSelected(((Boolean)value).booleanValue());
              if( row >= 3){
                setBackground( Color.yellow );
            else setBackground(Color.white);
            return this;
      class TableTextRenderer extends JTextArea implements TableCellRenderer {
          public Component getTableCellRendererComponent(JTable table,
                                  Object value, boolean isSelected,
                                  boolean hasFocus, int row, int column ) {
        JTextArea label = new JTextArea();
        label.setText((String)value);
        label.setBackground(Color.yellow);
                if( row >= 3 && column == 0){
                  setBackground( Color.yellow );
             else label.setBackground(Color.white);
      return label;
      }

Maybe you are looking for

  • HELP!!MacBook Pro and iPhone 5 won't sync via iCloud!

    I've just purchased and set up my first Mac. I have a MacBook Pro, and use and iPhone 5. I've set up iCloud on both in the settings / system preferences to sync contacts, calenders, notes etc... but for the love of trying and following any support I

  • Since the last update my Numbers app in IOS, iPad3 and iphone5 will not open.  It works fine on my macbook pro.  It starts but before I can open a file it closes.

    Since the last update my Numbers app will not load in either my iPad3 or my iPhone5.  It works fine on my MacBook Pro.  The app starts but before I can open a file it closes.  Is this a common problem and do you know hwo to solve it?

  • Accessing iOS launch images

    Good day! I'm working on AIR mobile application for iOS. This is a great feature on iOS which can show the static image before the AIR is initialized. But my app has a really lot of content. When the AIR is initialized user can see the black screen f

  • Deski report-Spacing between sections

    I have developed a deski report with sections and what this does is it creates spaces between two different section blocks.When I save this report as excel and try to apply filter on data it doesn't show all the values since there are empty rows in b

  • Belgian VAT

    Hi everyone,   I am looking into configuring Belgian VAT. There are some standard tax codes in ftxp for BE but our requirement is to have a few more different tax codes with same tax rates but different VAT declaration. Has anyone worked on Belgian V