DateFormat as Cell Renderer

I am trying to use a DateFormat object as a Rederer for a table column.
This is the Code I'm using:
DateFormat df2 = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM); //defines a date format.
list = new javax.swing.JTable();
TableColumn col = list.getColumnModel().getColumn(0);
    col.setCellRenderer(new MyTableCellRenderer());
public class MyTableCellRenderer extends JLabel implements TableCellRenderer {
        // This method is called each time a cell in a column
        // using this renderer needs to be rendered.
        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
            // 'value' is value contained in the cell located at
            // (rowIndex, vColIndex)
            if (isSelected) {
                // cell (and perhaps other cells) are selected
            if (hasFocus) {
                // this cell is the anchor and the table has the focus
            // Configure the component with the specified value
            setText(df2.format(value));
            // Set tool tip if desired
            //setToolTipText((String)value);
            // Since the renderer is a component, return itself
            return this;
        // The following methods override the defaults for performance reasons
        public void validate() {}
        public void revalidate() {}
        protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {}
        public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {}
    }The table holds data that I pulled in from an SQL database query. The Query works fine, I get my row of data, break it up into a Vector, then add it to the table model.
Code:
                   pst=sqlConnection.prepareStatement("SELECT * FROM taxilogdb ORDER BY id DESC LIMIT 1");
                    rs=pst.executeQuery();
                    while(rs.next()){
                        v.add((Date)rs.getTimestamp("timegiven"));
                        v.add(rs.getString("location"));
                        v.add(rs.getTimestamp("arrival"));
                        v.add(rs.getTimestamp("pickup"));
                        v.add(rs.getString("destination"));
                        v.add(rs.getDouble("fare"));
                        v.add(rs.getDouble("paid"));
                        v.add(rs.getDouble("check1"));
                        v.add(rs.getDouble("charge"));
                        v.add(rs.getTimestamp("clear"));
                        v.add(rs.getBoolean("CMO"));
                        v.add(rs.getBoolean("saferide"));
                        v.add(rs.getBoolean("timecall"));
                        v.add(rs.getBoolean("passed"));
                        v.add(rs.getBoolean("personal"));
                        v.add(rs.getBoolean("roadcrew"));
                        v.add(rs.getBoolean("walkup"));
                        v.add(rs.getString("chargeName"));
                        v.add(rs.getInt("ID"));
                    model.insertRow(0,v);
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }When I run the app, I get an exception:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.sql.Timestamp
at TaxiLogUI.TaxiLogUI$MyTableCellRenderer.getTableCellRendererComponent(TaxiLogUI.java:3589)
at javax.swing.JTable.prepareRenderer(JTable.java:3924)
at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2070)
I'm guessing from the Exception it is a result of trying to format the data as a Date. What I don't understand is that I Cast the SQL Timestamp to a Date, and as far as I can tell, that works fine. I verified that the issue is NOT when I break up the result set from the SQL Query, So I am not 100% sure where it's coming from. Why is it generating this exception? What should I read up on?? I'm stuck . Thanks.

If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained,
Compilable and Executable, Example Program that demonstrates the
incorrect behaviour, because I can't guess exactly what you are doing
based on the information provided.
And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its
original formatting.

Similar Messages

  • Problem with addRow and MultiLine Cell renderer

    Hi ,
    Ive a problem with no solution to me .......
    Ive seen in the forum and Ivent found an answer.......
    The problem is this:
    Ive a JTable with a custom model and I use a custom multiline cell renderer.
    (becuse in the real application "way" hasnt static lenght)
    When I add the first row all seem to be ok.....
    when I try to add more row I obtain :
    java.lang.ArrayIndexOutOfBoundsException: 1
    at javax.swing.SizeSequence.insertEntries(SizeSequence.java:332)
    at javax.swing.JTable.tableRowsInserted(JTable.java:2926)
    at javax.swing.JTable.tableChanged(JTable.java:2858)
    at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableMo
    del.java:280)
    at javax.swing.table.AbstractTableModel.fireTableRowsInserted(AbstractTa
    bleModel.java:215)
    at TableDemo$MyTableModel.addRow(TableDemo.java:103)
    at TableDemo$2.actionPerformed(TableDemo.java:256)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:17
    64)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Abstra
    ctButton.java:1817)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
    .java:419)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
    istener.java:245)
    at java.awt.Component.processMouseEvent(Component.java:5134)
    at java.awt.Component.processEvent(Component.java:4931)
    at java.awt.Container.processEvent(Container.java:1566)
    at java.awt.Component.dispatchEventImpl(Component.java:3639)
    at java.awt.Container.dispatchEventImpl(Container.java:1623)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
    at java.awt.Container.dispatchEventImpl(Container.java:1609)
    at java.awt.Window.dispatchEventImpl(Window.java:1590)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
    read.java:197)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    This seems to be caused by
    table.setRowHeight(row,(getPreferredSize().height+2)); (line 164 of my example code)
    About the model I think its ok.....but who knows :-(......
    Please HELP me in anyway!!!
    Example code :
    import javax.swing.*;
    import javax.swing.table.*;
    import java.text.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class TableDemo extends JFrame {
    private boolean DEBUG = true;
    MyTableModel myModel = new MyTableModel();
    MyTable table = new MyTable(myModel);
    int i=0;
    public TableDemo() {
    super("TableDemo");
    JButton bottone = new JButton("Aggiungi 1 elemento");
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(bottone,BorderLayout.NORTH);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    bottone.addActionListener(Add_Action);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    class MyTable extends JTable {
    MultiLineCellRenderer multiRenderer=new MultiLineCellRenderer();
    MyTable(TableModel tm)
    super(tm);
    public TableCellRenderer getCellRenderer(int row,int col) {
              if (col==1) return multiRenderer;
              else return super.getCellRenderer(row,col);
    class MyTableModel extends AbstractTableModel {
    Vector data=new Vector();
    final String[] columnNames = {"Name",
    "Way",
    "DeadLine (ms)"
    public int getColumnCount() { return 3; }
    public int getRowCount() { return data.size(); }
    public Object getValueAt(int row, int col) {
    Vector rowdata=(Vector)data.get(row);
                                                                return rowdata.get(col); }
    public String getColumnName(int col) {
    return columnNames[col];
    public void setValueAt (Object value, int row,int col)
         //setto i dati della modifica
    Vector actrow=(Vector)data.get(row);
    actrow.set(col,value);
         this.fireTableCellUpdated(row,col);
         public Class getColumnClass(int c)
              return this.getValueAt(0,c).getClass();
         public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col == 1)
    return false;
    else
    return true;
    public void addRow (String name,ArrayList path,Double dead) {
         Vector row =new Vector();
         row.add(name);
         row.add(path);
         row.add(dead);
         row.add(name); //!!!Mi tengo questo dato da utilizzare come key per andare a
         //prendere il path nella lista dei paths di Project
         //(needed as key to retrive data if name in col. 1 is changed)
         data.add(row);
         //Inspector.inspect(this);
         System.out.println ("Before firing Adding row...."+this.getRowCount());
         this.fireTableRowsInserted(this.getRowCount(),this.getRowCount());
    public void delRow (String namekey)
    for (int i=0;i<this.getRowCount();i++)
    if (namekey.equals(this.getValueAt(i,3)))
    data.remove(i);
    this.fireTableRowsDeleted(i,i);
    //per uscire dal ciclo
    i=this.getRowCount();
    public void delAllRows()
    int i;
    int bound =this.getRowCount();     
    for (i=0;i<bound;i++)     
         {data.remove(0);
         System.out.println ("Deleting .."+data);
    this.fireTableRowsDeleted(0,i);          
    class MultiLineCellRenderer extends JTextArea implements TableCellRenderer {
    private Hashtable rowHeights=new Hashtable();
    public MultiLineCellRenderer() {
    setEditable(false);
    setLineWrap(true);
    setWrapStyleWord(true);
    //this.setBorder(new Border(
    public Component getTableCellRendererComponent(JTable table,Object value,                              boolean isSelected, boolean hasFocus, int row, int column) {
    //System.out.println ("Renderer called"+value.getClass());
    if (value instanceof ArrayList) {
    String way=new String     (value.toString());
    setText(way);
    TableColumn thiscol=table.getColumn("Way");
    //System.out.println ("thiscol :"+thiscol.getPreferredWidth());
    //setto il size della JTextarea sulle dimensioni della colonna
    //per quanto riguarda il widht e su quelle ottenute da screen per l'height
    this.setSize(thiscol.getPreferredWidth(),this.getPreferredSize().height);
    // set the table's row height, if necessary
    //System.out.println ("Valore getPreferred.height"+getPreferredSize().height);
         if (table.getRowHeight(row)!=(this.getPreferredSize().height+2))
         {System.out.println ("Setting Row :"+row);
             System.out.println ("Dimension"+(getPreferredSize().height+2));
             System.out.println ("There are "+table.getRowCount()+"rows in the table ");
             if (row<table.getRowCount())
             table.setRowHeight(row,(getPreferredSize().height+2));
    else
    setText("");
    return this;
    /**Custom JTextField Subclass che permette all'utente di immettere solo numeri
    class WholeNumberField extends JTextField {
    private Toolkit toolkit;
    private NumberFormat integerFormatter;
    public WholeNumberField(int value, int columns) {
    super(columns);
    toolkit = Toolkit.getDefaultToolkit();
    integerFormatter = NumberFormat.getNumberInstance(Locale.US);
    integerFormatter.setParseIntegerOnly(true);
    setValue(value);
    public int getValue() {
    int retVal = 0;
    try {
    retVal = integerFormatter.parse(getText()).intValue();
    } catch (ParseException e) {
    // This should never happen because insertString allows
    // only properly formatted data to get in the field.
    toolkit.beep();
    return retVal;
    public void setValue(int value) {
    setText(integerFormatter.format(value));
    protected Document createDefaultModel() {
    return new WholeNumberDocument();
    protected class WholeNumberDocument extends PlainDocument {
    public void insertString(int offs,
    String str,
    AttributeSet a)
    throws BadLocationException {
    char[] source = str.toCharArray();
    char[] result = new char[source.length];
    int j = 0;
    for (int i = 0; i < result.length; i++) {
    if (Character.isDigit(source))
    result[j++] = source[i];
    else {
    toolkit.beep();
    System.err.println("insertString: " + source[i]);
    super.insertString(offs, new String(result, 0, j), a);
    ActionListener Add_Action = new ActionListener() {
              public void actionPerformed (ActionEvent e)
              System.out.println ("Adding");
              ArrayList way =new ArrayList();
              way.add(new String("Uno"));
              way.add(new String("Due"));
              way.add(new String("Tre"));
              way.add(new String("Quattro"));
              myModel.addRow(new String("Nome"+i++),way,new Double(0));     
    public static void main(String[] args) {
    TableDemo frame = new TableDemo();
    frame.pack();
    frame.setVisible(true);

    In the addRow method, change the line
    this.fireTableRowsInserted(this.getRowCount(),this.getRowCount()); to
    this.fireTableRowsInserted(data.size() - 1, data.size() - 1);Sai Pullabhotla

  • Table cell renderer works with any L&F, but not with Windows

    Hi,
    I created a table cell renderer / editor for a combobox in a table cell. This works all as expected, but if the Look&Feel is com.sun.java.swing.plaf.windows.WindowsLookAndFeel, which is the system L&F on Vista, the selected values in the combobox are not shown in the cell after loosing focus. Metal LF and Motif LF work, and a third party one "TinyLF" works as well.
    Can anyone imagine why, and what needs to be changed to get a cross platform consistency without Metal LF?
    A compilable demo:
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.io.IOException;
    import java.security.NoSuchAlgorithmException;
    import javax.swing.DefaultCellEditor;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    public class Test {
        static class CellRendererWithComboBox extends JLabel implements TableCellRenderer {
            JLabel label = new JLabel();
             * Set this renderer to the given column
             * @param column
             * @param r
             * @param editable
            public void setRendererTo(JTable table, int column, boolean editable) {
                TableColumn col = table.getColumnModel().getColumn(column);
                JComboBox xc = new JComboBox(new DefaultComboBoxModel(new Object[]{1, 2, 3, 4, 5, 6, 7}));
                col.setCellEditor(new ComboBoxEditor(xc));
                col.setCellRenderer(this);
                xc.setEditable(editable);
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
                if (hasFocus && isSelected) {
                    if (isSelected) {
                        label.setForeground(table.getSelectionForeground());
                        label.setBackground(table.getSelectionBackground());
                    } else {
                        label.setForeground(table.getForeground());
                        label.setBackground(table.getBackground());
                    label.setText((value == null) ? "" : value.toString());
                    return label;
                } else {
                    label.setText((value == null) ? "" : value.toString());
                    return label;
            class ComboBoxEditor extends DefaultCellEditor {
                private final JComboBox box;
                private boolean fire = true;
                public ComboBoxEditor(JComboBox b) {
                    super(b);
                    this.box = b;
                    b.setLightWeightPopupEnabled(false);
                @Override
                public boolean stopCellEditing() {
                    if (fire) {
                        super.stopCellEditing();
                    return true;
                public void stopCellEditingSilent() {
                    fire = false;
                    stopCellEditing();
                    fire = true;
        public static void main(String... aArgs) throws NoSuchAlgorithmException, IOException {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException classNotFoundException) {
            } catch (InstantiationException instantiationException) {
            } catch (IllegalAccessException illegalAccessException) {
            } catch (UnsupportedLookAndFeelException unsupportedLookAndFeelException) {
            JFrame p = new JFrame();
            JTable t = new JTable();
            TableModel m = new DefaultTableModel(new Object[][]{
                        new Object[]{1, 2, 3, 4, 5, 6, 7},
                        new Object[]{1, 2, 3, 4, 5, 6, 7},
                        new Object[]{1, 2, 3, 4, 5, 6, 7},
                        new Object[]{1, 2, 3, 4, 5, 6, 7},
                        new Object[]{1, 2, 3, 4, 5, 6, 7}},
                    new Object[]{1, 2, 3, 4, 5, 6, 7});
            t.setModel(m);
            Test.CellRendererWithComboBox f = new CellRendererWithComboBox();
            f.setRendererTo(t, 1, true);
            p.setLayout(new BorderLayout());
            p.add(t, BorderLayout.CENTER);
            p.pack();
            p.setVisible(true);
    }

    1) Your custom cell renderer does nothing extra, so you can depend on default renderer.
    2) Instead of extending JLabel and implementing TableCellReneder, you should extend DefaultTableCellRenderer and override its get renderer method because DefaultTableCellRenderer itself extends JLabel and aditionally it does some optimizations etc., which you can miss if you implement your own renderer.
    3) If you set foreground and background color in last else statement also, then you can see the values correctly in windows L&F as well.
    Thanks!

  • Event Handling in JTable Custom Cell Renderer

    I have a JLabel as a custom cell Renderer for a column. I want to handle mouse click event for the JLabel rendered in the cell.
    I tried adding the listener for the label in the custom cell renderer but it is not working. Any ideas how to handle this problem??
    Thanks
    S.Anand

    If you want to handle the selection of a tree node
    1) write a class like:
    public class TreePaneListener implements TreeSelectionListener {
    // TREE SELECTION LISTENER
    public void valueChanged(TreeSelectionEvent e) {
    JTree tree = (JTree)e.getSource();
    DefaultMutableTreeNode node = null;
    int count = 0;
    boolean doSomething = false;
    if(tree.getSelectionCount() > 1) {
         TreePath[] selection = tree.getSelectionPaths();
         int[] temp = new int[selection.length];
         for(int i =0; i < selection.length; i++) {
    // Check each node for selection
         node = (DefaultMutableTreeNode)selection.getLastPathComponent();
         if(node.getLevel()==2) {
    // Change this code to take the action desired
         doSomething = true;
    2) After creating the tree register the listener
    TreePaneListener handler = new TreePaneListener();
    tree.addTreeSelectionListener(handler);

  • Set Background/Foreground color for Cell Renderer in JComboBox

    Hello,
    I was wondering if there is a way to change default settings for when I browse items under a JComboBox's cell renderer? I want the item's color to change (to what I set it to), when mouse enters the item. As of now, the cell's background color changes to Blue when I enter it. Is this default for JComboBox or might it have been set somewhere, that I need to look into?
    Please let me know if there are ways to do this.
    Thanks!
    Message was edited by:
    programmer_girl

    Here's my SSCCE:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JComboBox;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.text.DefaultHighlighter;
    public class MyComboBoxTest extends JPanel {
          * @param args
         String[] patterns = {"pattern1","pattern2","pattern3"};
         public MyComboBoxTest()
              JPanel patternsPanel = new JPanel();
            setMinimumSize(new Dimension(100, 100));
            JComboBox patternList = new JComboBox(patterns);
            final JTextField editor = (JTextField) patternList.getEditor().getEditorComponent();
            patternList.setEditable(true);
            this.add(patternsPanel);
            patternsPanel.add(patternList);
            patternList.addActionListener(new ActionListener()
                 public void actionPerformed(ActionEvent e)
                      editor.setSelectedTextColor(Color.WHITE);
                      editor.setForeground(Color.WHITE);
                      try{
                           editor.getHighlighter().addHighlight(0, editor.getText().length(),new DefaultHighlighter.DefaultHighlightPainter(Color.BLUE));
                           } catch (Exception ex){
                                ex.getMessage();
            editor.addMouseListener(new MouseAdapter()
                 public void mouseClicked(MouseEvent e)
                      editor.getHighlighter().removeAllHighlights();
                      editor.setForeground(Color.BLACK);
                      editor.setSelectedTextColor(Color.BLACK);
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              JFrame frame = new JFrame("My ComboBox Demo");
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setSize(100, 100);
            frame.getContentPane().add(new MyComboBoxTest());
            frame.setLocation(50, 50);
            frame.pack();
            frame.setVisible(true);
    }

  • How to display multiple JComponents in a tree cell renderer

    I have an object in a tree cell renderer and want to display its members(three members) status in a JTree as checkboxes such that each node displays three checkboxex with member-names and a node name. i tried using a JPanel and adding three labels into this panel to be returned for the cell renderer but the GUI fails to paint the node componnents. However on clicking the node the component which isn't visible displays correctly. please Help me out

    Since you didn't provide any sample code, it's all about wild guesses on what your problem is. The following code shows the type of program you could have posted :import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    public class TestTree extends JPanel {
         private static class MyCell {
              String theCellName;
              boolean theFirstField;
              boolean theSecondField;
              boolean theThirdField;
              public MyCell(String aName, boolean firstField, boolean secondField, boolean thirdField) {
                   theCellName = aName;
                   theFirstField = firstField;
                   theSecondField = secondField;
                   theThirdField = thirdField;
         private static class MyTreeCellRenderer extends JPanel implements TreeCellRenderer {
              private JLabel theCellNameLabel;
              private JCheckBox theFirstCheckBox;
              private JCheckBox theSecondCheckBox;
              private JCheckBox theThirdCheckBox;
              private DefaultTreeCellRenderer theDelegate;
              public MyTreeCellRenderer() {
                   super(new GridLayout(4, 1));
                   theCellNameLabel = new JLabel();
                   add(theCellNameLabel);
                   theFirstCheckBox = new JCheckBox("firstField");
                   add(theFirstCheckBox);
                   theSecondCheckBox = new JCheckBox("secondField");
                   add(theSecondCheckBox);
                   theThirdCheckBox = new JCheckBox("thirdField");
                   add(theThirdCheckBox);
                   theDelegate = new DefaultTreeCellRenderer();
                   setOpaque(true);
              public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                                                                       boolean expanded, boolean leaf, int row, boolean hasFocus) {
                   if (!(value instanceof DefaultMutableTreeNode)) {
                        return theDelegate.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
                   Object userObject = ((DefaultMutableTreeNode)value).getUserObject();
                   if (!(userObject instanceof MyCell)) {
                        return theDelegate.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
                   setBackground(tree.getBackground());
                   if (selected) {
                        setBorder(BorderFactory.createLineBorder(Color.BLUE, 2));
                   } else {
                        setBorder(BorderFactory.createLineBorder(getBackground(), 2));
                   MyCell cell = (MyCell)userObject;
                   theCellNameLabel.setText(cell.theCellName);
                   theFirstCheckBox.setSelected(cell.theFirstField);
                   theSecondCheckBox.setSelected(cell.theSecondField);
                   theThirdCheckBox.setSelected(cell.theThirdField);
                   return this;
              public Component add(Component comp) {
                   if (comp instanceof JComponent) {
                        ((JComponent)comp).setOpaque(false);
                   return super.add(comp);
         public TestTree() {
              super(new BorderLayout());
              JTree tree = new JTree(createModel());
              tree.setShowsRootHandles(true);
              tree.setCellRenderer(new MyTreeCellRenderer());
              add(new JScrollPane(tree), BorderLayout.CENTER);
         private static final TreeModel createModel() {
              DefaultMutableTreeNode root = new DefaultMutableTreeNode(new MyCell("root", true, true, true));
              DefaultMutableTreeNode child1 = new DefaultMutableTreeNode(new MyCell("child1", false, true, false));
              DefaultMutableTreeNode child2 = new DefaultMutableTreeNode(new MyCell("child2", false, false, true));
              root.add(child1);
              root.add(child2);
              return new DefaultTreeModel(root);
         public static void main(String[] args) {
              final JFrame frame = new JFrame("Test");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setContentPane(new TestTree());
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.setSize(600, 400);
                        frame.show();
    }

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

  • CheckBox in customized cell renderer - Urgent

    i need to customize the cell renderer for a table for one of the columns. One of the column is Boolean type and i want it the way it comes in a default cell renderer.
    if i mention the renderer for the column as "checkbox" - it gives me the checkbox "left aligned" i want it in the center.
    what shall i do?

    that works.
    thanks ivan.
    could i get the same result with defaultTableCellRenderer? as it extends JLabel i get the label-"true/false" not the checkbox.

  • JTable with JPanel form as cell renderer/editor

    I have a JTable that uses a custom cell editor/renderer. The cell editor/renderer is a JPanel form with labels and text panes. As the user edits the information, I adjust the table row height (setRowHeight) and the JPanel layout manager updates the layout on the cell editor. This all seems to work fine. However, when the user exists the cell and the cell renderer is shown, it has the correct new row height but has not been correctly layed-out for the new row height. How do I force my cell renderer to be re-layout after the editor closes?

    That does not seem to work. I have done the following:
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int r, int c)
    this.table = (EditorTable) table;
    row = r;
    column = c;
    if (isSelected)
    setBackground (Preferences.selectedRowBgColor);
    else
    setBackground (formBg);
    // constructs the panel components
    setCellValue (value);
    revalidate();
    return (this);

  • Tree Cell Renderer settings for displaying complete text.

    I have a tree model. It is of the form
    abc (123.00)
    -----def (456.00)
    ----------ghi (678.00)
    But it is displayed like
    abc (12...
    -----def (45..
    ----------ghi (67..
    I don't want the numbers in the end to be missing. It is a problem for the user to expand them everytime.
    I am using, JTree and using my cell renderer, with following properties in
    super.getTreeCellRendererComponent(tree, false, X, false, false, row, false);I did try to change it to
    super.getTreeCellRendererComponent(tree, false, X, TRUE, false, row, false);but still no success.
    My function toString() for tree elements looks like this
                     double u = "123.00";
                     String num = String.format("%.2f", u);
                     return getName() + " (" + num  + ")";Can you please suggest possible way around for this?

    package abc;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.WindowConstants;
    import javax.swing.JFrame;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeSelectionModel;
    public class NewJPanel extends javax.swing.JPanel implements MouseListener {
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              frame.getContentPane().add(new NewJPanel());
              frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);
         JTree m_tree;
        private JScrollPane myPane;
        float multi = 1;
        DefaultTreeModel tree = new DefaultTreeModel(new ContainerNode("root"));
        DefaultMutableTreeNode parent = (DefaultMutableTreeNode)tree.getRoot();
         public NewJPanel() {
            super(new BorderLayout());
            String util = String.format("%.2f", 123456789012345679801234567980.00);
            util = "abc" + " (" + util  + ")";
                DefaultMutableTreeNode e = new DefaultMutableTreeNode(util);
                tree.insertNodeInto(e, parent, 0);
            m_tree = new JTree(tree);
            m_tree.setEditable(false);
            m_tree.setDragEnabled(false);
            m_tree.getSelectionModel().setSelectionMode(TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
            m_tree.setAutoscrolls(true);
            m_tree.setPreferredSize(new java.awt.Dimension(397, 297));
            myPane = new JScrollPane(m_tree);
            myPane.setAutoscrolls(true);
            myPane.getVerticalScrollBar().setAutoscrolls(true);
            add(myPane, BorderLayout.CENTER);
            m_tree.addMouseListener(this);
              initGUI();
         private void initGUI() {
              try {
                   setPreferredSize(new Dimension(400, 300));
              } catch (Exception e) {
                   e.printStackTrace();
         public void mouseClicked(MouseEvent e) {
              String util = String.format("%f", 6546464642345679801234567980.00 * multi);
            util = "abc" + " (" + util  + ")";
            DefaultMutableTreeNode child = (DefaultMutableTreeNode) parent.getChildAt(0);
            child.setUserObject(util);
            m_tree.repaint();
         public void mouseEntered(MouseEvent e) {}
         public void mouseExited(MouseEvent e) {}
         public void mousePressed(MouseEvent e) {}
         public void mouseReleased(MouseEvent e) {}
    class ContainerNode extends DefaultMutableTreeNode
        private static final long serialVersionUID = 14;
        ContainerNode(String s)
        { super(s); }
    }Executing this code... clicking in the panel, changes the number.
    The new number is displayed as (65464646423456798000000000.000.......
    My problem is nearly similar, except that in my code I am using, String.format("%.2f", 6546464642345679801234567980.00 * multi);
    and still I get (65...)

  • Custom table model, table sorter, and cell renderer to use hidden columns

    Hello,
    I'm having a hard time figuring out the best way to go about this. I currently have a JTable with an custom table model to make the cells immutable. Furthermore, I have a "hidden" column in the table model so that I can access the items selected from a database by their recid, and then another hidden column that keeps track of the appropriate color for a custom cell renderer.
    Subject -- Sender -- Date hidden rec id color
    Hello Pete Jan 15, 2003 2900 blue
    Basically, when a row is selected, it grabs the record id from the hidden column. This essentially allows me to have a data[][] object independent of the one that is used to display the JTable. Instinctively, this does not seem right, but I don't know how else to do it. I know that the DefaultTableModel uses a Vector even when it's constructed with an array and I've read elsewhere that it's not a good idea to do what I'm trying to do.
    The other complication is that I have a table sorter as well. So, when it sorts the objects in the table, I have it recreate the data array and then set the data array of the ImmutableTableModel when it has rearranged all of the items in the array.
    On top of this, I have a custom cell renderer as well. This checks yet another hidden field and displays the row accordingly. So, not only does the table sort need to inform the table model of a change in the data structure, but also the cell renderer.
    Is there a better way to keep the data in sync between all of these?

    To the OP, having hidden columns is just fine, I do that all the time.. Nothing says you have to display ALL the info you have..
    Now, the column appears to be sorting properly
    whenever a new row is added. However, when I attempt
    to remove the selected row, it now removes a seemingly
    random row and I am left with an unselectable blank
    line in my JTable.I have a class that uses an int[] to index the data.. The table model displays rows in order of the index, not the actual order of the data (in my case a Vector of Object[]'s).. Saves a lotta work when sorting..
    If you're using a similar indexing scheme: If you're deleting a row, you have to delete the data in the vector at the INDEX table.getSelectedRow(), not the actual data contained at
    vector.elementAt(table.getSelectedRow()). This would account for a seemingly 'random' row getting deleted, instead of the row you intend.
    Because the row is unselectable, it sounds like you have a null in your model where you should have a row of data.. When you do
    vector.removeElementAt(int), the Vector class packs itself. An array does not. If you have an array, when you delete the row you must make sure you dont have that gap.. Make a new array of
    (old array length-1), populate it, and give it back to your model.. Using Vectors makes this automatic.
    Also, you must make sure your model knows the data changed:
    model.fireTableDataChanged(); otherwise it has no idea anything happened..
    IDK if that's how you're doing it, but it sounds remarkably similar to what I went thru when I put all this together..

  • Custom cell renderer.

    Folks,
    I have written a small custom defined cell renderer which displays
    a list
    When the first item is selected,the focus turns to red
    When the 2nd item is selected,1 and 2 items turn to red.
    (Obviously as I am setting the background to red)
    I just need to change the color of the focus element only.
    ie when i click the 1st element,focus changes to red.
    when i click the 2nd element,only the 2nd element becomes red and not the 1st and 2nd element
    class FTRDListCellRenderer extends JLabel implements ListCellRenderer {
    private final JLabel label = new JLabel();
      label.setOpaque(true);
      public Component getListCellRendererComponent(
      JList list, Object value,int index,
      boolean isSelected, boolean cellHasFocus) {
      label.setText(value.toString());
      if(isSelected){
      label.setBackground(isSelected ? Color.red : Color.yellow);
       else{
       return label;

    xpost
    http://forum.java.sun.com/thread.jsp?forum=31&thread=490864&tstart=0&trange=15

  • JTree cell renderer: how to fill whole row?

    hi,
    i'm trying to make a tree cell renderer that renders at default height, but fills the horizontal width of the tree (e.g. with a JLabel with a custom background color). I'm working on the theory that in order to do this you need to change the preferred size of the component used to stamp the image at render time.
    The problem is that the preferred width then needs to be set to a value that depends on the context of the particular node (e.g. a deeply nested child node will be further to the right than the root node).
    I can't seem to find a method to say where the rendering starts though - does anyone know a way?
    (also if not then would setting the width to some astronimcal value break anything?)
    thanks,
    asjf

    Try this one, it will higlight the background and foreground colors of entire rows.
    Oscar
         class TableRenderer
              extends DefaultTableCellRenderer
              implements ListCellRenderer
              private boolean focused = true;
              private JLabel renderer;
              public TableRenderer()
                   super();
                   renderer = new JLabel();
                   renderer.setOpaque(true);
              public Component getListCellRendererComponent(
                   JList list,
                   Object value,
                   int index,
                   boolean isSelected,
                   boolean cellHasFocus)
                   return renderer;
              public Component getTableCellRendererComponent(
                   JTable table,
                   Object value,
                   boolean isSelected,
                   boolean hasFocus,
                   int row,
                   int column)
                   renderer =
                        (JLabel) super.getTableCellRendererComponent(
                             table,
                             value,
                             isSelected,
                             hasFocus,
                             row,
                             column);
                   /* Make the Labels border empty and indented */
                   setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));
                   /* This is used to create alternate row colors */
                   Color bgColor = Color.white;
                   if (row % 2 == 0)
                        bgColor = new Color(237, 243, 254);
                   /* if the table has focus and the row is selected use these colors */
                   if (table.hasFocus() && table.getSelectedRow() == row)
                        table.setSelectionForeground(Color.WHITE);
                        table.setSelectionBackground(new Color(101, 137, 178));
                   /* if the table has not the focus but the row is selected use these colors */
                   else if (
                        table.hasFocus() == false && table.getSelectedRow() == row)
                        table.setSelectionBackground(new Color(196, 196, 194));
                   /* if not use the standard color */
                   else
                        renderer.setBackground(bgColor);
                        table.setSelectionForeground(SystemColor.textText);
                   if (value instanceof ColorData)
                        ColorData cvalue = (ColorData) value;
                        setForeground(cvalue.color);
                        setText(cvalue.data.toString());
                                /* Set the Labels value */
                   setText(String.valueOf(value));
                   return renderer;
         }

  • Custom Jtree Cell Renderer goes to infinite loopp...any suggestion???

    Hey ...thanks for you help before....
    Another problem..
    My Jtree works fine with default Cell Renderer .. but goes to infinite
    loop with CustomDefaultRenderer after few minutes...
    Any suggestions....
        public DynamicTree() {
            super(new GridLayout(1,0));
            rootNode = new DefaultMutableTreeNode("POSTINGS & SEARCHES");
            treeModel = new DefaultTreeModel(rootNode);
            treeModel.addTreeModelListener(new MyTreeModelListener());
            tree = new JTree(treeModel);
            tree.setEditable(false);
            tree.getSelectionModel().setSelectionMode
                    (TreeSelectionModel.SINGLE_TREE_SELECTION);
            tree.setShowsRootHandles(true);
      //      tree.addMouseListener(ml);
      //      tree.addKeyListener(kl);
            JScrollPane scrollPane = new JScrollPane(tree);
            add(scrollPane);
            //          tree.setCellRenderer();
            tree.addTreeSelectionListener(new TreeSelectionListener(){
                public void valueChanged(TreeSelectionEvent evt){
                    System.out.println("Tree's lead selection path is " +
                            tree.getLeadSelectionPath());
            tree.setCellRenderer( new CustomDefaultRenderer());              
    public class CustomDefaultRenderer extends DefaultTreeCellRenderer {
        String suffix = null ;
        String prefix = null ;
        boolean expired = false;
        boolean matched = false ;
        PostingHandler pHandler = new PostingHandler();
        public Component getTreeCellRendererComponent(
                JTree tree,
                Object value,
                boolean sel,
                boolean expanded,
                boolean leaf,
                int row,
                boolean hasFocus) {
            super.getTreeCellRendererComponent(
                    tree, value, sel,
                    expanded, leaf, row,
                    hasFocus);
            suffix = (String)value.toString() ;
            try {
                prefix = value.toString().substring(0,value.toString().indexOf(":") + 1);
                suffix = suffix.substring(suffix.indexOf(":")+1,suffix.length());
                System.out.println("Prefix:"+prefix +"\tSufix :"+suffix);
            }catch (Exception e){System.out.println("Nothing to index yet" + e);}
            //    value = (Object)suffix;
            if(pHandler.newPostingsMatch.contains(prefix)) {
         //            if(hasFocus){pHandler.removePostingMatch(prefix);}               
                         setBackgroundNonSelectionColor(Color.CYAN);
            }else
                setBackgroundNonSelectionColor(Color.WHITE);
            System.out.println("Other <>values:\tValue" + value.toString() + "\tSEL:"+sel +"\tExpanded:" + "\tLEAF:"+leaf +
                    "\tRow:" +row + "\tfocus:"+hasFocus );
            return this;
        public void paintComponent(Graphics g){
            System.out.println("Paint is called");
            //g.drawLine(0, 0, 100, 100);
            if(expired){
                g.drawLine(22, 11, 100,11);
            g.drawString(suffix, 22,15);
            validate();
            repaint();
    }

    Figured it out right after this post :)
    I had to do the following in my cellrenderer
    setBackgroundNonSelectionColor(new Color(0, 0, 0, 0));As a parameter I sent a color object with a alpha level of 0 (completly transparent)...

  • Table Cell Renderer Customization not working

    I have a customized cell renderer that works wonderfully, it paints the background and text like it should, but I am also trying to paint a stripe like a 1 sided border across the top of the table cell, but (and this is the wierd part) only the first table column header is painting with this "stripe" on the top of it, every other column header and every other table cell do not paint with stripe on it. I print out the coords as I pass them to the graphics object to paint the line and the coords are correct, but the lines only show up in the first cell.
    I have tried to put this code into the Renderer, and today I tried to put it into the UIComponent with the same result.
    Relevant code:
    // inner class for the renderer
    private class LabelUI extends MetalLabelUI
    public void paint(Graphics g,JComponent c)
    // PAINT THE LABEL(RENDERER) USING THE NORMAL ROUTINE
    super.paint(g,c);
    // PICK A COLOR TO TEST THE CODE
    g.setColor(Color.green);
    // DUMP THE COORDS OUT TO CONSOLE
    System.out.println("Drawing a line from :"+
    c.getX()+","+(c.getY()+1)+","+
    (c.getX()+c.getWidth())+","+(c.getY()+1));
    // DRAW THE LINES
    g.drawLine(c.getX(),c.getY()+1,c.getX()+c.getWidth(),c.getY()+1);
    g.drawLine(c.getX(),c.getY()+2,c.getX()+c.getWidth(),c.getY()+2);
    }

    camickr- thanks for the input. I had tried a matte border yesterday in the renderer and the L&F object and couldn't get it to paint, but maybe I have something set elsewhere that is preventing it from painting, so I'll give that one another try. If I come up with an answer I'll be sure to post! -dohare
    If I understand the question then take a look at the
    HighlightCellRenderer class of this little
    application. It uses vertical lines on certain
    columns:
    http://www.discoverteenergy.com/files/RHex.zip
    run the program: java Hex

Maybe you are looking for

  • Reminder for text based PO's on plant level or purchasing org. level?

    Hi, I work for a corporate company and we have in our system arround 100 different plant codes (of more or less different companies). My problem is now, how to set-up the reminder in part of text based purchase orders for the different plants? Or dif

  • Posting an 850 Purchase Order through EDI

    Heyy Guys, I am trying to post an 850 from translator and I am struck at the control record mapping. I maintained VOE4 entries for mapping external partner number to internal partner number. But doesn't the SNDPRN field in the control record use that

  • Calculating the % in  the query...

    Hi, There is a column in the query , which contains 0's and 1's. I want to calculate the  % of all 1's in the query as a result i.e (counting all values <> 0/counting all values) * 100 Is is possible through formula?? Thanks.

  • I cannot find an option in iphone4s to lock on GSM (2g) network. Similar option is available in iPhone 4.

    I cannot find an option in iphone4s to lock on GSM (2g) network. Similar option is available in iPhone 4.

  • Boolean help

    I need to design a programme which determines whether you are a taurus or not. public class taurus1 public static void main (String args []) boolean taurus; int month,day; month=4; day=6; if((month == 4) && (day > 20)) taurus = true; if((month == 5)