Cell Render

I've come this for with the cell render but i'm stuck. MY code is
public class JListColorRender extends DefaultListCellRenderer {
     public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
          Component c = super.getListCellRendererComponent(list,value, 2, isSelected,hasFocus());
c.setBackground(Color.RED);
return c;
But the problem is, it makes the whole JList red when I'm trying to get a single value red. What am I doing wrong?

Whats is an SCCEE w/e? If u mean a snippet of my code, here it is:
JListColorRender render;
     public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(redButton)){
render=new JListColorRender();
               list.setCellRenderer(render);
     }//end actionperformed
public class JListColorRender extends DefaultListCellRenderer {
     public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Component c = super.getListCellRendererComponent(list,value, index, isSelected,hasFocus());
          if (value.equals(list.getSelectedValue())) {
               c.setBackground(Color.RED);
               } else {
               c.setBackground(Color.WHITE);
return c;
And thats my code. I want a button clicked and it makes that one cell turn red, in which it does. But when I click another cell, it turns red also, without the button being clicked. Is that enough information? Is that an SCEEE?
One thing I haved tried to do is disable the render object after the action command but that doesn't seem to work either.
Message was edited by:
blackmage

Similar Messages

  • Table cell Render for one cell

    Hi all
    I am hoping that someone can help me with a cell render for one cell only.
    I am needing to make some cells bold.
    What i was hoping is that there is a way of passing in a row and column number to make that cells font bold?
    Any ideas ??
    I am building a List of accounts that I what to look like this.
    1-0000 Asset |Asset|Balance
    1-1000 Cheque Account |Bank|Balance
    1-2000 Credit Cards |Credit|Balance
    1-2020 Visa |Credit Card|Balance
    1-2030 Master Card |Credit Card|Balance

    Create a renderer like you've done in the past:
    http://forum.java.sun.com/thread.jspa?threadID=679718&start=2
    The renderer knows the row and column you are doing the renderering on so you just need to add a conditional check:
    if (aBoldCell)
    setFont( getFont().deriveFont(...) );
    else
    setFont( table.getFont() );

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

  • ComponentView does not redraw component in JTextPane Cell Rend

    We have created a JTable implementation that uses JTextPanes as cell renderers/editors so that text styles and the like are available. We want insert a component, such as a JButton, into the JTextPane. However, the component is only visible when the cell is in an editable state. In the renderer, the ComponentView looks like it has set aside the space where the component is to be, but the component is not visible.
    I have looked at this problem for several days now, and have only determined that this seems to be occuring at a low level. What I have found is that the ButtonUI's update method is not called when the document is in the cell renderer, while it seems called continuously in the cell editor (on each caret blink).
    Does anybody have any insight as to the problem? I have submitted this as a bug to Sun but wanted to find out if anybody else has come across anything similar to this.
    Thank for any help.
    Steve Feveile
    Here is sample code to reproduce the problem:
    // Main Class
    * Main frame for the testing of the component not painting. This simplifies
    * an issue we have come across when trying to set up using a JTextPane as a
    * renderer/editor as the cells in a table.
    * Under these conditions we have found that a component inserted into the JTextPanes document
    * only appears in the editing state of the cell, whereas the rendering state leaves
    * the spacing for the component but does not make it visible.
    * Note that creating a JTextPane with the one of these documents will show the component,
    * even when not editing.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    public class tableFrame extends JFrame
         public tableFrame()
              //set up frame
              getContentPane().setLayout(new BorderLayout());
              setSize(500,300);
              setTitle("Table Missing Component Test");
    addWindowListener(
         new WindowAdapter() {
              public void windowClosing(WindowEvent e) {
                             setVisible(false);                         
                   System.exit(0);     
              //set up components the table
              JTable table = new JTable(createDocumentTableModel(2,2));
              table.setRowHeight(60);
              //set the default renderer/editor to use the JTextPane implementation
              for (int x = 0; x < table.getColumnCount(); x++) {
                   table.setDefaultEditor(table.getColumnClass(x), new TextPaneCellEditor());
                   table.setDefaultRenderer(table.getColumnClass(x), new TextPaneRenderer());
              JScrollPane pane = new JScrollPane(table);
              getContentPane().add(pane, BorderLayout.CENTER);
              //this adds a textpane without the table involved
              //uising the same way of inserting a document
              JTextPane tPane = new JTextPane();
              DefaultStyledDocument doc = new DefaultStyledDocument();
              try
                   doc.insertString(0, "Some text in a JTextPane", null);
                   JButton b = new JButton("Button");
         SimpleAttributeSet inputAttributes = new SimpleAttributeSet();
              StyleConstants.setComponent(inputAttributes, b);
              doc.insertString(0 , " ", inputAttributes);
              catch (Throwable t)
                   System.out.println("createDocumentTableModel error: " + t.getMessage());
              tPane.setDocument(doc);
              tPane.setSize(490, 60);
              JScrollPane pane2 = new JScrollPane(tPane);
              getContentPane().add(pane2, BorderLayout.SOUTH);
         * this creates a table model where the documents are the value
         * in each cell, and the cell renderer/editor can use this instead
         * of a string value
         private TableModel createDocumentTableModel(int row, int col)
              Vector headerData = new Vector();
              Vector tableData = new Vector();
              for (int i=0;i<row;i++)
                   headerData.add("Column" + i);
                   Vector rowData = new Vector();
                   for (int j=0;j<col;j++)
                        DefaultStyledDocument doc = new DefaultStyledDocument();
                        try
                             //this inserts some string to see that this is visible
                             //when editing and rendering
                             doc.insertString(0, ("Row: " + i + ", Column: " + j), null);
                             //this button will only be visible when the cell is in
                             //an editing state
                             JButton b = new JButton("Button" + i + "-" + j);
                   SimpleAttributeSet inputAttributes = new SimpleAttributeSet();
                        StyleConstants.setComponent(inputAttributes, b);
                        doc.insertString(0 , " ", inputAttributes);
                        catch (Throwable t)
                             System.out.println("createDocumentTableModel error: " + t.getMessage());
                        rowData.add(doc);
                   tableData.add(rowData);
              return new DefaultTableModel(tableData, headerData);
         //starts the ball rolling
         static public void main(String args[])
              (new tableFrame()).setVisible(true);
    // Custom Cell Editor
    * Sets the editor to use a JTextPane implementation
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import java.util.EventObject;
    import java.io.Serializable;
    import javax.swing.*;
    import javax.swing.text.*;
    public class TextPaneCellEditor implements TableCellEditor
    /** Event listeners */
    protected EventListenerList listenerList = new EventListenerList();
    transient protected ChangeEvent changeEvent = null;
    protected JTextPane editorComponent;
    protected EditorDelegate delegate;
    protected int clickCountToStart = 1;
         * constructor.
    public TextPaneCellEditor() {
              editorComponent = new JTextPane();
              //use 1 click count to edit a cell
              clickCountToStart = 1;
              * controls the values of the editor
              delegate = new EditorDelegate() {
                   * sets the text value cell.
                   * @param value - value to set in the document
                   public void setValue(Object value) {
                        if (value instanceof Document)
                             editorComponent.setDocument((Document) value);
                        else
                             editorComponent.setText("");
                   * gets the text value cell.
                   * @return the document in the textpane
                   public Object getCellEditorValue() {
                        return editorComponent.getDocument();
         // implements the setting the value for the editor
         public Component getTableCellEditorComponent(JTable table, Object value,
                   boolean isSelected, int row, int column) {
              if (value != null)          
                   delegate.setValue(value);
              else
                   delegate.setValue("");
              return editorComponent;
    // Implementing the CellEditor Interface
         // implements javax.swing.CellEditor
         public Object getCellEditorValue() {
              return delegate.getCellEditorValue();
         // implements javax.swing.CellEditor
         public boolean isCellEditable(EventObject anEvent) {
              if (anEvent instanceof MouseEvent) {
                   return ((MouseEvent)anEvent).getClickCount() >= clickCountToStart;
              return true;
    // implements javax.swing.CellEditor
         public boolean shouldSelectCell(EventObject anEvent) {
              return delegate.shouldSelectCell(anEvent);
         // implements javax.swing.CellEditor
         public boolean stopCellEditing() {
              fireEditingStopped();
              return true;
         // implements javax.swing.CellEditor
         public void cancelCellEditing() {
              fireEditingCanceled();
    // Handle the event listener bookkeeping
         // implements javax.swing.CellEditor
         public void addCellEditorListener(CellEditorListener l) {
              listenerList.add(CellEditorListener.class, l);
         // implements javax.swing.CellEditor
         public void removeCellEditorListener(CellEditorListener l) {
              listenerList.remove(CellEditorListener.class, l);
         * Notify all listeners that have registered interest for
         * notification on this event type. The event instance
         * is lazily created using the parameters passed into
         * the fire method.
         * @see EventListenerList
         protected void fireEditingStopped() {
              // Guaranteed to return a non-null array
              Object[] listeners = listenerList.getListenerList();
              // Process the listeners last to first, notifying
              // those that are interested in this event
              for (int i = listeners.length-2; i>=0; i-=2) {
                   if (listeners==CellEditorListener.class) {
                        // Lazily create the event:
                        if (changeEvent == null)
                             changeEvent = new ChangeEvent(this);
                        ((CellEditorListener)listeners[i+1]).editingStopped(changeEvent);
         * Notify all listeners that have registered interest for
         * notification on this event type. The event instance
         * is lazily created using the parameters passed into
         * the fire method.
         * @see EventListenerList
         protected void fireEditingCanceled() {
              // Guaranteed to return a non-null array
              Object[] listeners = listenerList.getListenerList();
              // Process the listeners last to first, notifying
              // those that are interested in this event
              for (int i = listeners.length-2; i>=0; i-=2) {
                   if (listeners[i]==CellEditorListener.class) {
                        // Lazily create the event:
                        if (changeEvent == null)
                             changeEvent = new ChangeEvent(this);
                        ((CellEditorListener)listeners[i+1]).editingCanceled(changeEvent);
    // Protected EditorDelegate class
    protected class EditorDelegate implements ActionListener, ItemListener, Serializable {
              //made up of unimplemented methods
              protected Object value;
              public Object getCellEditorValue() {
                   return null;
              public void setValue(Object x) {}
              public void setDocument(Object x) {}
              public Document getDocument() {
                   return null;
              public boolean isCellEditable(EventObject anEvent) {
                   return true;
              /** Unfortunately, restrictions on API changes force us to
              * declare this method package private.
              boolean shouldSelectCell(EventObject anEvent) {
                   return true;
              public boolean startCellEditing(EventObject anEvent) {
                   return true;
              public boolean stopCellEditing() {
                   return true;
                   public void cancelCellEditing() {
              public void actionPerformed(ActionEvent e) {
                   fireEditingStopped();
              public void itemStateChanged(ItemEvent e) {
                   fireEditingStopped();
    // Custom Cell Renderer
    * renders a table cell as a JTextPane.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    public class TextPaneRenderer extends JTextPane implements TableCellRenderer                                                  
         * Constructor - just set to noneditable
         public TextPaneRenderer() {
              setEditable(false);
         * implementation of table cell renderer. If the value is a document
         * the, the text panes setDocument is used, otherwise a string value
         * is set
         public Component getTableCellRendererComponent(JTable table, Object value,
                   boolean isSelected, boolean hasFocus, int row, int column) {
              if (value != null)
                   if (value instanceof Document)
                        //set the value to a document
                        setDocument((Document) value);
                   else
                        //convert the value to a string
                        setText(value.toString());
              else
                   //set text to an empty string
                   setText("");
              return this;

    Hi, I came across the forum and found your problem is very similar to what I am having now. Your post has been a year old, I just wonder if you come up anything productive to what you had? Could you let us know what you (or Sun) find out if you do have one? Thanks.

  • I need to change tree cell render on particular node when it is selected.

    actually the treecell change its icon when it is selected. yhe other cell doesnot changed its icon

    Write your own renderer or extends DefaultTreeCellRenderer. Add something like this to the method
    Component getTreeCellRendererComponent(JTree tree,
                                           Object value,
                                           boolean selected,
                                           boolean expanded,
                                           boolean leaf,
                                           int row,
                                           boolean hasFocus)
        if (selected)
           set the icon to be special icon
        else
           set the icon back to normal
    }

  • JTable cell Render on the last row column one help please

    Hi All
    I am hoping that someone will be able to help me with this....
    I want to render the last row and column one of the table with this render
    thanks for any help
    Craig
        public class MyRenderer2 extends DefaultTableCellRenderer {
            public Component getTableCellRendererComponent(JTable table,
                    Object value,
                    boolean isSelected, boolean hasFocus,
                    int row, int column) {
                ImageIcon icon = new ImageIcon(image_pics.SMALL_BLUE);
                setIcon(icon);
                return this;
        }

    it still renders every row
    any Ideas ??
    I just want the last row column 0 to be rendered
    I a call a method set table
    then I call for the data
    //TableModel
        public void setClientTableModel() {
            clientModel = new DefaultTableModel(coloumHeaderObject, 0) {
                public boolean isCellEditable(int row, int column) {
                    return false;
            TableSorter sorter = new TableSorter(clientModel); //ADDED THIS
            sorter.setTableHeader(phoneList.getTableHeader()); //ADDED THIS
            phoneList.setModel(sorter);
           // phoneList.setTableHeader(null);
            setTable();
            revalidate();
        public void setTable() {
          // phoneList.getColumnModel().getColumn(0).setCellRenderer(new MyRenderer());
            phoneList.getColumnModel().getColumn(1).setCellRenderer(new MyRenderer1());
            phoneList.getColumnModel().getColumn(4).setCellRenderer(new MyRenderer2());
            phoneList.getColumnModel().getColumn(0).setMinWidth(20);
            phoneList.getColumnModel().getColumn(0).setMaxWidth(20);
            phoneList.getColumnModel().getColumn(0).setPreferredWidth(20);
            phoneList.getColumnModel().getColumn(1).setMinWidth(20);
            phoneList.getColumnModel().getColumn(1).setMaxWidth(20);
            phoneList.getColumnModel().getColumn(1).setPreferredWidth(20);
            phoneList.getColumnModel().getColumn(2).setMinWidth(80);
            phoneList.getColumnModel().getColumn(2).setMaxWidth(80);
            phoneList.getColumnModel().getColumn(2).setPreferredWidth(80);
            phoneList.getColumnModel().getColumn(3).setMinWidth(150);
            phoneList.getColumnModel().getColumn(3).setMaxWidth(150);
            phoneList.getColumnModel().getColumn(3).setPreferredWidth(150);
            phoneList.getColumnModel().getColumn(4).setMinWidth(20);
            phoneList.getColumnModel().getColumn(4).setMaxWidth(20);
            phoneList.getColumnModel().getColumn(4).setPreferredWidth(20);
            phoneList.setOpaque(false);
            phoneList.setGridColor(Color.lightGray);
            phoneList.setRowHeight(18);
            phoneList.setShowVerticalLines(false);
            phoneList.setIntercellSpacing(new Dimension(0, 0));
            phoneList.setFont(new java.awt.Font("Lucida Grande", 0, 11));
            phoneList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            if (ALLOW_COLUMN_SELECTION) { // false by default
                if (ALLOW_ROW_SELECTION) {
                    phoneList.setCellSelectionEnabled(true);
                phoneList.setColumnSelectionAllowed(true);
                ListSelectionModel colSM = phoneList.getColumnModel().getSelectionModel();
                colSM.addListSelectionListener(new ListSelectionListener() {
                    public void valueChanged(ListSelectionEvent e) {
                        if (e.getValueIsAdjusting())return;
                        ListSelectionModel lsm = (ListSelectionModel) e.getSource();
                        int row = phoneList.getSelectedRow(), col = 3;
                        int rowID = phoneList.getSelectedRow(), colID = 5;
                        if (lsm.isSelectionEmpty()) {
                        } else {
                            int selectedCol = lsm.getMinSelectionIndex();
                            if (selectedCol == 4) {
                                phoneNumber = (String) phoneList.getValueAt(row, col).toString();
                                main.setPhoneNumber(phoneNumber);
                                main.openLargePhone();
                                lsm.clearSelection();
                            if (selectedCol == 5) {
                                ID = (String) phoneList.getValueAt(row, col).toString();
                             //   main.setID(ID);
                              //  main.deleteContact();
                                lsm.clearSelection();
    //set table data
        public void setTest() {
            setClientTableModel();
            Object[] data = {" ", " ", "Work", "03 9841-8247", " "};
            clientModel.addRow(data);
            Object[] data1 = {" ", " ", "Fax", "03 9842-0360", " "};
            clientModel.addRow(data1);
            phoneList.getColumnModel().getColumn(0).setCellRenderer(new MyRenderer());
        }

  • JTable cell render

    Hello,
    I have a JTable that have a column with a custom cell renderer ( for example a JTextField or a JPanel)
    class ConfigCellRenderer extends JPanel implements TableCellRenderer
         ArrayList modifiedProperties;
         public ConfigCellRenderer (String[][] defaultsDataModel,ConfigurationPanel parent,ArrayList modifiedProperties)
              this.modifiedProperties = modifiedProperties;
         JPanel panel = new JPanel();
         JLabel label = new JLabel();
         public Component getTableCellRendererComponent(JTable table, Object value,
                   boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex)
              label.setText(value.toString());
              panel.add(label);
              if(modifiedProperties.contains((String)value)
                   panel.setBackground(Color.RED);
         return panel;
    }The problem is that all row's panels are marked red instead of the one that meats criteria.
    Is there a way to change color only for the row I'm interested in?
    Thanks and best regards,
    johnny
    Edited by: smeag0l on Jul 27, 2008 11:50 PM

    if(modifiedProperties.contains((String)value) {
         panel.setBackground(Color.RED);
    } else {
         panel.setBackground(Color.white);
    }Since the component is used as a rubber stamp for all the fields, once you set a property it remains and is used for all the other cells until reset
    ICE

  • Jtabe + cell render

    HI ,
    I have one JTable, it cells are rendered one. Each cell contains one Japnel, which include two text fields... When I click on a second textfield in a particular cell, the focus going to the first text field. Formore test, I added one Jcombo before the text field. And now focus is going to JCombo.. ie the focus going to the first focusable component in a particular cell.....
    Why this happens , any Idea ?

    I don't see how this applies to renderers, as renderers are nothing more then glorified screen shots of a component painted into a cell.
    You mean editors? Well, why shouldn't the focus go to the first focusable component in the cell? How should it know what you want focused?

  • Cell render in data grid

    Lets say you have two columns one that renders as an image
    the other text. Why is it that the image gets distorted when there
    is more text. Is there anyway to fix this?

    "realtime158" <[email protected]> wrote in
    message
    news:g6b692$ksh$[email protected]..
    > Lets say you have two columns one that renders as an
    image the other text.
    > Why is it that the image gets distorted when there is
    more text. Is there
    > anyway to fix this?
    Try setting maintainAspectRatio to true on the image control.
    HTH;
    Amy

  • JComboBox Cell Render selection problem

    .......It only changes the color of the triangle for the drop down. It does not change the color of what is selected. There is just a gray selection background
    <code>
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.plaf.basic.*;
    public class ComboBoxColor extends JFrame
         public ComboBoxColor()
              Object[] items = { Color.red, Color.green, Color.blue };
              JComboBox comboBox = new JComboBox( items );
              comboBox.setRenderer( new ColorRenderer( comboBox) );
              getContentPane().add( comboBox, BorderLayout.NORTH );
         public static void main(String[] args)
              ComboBoxColor frame = new ComboBoxColor();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );
         class ColorRenderer extends BasicComboBoxRenderer
              JComboBox comboBox;
              Border border;
              public ColorRenderer(JComboBox comboBox)
                   this.comboBox = comboBox;
                   border = new LineBorder( Color.WHITE );
    //setOpaque(true);
              public Component getListCellRendererComponent(
                   JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
                   super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                   setText("");
                   setBackground( (Color)value );
                   if (isSelected)
                        setBorder( border );
                   else
                        setBorder( null );
                   if (index == -1)
                        System.out.println((Color)value);
    comboBox.setBackground((Color)value);
    if((Color)value==Color.RED){
    System.out.println("REd");
    comboBox.setBackground(Color.RED);
    else if((Color)value==Color.GREEN){
    System.out.println("Green");
    comboBox.setBackground(Color.GREEN);
    else{
    System.out.println("Blue");
    comboBox.setBackground(Color.BLUE);
                   return this;
    </code>

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.plaf.basic.*;
    public class ComboBoxColor extends JFrame
         public ComboBoxColor()
              Object[] items = { Color.red, Color.green, Color.blue };
              JComboBox comboBox = new JComboBox( items );
              comboBox.setRenderer( new ColorRenderer( comboBox) );
              getContentPane().add( comboBox, BorderLayout.NORTH );
         public static void main(String[] args)
              ComboBoxColor frame = new ComboBoxColor();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );
         class ColorRenderer extends BasicComboBoxRenderer
              JComboBox comboBox;
              Border border;
              public ColorRenderer(JComboBox comboBox)
                   this.comboBox = comboBox;
                   border = new LineBorder( Color.WHITE );
                            //setOpaque(true);
              public Component getListCellRendererComponent(
                   JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
                   super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                   setText("");
                   setBackground( (Color)value );
                   if (isSelected)
                        setBorder( border );
                   else
                        setBorder( null );
                   if (index == -1)
                        System.out.println((Color)value);
                                    comboBox.setBackground((Color)value);
                                    if((Color)value==Color.RED){
                                        System.out.println("REd");
                                        comboBox.setBackground(Color.RED);
                                    else if((Color)value==Color.GREEN){
                                        System.out.println("Green");
                                        comboBox.setBackground(Color.GREEN);
                                    else{
                                        System.out.println("Blue");
                                        comboBox.setBackground(Color.BLUE);
                   return this;
    }

  • Multiple Line cell render in  JTable

    The issue here is that what's the right way to judge
    how many lines is needed to show the Object value in TableCellRender's
    public Component getTableCellRendererComponent(
    JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus,
    int row,
    int column)
    The way by FontMetrics or by Component's getPreferredSize() is not correct.
    For a short Object value = "FAC Question" for which the table column is wide enough to display whole string,
    the width by calculating FontMetrice on this Object could be larger than the width of table column.
    For example:
    Object value = "FAC Question A";
    tableColumn.getPreferredSize().width = 75;
    fontMetrics.stringWidth(value)=120;
    getTableCellRenderComponent(...).getPreferredSize().width=120

    Hi, use
    JTable table = new JTable();
    DefaultListSelectionModel  dlm =  new DefaultListSelectionModel();
    dlm.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION  ); //1( the first one should be the one you are looking for)
    or (choose 1 or 2, the rest stays the same)
    dlm.setSelectionMode( ListSelectionModel.SINGLE_INTERVAL_SELECTION );//2
    table.getColumnModel().setSelectionModel(dlm);
    table.setCellSelectionEnabled(true);Hope this helps.
    Greetings Michael.

  • Custom table cell renderer in a JTable is not called

    Hello, all,
    I have the following task: I need to select several cells in a column, change the value of those cells, and once the value changes, the color of these cells should change as well. I wrote a custom cell renderer, and registered it for the object type that will use it to render the cell. However, the custom cell renderer is never called. Instead, the class name of the object is displayed in the cell.
    My code snippents are as follows:
    //Declare the table and add custom cell renderer
    JTable table = new JTable (7,7);
    table.setCellSelectionEnabled (true);
    table.setSelectionMode (ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    //Add the custom cell renderer to render objects of type Item
    table.setDefaultRenderer(Item.class, new CustomTableCellRenderer());
    //Get the selected cells and change the object type in those cells
    //This part works, since I see the app entering the for loop in the debugger, and the item.toString() value is displayed in each selected cell
    int rowIndexStart = table.getSelectedRow();
    int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
    int colIndex = table.getSelectedColumn();
    Item item = new Item ();
    for (int i = rowIndexStart; i<=rowIndexEnd; i++){
                  table.setValueAt(item, i, colIndex);
                 //I expect the cell to redraw now using custom cell renderer defined below, but that cell render is never called.  Instead, the item.toString() value is displayed in the cell.   What is wrong?
    //Definition of custom cell renderer. 
    //the getTableCellRendererComponent is never called, since the System.out.println never prints.  I expected this method to be called as soon as the Item object is added to the cell.  Am I wrong in expecting that?
    class CustomTableCellRenderer extends DefaultTableCellRenderer  {
        public Component getTableCellRendererComponent (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            Component cell = super.getTableCellRendererComponent (table, value, isSelected, hasFocus, row, column);
            System.out.println("value: "+value.getClass()+" isSelected "+isSelected+" hasFocus "+hasFocus+" row "+row+" col "+column);
            if (this.isFocusOwner()) {
            cell.setBackground( Color.red );
            cell.setForeground( Color.white );
            return cell;
    } Please, help,
    Thank you!
    Elana

    The suggestion given above assumes that all the data in a given column is of the same type.
    If you have different types of data in different rows the you should be overriding the getCellRenderer(...) method. Something like:
    public TableCellRenderer getCellRenderer(int row, int column)
        Object o = getValueAt(row, column);
        if (o instanceof Item)
            return yourCustomRenderer
        else
            return super.getCellRenderer(row, column);
    }

  • "interactive" cell renderer

    I have an application that pulls and displays data from a database in the form of a table. The user can then use/manipulate that data. Each row of data has 5 different states. I want to either change the font or row color in the display table using a different color or set of font characteristics for each state. The state of a given row of data may or may not involve actually changing any values within the row. I use a HashMap as a row state map to track the state of a given row of data. How can I effect the row color or font changes as the row state changes on a table that is already visible to the user? I was able to get the visual effect I am looking for, but had to use an in-line definition for a custom cell renderer in order for the cell render to see the changes in the row state map, as I couldn't find a way to reach a method in the cell renderer to load a state map once the renderer was attached to the table as the default cell renderer. Unfortunately, site software development policy prohibits me from using in-line class definitions or global data (such as using a Singleton class to hold the row state map). Any suggestions?

    hmsdefender wrote:
    I was able to get the visual effect I am looking for, but had to use an in-line definition for a custom cell renderer in order for the cell render to see the changes in the row state map, as I couldn't find a way to reach a method in the cell renderer to load a state map once the renderer was attached to the table as the default cell renderer.As for your inline definition, just create a standalone/toplevel cell renderer that has a reference to your row state map. Where you now have the inline definition, create a new instance of that renderer and pass in the row state map (e.g. as a ctor argument).
    Alternatively, make the row state part of your TableModel and have the renderer access the data via JTable's getModel method.
    As for seeing chances in the row state map, it will not be enough for the renderer to see those, because the renderer cannot repaint a table cell of its own accord. Whenever something changes in the row state map, you need to trigger a repaint for the JTable.

  • Table cell with 2 colors

    Hi Guys,
    I have a JTable which I need its cells to have 2 colors (indicating different type of data for the same cell). I could not find a way to do this. Anyone can help me out here?
    Thanks in advance
    Eman

    PhHein wrote:
    eman_c wrote:
    Hi,
    I already checked that page, and as far as i understood (and please correct me if I am wrong) the renderer lets you control one cell (which is great) but one cell can be applied with one ForGround color. What I needed is that in the same cell, part of the data is colored red for example and the other in green. If it is indeed possible using cell render, could you please explain how?
    Thanks again
    EmanSorry, I don't think it is possible at all to have different background colors in one cell. But you could however set different text colors in the same cell by using html.Err...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.*;
    import java.util.regex.*;
    import java.text.*;
    public class ShadeCellDependingOnValue extends JPanel
        static final Object[][] tableData =
            {1, new Double(10.0)},
            {2, new Double(20.0)},
            {3, new Double(50.0)},
            {4, new Double(10.0)},
            {5, new Double(95.0)},
            {6, new Double(60.0)},
        static final Object[] headers =
            "One",
            "Two",
        public ShadeCellDependingOnValue() throws Exception
            super(new BorderLayout());
            final DefaultTableModel model = new DefaultTableModel(tableData, headers);
            final JTable table = new JTable(model);
            table.getColumnModel().getColumn(1).setCellRenderer( new LocalCellRenderer(120.0));
            add(table);
            add(table.getTableHeader(), BorderLayout.NORTH);
        public class LocalCellRenderer extends DefaultTableCellRenderer
            private double v = 0.0;
            private double maxV;
            private final JPanel renderer = new JPanel(new GridLayout(1,0))
                public void paintComponent(Graphics g)
                    super.paintComponent(g);
                    g.setColor(Color.CYAN);
                    int w = (int)(getWidth() * v / maxV + 0.5);
                    int h = getHeight();
                    g.fillRect(0, 0, w, h);
                    g.drawRect(0, 0, w, h);
            private LocalCellRenderer(double maxV)
                this.maxV = maxV;
                renderer.add(this);
                renderer.setOpaque(true);
                renderer.setBackground(Color.YELLOW);
                renderer.setBorder(null);
                setOpaque(false);
                setHorizontalAlignment(JLabel.CENTER);
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)
                super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
                if (value instanceof Double)
                    v = ((Double)value).doubleValue();
                return renderer;
        public static void main(String[] args) throws Exception
            final JFrame frame = new JFrame("Fred120");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(new ShadeCellDependingOnValue());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    }

  • JTable edited cells, in bold text

    Hi
    I'm using a JTable to edit some data. And just wondering if I can realze the data edited. Putting some text bold, or whatever in the render.
    Is it posible to get the component of just a cell and set up some properties?
    Thanks in advance.

    JLabel can handle some html markup, for example:
    JLabel l = new JLabel();
    l.setText("<html><i>italics</i> <b>bold</b> <u>underline</u></html>");The default cell render is derived from JLabel, so you can:
    1. Contrive to have your data object's toString methods produce such html
    2. or subclass DefaultTableCellRenderer and override setValue.
    3 etc...

Maybe you are looking for

  • Configuration of Public Key Authentication Policy for SFTP on OAG 11.1.2.2

    Hi I'm working on the configuration of an SFTP server over OAG, using both password and public key authentication. This particular listener need 3 policies: - Password Authentication - Public Key Authentication - File upload Both File upload and pass

  • What Is Better?

    Two quick questions... 1. Are scene's the only way to make pages in the flash IOS development? 2. whats better touch events or mouse events? thank you for looking and possible responding 

  • Effective start and end dates for a compensation workbench plan

    Hi all, We are having a requirement where we want to get the data respective to current plan for reporting purposes. What i have noticed is there is no such thing as effective_start_date and effective_end_date directly in all the cwb tables. The diff

  • Problem after updating iPhone 3G to iOS 4

    I have an iPhone 3G. I updated it with the iOS 4 software from iTunes. It backed-up all my information and then restored my phone. Everything was fine, but now I frequently see a keypad the with the message "Voice mail password incorrect." If anyone

  • Invoke- Receive - Time delay

    Hello All, I have two Async processes, Process A and Process B. Process A invokes process B and waits for response from Process B. Process A gets the response back from process B when process B invokes process A, however there is a 10 sec time delay