JTable loses selection with custom renderes

Hello,
I have a JXTreeTable with five columns, out of which I have custom rendered 3 columns. When I select a node is the tree, the corresponding columns are selected except the custom rendered columns. Any reason why it would be so?.
I have set the row selection enabled to be true.
I know I shouldnt be posting JXTreeTable questions here, but am hoping any JTable guru's might be able to help me out
Thanks
K

The general structure of the renderer code would be:
class CustomRenderer extends DefaultTableCellRenderer
     public Component getTableCellRendererComponent(
          JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
          super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
          if (! isSelected)
               // add your custom code here to change background
          return this;
}

Similar Messages

  • JTable column names with custom model

    I'm having problems with column names in a JTable which uses a custom model. For some reason, the colums are being shown as A, B, C etc. The data, however, displays fine.
    This is the code which constructs the table.
    MyTableModel tableModel = new MyTableModel(myArrayList);
      myTable = new JTable(tableModel);
      myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      myTable.setFillsViewportHeight(true);This is the class, MyTableModel
    class MyTableModel extends AbstractTableModel {
            private ArrayList<Account> data;
            private String[] colNames = {"", "Name","Type","Group","Created","Modified"};
            public MyTableModel(ArrayList<Account> data) {
                this.data = data;
            public int getRowCount() {
                return data.size();
            public int getColumnCount() {
                return 6;
            public Object getValueAt(int row, int col) {
                Account account = (Account)data.get(row);
                switch(col) {
                    case 0:
                        return account.getIcon();
                    case 1:
                        return account.getName();
                    case 2:
                        return account.getType();
                    case 3:
                        return account.getGroup();
                    case 4:
                        return account.getDateCreated();
                    case 5:
                        return account.getDateModified();
                    default:
                        return "";
            public String getColumName(int index) {
             System.out.println("N:"+colNames[index]);
                return colNames[index];
        }When the table is displayed, nothing's displayed to the console, but I'd have thought getColumnName would print the current column name. Am I missing something obvious?

    Oh great. I'll go back under my rock.
    Thanks =)

  • JTable row selection with tab key

    Helo.
    I'm having a problem selecting rows in a JTable. The JTable is with single row selection and without column and cell selection. When I press <tab> the selection changes to another cell, and I wanna it to change to the other row of the table, can anyone help me? I think this is a easy one and I haven�t found a way to do it. I�m using JBuilder for the development.

    The default Action for the Tab KeyStroke is to move focus to the next cell.
    The default Action for the Enter KeyStroke is to move focus to the next line.
    So this functionality is already available in JTable by default.
    If you want to Tab Key to work the same way as the Enter Key then you need to map the Tab Key to use the Action assigned to the Enter Key.
    This [url http://forum.java.sun.com/thread.jsp?forum=57&thread=505866]posting shows how you can reassign an Action for a given KeyStroke.
    For more information on this topic read this section from the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings.

  • JCheckBox as nodes in JTree having problems with custom renderer and editor

    Ok, let me give some background. I have an XML document that I am parsing and reading in as a JTree. Works fine.
    Next, I have overwritten the DefaultTreeCellEditor to return a JCheckBox and in this implementation of the getTreeCellEditorComponent(), I actually tell the node that he is selected. Works great.
    Next, I have overwritten the DefaultTreeCellRenderer to return a JCheckBox and in the implementation of the getTreeCellEditorComponenet, I actually check to see if the Node is selected in the tree based upon the isSelected state of the actual Tree Node set in the tree cell editor, and if so, I set the JCheckBox to selected(true).Works Great.
    Now, here is the issue. If a node in the tree is selected that contains children, then I want all of the children of that node to also be selected. However, when I select a node with children only the selected node is changed, and then a few moments later, the system repaints the entire tree and ALL nodes int the tree are set to a selected state. Strange? Yes. Any ideas?? WONDERFUL!! :)
    Here is the TreeCellEditor code:
    public Component getTreeCellEditorComponent(JTree tree,
    Object value,
    boolean isSelected,
    boolean expanded,
    boolean leaf,
    int row)
    elementCheckBox_ = new JCheckBox();
    Component result = null;
    System.out.println("isSelected? Editor = " + isSelected);
    TreePath newPath = tree.getPathForRow(row);
    System.out.println("value = " + value.getClass().toString());
    if(value instanceof IMarketTreeNodeElement)
    if(isSelected)
    if(((IMarketTreeNodeElement)value).isSelected())
    ((IMarketTreeNodeElement)value).setSelected(false);
    else
    ((IMarketTreeNodeElement)value).setSelected(true);
    elementCheckBox_.setSelected(isSelected);
    return elementCheckBox_;
    Here is the TreeCellRenderer code:
    public Component getTreeCellRendererComponent(JTree tree,
    Object value,
    boolean selected,
    boolean expanded,
    boolean leaf,
    int row,
    boolean hasFocus)
    Color colSelBorderCol = UIManager.getColor
    ("Tree.selectionBorderColor");
    selBorder_ = BorderFactory.createLineBorder(colSelBorderCol, 1);
    normBorder_ = BorderFactory.createEmptyBorder(1,1,1,1);
    elementCheckBox_.setText(value.toString());
    if(selected)
    elementCheckBox_.setSelected(selected);
    elementCheckBox_.setForeground(Color.YELLOW);
    elementCheckBox_.setBackground(Color.RED);
    else
    elementCheckBox_.setForeground(tree.getForeground());
    elementCheckBox_.setBackground(tree.getBackground());
    if (hasFocus)
    elementCheckBox_.setBorder(selBorder_);
    else
    elementCheckBox_.setBorder(normBorder_);
    return elementCheckBox_;
    Here is the Node Code setting all child nodes to selected:
    public void setSelected(boolean selected)
    isSelected_ = selected;
    if(isSelected_)
    if((this.getTagName() == "MARKET") ||
    (this.getTagName() == "TIER") &&
    (this.getChildCount() != 0))
    selectChildren(true);
    else
    if((this.getTagName() == "MARKET") ||
    (this.getTagName() == "TIER") &&
    (this.getChildCount() != 0))
    selectChildren(false);
    public boolean isSelected()
    return isSelected_;
    public void selectChildren(boolean selected)
    int children = getChildCount();
    for(int i = 0; i < children; i++)
    IMarketTreeNodeElement elem = (IMarketTreeNodeElement)
    this.getChildNodes().item(i);
    isSelected_ = selected;
    Thanks for any help! :-)

    I tried to run your sample code and it won't compile. The header files:
    #include
    #include
    #include
    #include
    #include
    do not exist on my install of MeasurementStudio. I am a bit suspicous that I don't have the latest and greatest (loading the dialong resouce gave version warnings). Here is one of my header file headers:
    //==============================================================================
    // Title : NiAxes3d.h
    // Copyright : National Instruments 1999. All Rights Reserved.
    // Purpose : Defines the CNiAxes3D class.
    //==============================================================================
    I
    looked on your updates site and don't really see an update that applies to ComponentWorks or MeasurementStudio. My version per the MAX program for 3DControls is 3.5.549.
    Do I need a newer version? What do I have to do to get the updated version? What does it cost?
    Chuck

  • JTree selection problem when using custom renderer and editor

    Hello:
    I created a JTree with custom renderer and editor.
    The customization makes JCheckBox to be the component
    responsible for editing and rendering.
    The problem is that when I click on the node with the checkbox
    the JTree selection model does not get updated.
    Without customizations of the editor and renderer the MouseEvent would be fired and BasicTreeUI$MouseHandler.mousePressed() method would call
    the selectPathForEvent() method which would be responsible for updating
    the selection model. At the same time if I attach a mouse listener to the JTree (customized) I see the events when clicking on the nodes. It seems like the MouseEvent gets lost and somehow as a result of which the selection model does not get updated.
    Am I missing something?
    Thanks
    Alexander

    You probably forgot to call super.getTreeCellRendererComponent(...) at the beginning of your getTreeCellRendererComponent(...) method in your custom renderer.
    Or maybe in the getTreeCellEditorComponent(...) of the TreeCellEditor...

  • Problem using multiple choice LOV with custom attribute in IAS 10.1.2.0.2

    Hi
    When aplying a multiple choice and selecting multiple selection and saving in the content area , everything looks fine .
    However when looking at the page the selection is only the first one selected and not the miltiple choices I made
    can someone tell me what is going on , does the miltiple selection with custom attribute
    works ??
    thanks in advance
    Igal

    Hi there,
    I don't really understand what you're doing but I used lot of LOV in custom attributes on my custom items and everything works fine.
    Can you explain more your problem ?

  • JTable with custom combobox

    Hi
    I been trying to create a JTable with a custom combobox, that is in a column the lists contained within each combobox is unique. I tried using a renderer, even though the combo appears I cannot select the combo for editing. Any suggestions on how to get the combo working properly would be appreciated thanks.

    It's been a few years since I did something like this, but my recollection is that you should implement the TableCellEditor interface and have the getTableCellEditor method return your custom combo box. Then, either override getCellEditor in your JTable to return your custom TableCellEditor or (better) call tableColumn.setCellEditor for the column you're interested in, passing an instance of your TableCellEditor. I suggest you return the same JComboBox from your implementation of getTableCellEditor every time, and either replace the underlying model or have a custom model in which you can easily switch the contents on-the-fly.
    Having done this in the past, I remember that it's quite easy to leak stuff - I wouldn't advise making a new JComboBox every time.
    Regards,
    Huw

  • Problem with JTree custom renderer when editing

    I have a JTree which uses a custom renderer to display my own icons for different types of nodes. The problem I am having is when I setEditable to true and then attept to edit a node the icon switches back to the default icon, as soon as I am done editing it goes back.
    What I am doing wrong?

    Here is my rendererer
    public class DeviceTreeRenderer extends DefaultTreeCellRenderer implements GuiConstants {
       public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
          JLabel returnValue = (JLabel)super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
          if (value != null) {
             returnValue.setToolTipText(value.toString());
          if (value instanceof Device) {
             returnValue.setIcon(TREE_DEVICE);
             if (!((Device)value).isAlive()) {
                returnValue.setEnabled(false);
          else if (value instanceof GuiPanelGroup) {
             if (expanded) {
                returnValue.setIcon(TREE_PANEL_GROUP_OPEN);
             else {
                returnValue.setIcon(TREE_PANEL_GROUP_CLOSED);
          else if (value instanceof GuiPanel && ((GuiPanel)value).isDirty()) {
             returnValue.setIcon(TREE_PANEL_DIRTY);
          return returnValue;
    }Here is my editor:
    public class WwpJTreeCellEditor extends DefaultTreeCellEditor implements GuiConstants {
          private WwpJTree tree;
           * Creates a new WwpJTreeCellEditor.
           * @param tree The WwpJTree to associate with this editor.
          public WwpJTreeCellEditor(WwpJTree tree) {
             super(tree, (DefaultTreeCellRenderer)tree.getCellRenderer());
             this.tree = tree;
           * Overrides the default isCellEditable so that we check the isEditable() method
           * of the WwpJTreeNodes.
           * @param e An EventObject.
          public boolean isCellEditable(EventObject e) {
             boolean returnValue = super.isCellEditable(e);
             if (returnValue) {
                WwpJTreeNode node = this.tree.getSelectedNode();
                if (node == null || !node.isEditable() || node.isDragging()) {
                   returnValue = false;
             return returnValue;
       }In my JTree I make these calls:
    super.setCellRenderer(new DeviceTreeRenderer());
    super.setCellEditor(new WwpJTreeCellEditor(this));
    super.setEditable(true);

  • Size of combobox in JTable with custom cell editor

    Hi All -
    I have a JTable that displays a combobox in certain cells. I have a custom table model, renderer, and editor. All of that works fine. I render the combobox with the renderer, and then return the combobox as an editor in the editor so that it can drop down and actually be of use. My problem is - I set the size of the combobox with a setBounds call in the renderer, I add it to a panel, and return the panel - because I dont want the combobox to take up the entire space of the cell. This approach fails in the editor. The setBounds and setSize calls have no effect. As soon as you click the combobox, the editor takes over and all of a sudden the combobox resizes to the entire area of the cell. I assume this is because in the editor you arent actually placing anything - your simply returning the "editing form" of the component.
    So - anybody know of a way to work around this? Worst case, I could just allow the combobox to use the entire area of the cell - but it makes it uglier so I figured I would run it by the forums.
    Eric

    Rather than just redirect you to my previous answer from ages ago, I'll just give it again. :-)
    You can actually do this, but you have to get tricky. By default, the dropdown's width will be the same width as the cell... but it doesn't have to be that way. Essentially what you have to do is override the UI (MetalComboBoxUI) for the combo component. In your new customized UI component subclass (that you set the combo to use), modify the the createPopup() method of this UI class, and add your own logic to set the size of the popup before you return it.
    Ideally the size would be based on the computed max width of a rendered item shown in the combo, but really you could set it to whatever just to see how it works.

  • Cell with boolean value not rendering properly in Swing (custom renderer)

    Hello All,
    I have a problem rendenring boolean values when using a custom cell renderer inside a JTable; I managed to reproduce the issue with a dummy application. The application code follows:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.lang.reflect.InvocationTargetException;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import java.util.logging.Logger;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.SwingUtilities;
    * Simple GUI that uses custom cell rendering
    * @author josevnz
    public final class SimpleGui extends JFrame {
         private static final long serialVersionUID = 1L;
         private Logger log = Logger.getLogger(SimpleGui.class.getName());
         private JTable simpleTable;
         public SimpleGui() {
              super("Simple GUI");
              setPreferredSize(new Dimension(500, 500));
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setLayout(new BorderLayout());
         public void constructGui() {
              simpleTable = new JTable(new SimpleTableModel());
              simpleTable.getColumnModel().getColumn(2).setCellRenderer(new HasItCellRenderer());
              SpecialCellRenderer specRen = new SpecialCellRenderer(log);
              simpleTable.setDefaultRenderer(Double.class, specRen);
              simpleTable.setDefaultRenderer(String.class, specRen);
              simpleTable.setDefaultRenderer(Date.class, specRen);
              //simpleTable.setDefaultRenderer(Boolean.class, specRen);
              add(new JScrollPane(simpleTable), BorderLayout.CENTER);          
              pack();
              setVisible(true);
         private void populate() {
              List <List<Object>>people = new ArrayList<List<Object>>();
              List <Object>people1 = new ArrayList<Object>();
              people1.add(0, "Jose");
              people1.add(1, 500.333333567);
              people1.add(2, Boolean.TRUE);
              people1.add(3, new Date());
              people.add(people1);
              List <Object>people2 = new ArrayList<Object>();
              people2.add(0, "Yes, you!");
              people2.add(1, 100.522222);
              people2.add(2, Boolean.FALSE);
              people2.add(3, new Date());
              people.add(people2);
              List <Object>people3 = new ArrayList<Object>();
              people3.add(0, "Who, me?");
              people3.add(1, 0.00001);
              people3.add(2, Boolean.TRUE);
              people3.add(3, new Date());
              people.add(people3);
              List <Object>people4 = new ArrayList<Object>();
              people4.add(0, "Peter Parker");
              people4.add(1, 11.567444444);
              people4.add(2, Boolean.FALSE);
              people4.add(3, new Date());
              people.add(people4);
              ((SimpleTableModel) simpleTable.getModel()).addAll(people);
          * @param args
          * @throws InvocationTargetException
          * @throws InterruptedException
         public static void main(String[] args) throws InterruptedException, InvocationTargetException {
              final SimpleGui instance = new SimpleGui();
              SwingUtilities.invokeAndWait(new Runnable() {
                   @Override
                   public void run() {
                        instance.constructGui();
              instance.populate();
    }I decided to write a more specific renderer just for that column:
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableCellRenderer;
    * Cell renderer used only by the DividendElement table
    * @author josevnz
    final class HasItCellRenderer extends DefaultTableCellRenderer {
         protected static final long serialVersionUID = 2596173912618784286L;
         private Color hasIt = new Color(255, 225, 0);
         public HasItCellRenderer() {
              super();
              setOpaque(true);
         @Override
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
              int desCol = table.convertColumnIndexToView(1);
              if (! isSelected && value instanceof Boolean && column == desCol) {
                   if (((Boolean) value).booleanValue()) {
                        comp.setForeground(hasIt);     
                   } else {
                        comp.setForeground(UIManager.getColor("table.foreground"));
              return comp;
          * Override for performance reasons
         @Override
         public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {
              // EMPTY
         @Override
         protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
              // EMPTY
         @Override
         public void revalidate() {
              // EMPTY
         @Override
         public void validate() {
              // EMPTY
    } // end classBut the rendering comes all wrong (a String saying true or false, not the expected checkbox from the default renderer) and also there is a weird flickring effect as this particular boolean column is editable (per table model, not show here)...
    I can post the table model and the other renderer if needed (didn't want to put too much code on the question, at least initiallty).
    Should I render a checkbox myself for this cell in the custom renderer? I'm puzzled as I expected the default renderer part of the code to do this for me instead.
    Thanks!
    Edited by: josevnz on Apr 14, 2009 12:35 PM
    Edited by: josevnz on Apr 14, 2009 12:37 PM

    camickr
    Thats because the default render is a JLabel and it just displays the text from the toString() method of the Object in the table model.What I meant to say is that I expected the JCheckbox not a String representation of the boolean value.
    Thats because a different renderer is used depending on the Class of data in the column. Look at the source code for the JTable class to see what the "default >renderer for the Boolean class" is. Then you can extend that or if its a private class then you will need to copy all the code and customize it.At the end I looked at the code and replicated the functionality I needed. I thought than maybe there was a way to avoid replicating the same logic all over again in order to implement this functionality. Good advice, though.
    see you learned nothing from your last posting. This is NOT a SSCCE. 90% of the code you posted is completely irrelevant for the described problem. There is abosutelly no need to post the custom TableModel, because there is no need to use a custom TableModel for this problem. The TableModel has nothing to do with how a column is rendererd.The custom table model returns the type of the column (giving a hint to the renderer on what to expect, right?) and for the one that had a problem it says than the class is Boolean. That's why I mentioned it:
    public Class getColumnClass(int columnIndex) {
        // Code omited....
    You also posted data for 4 columns worth of data. Again, irrelevant. Your question is about a single column containing Boolean data, so forget about the other columns.
    When creating a SSCCE you don't start with your existing code and "remove" code. You start with a brand new class and only add in what is important. That way hopefully if you made a mistake the first time you don't repeat it the second time.That's what I did, is not the real application. I copy & pasted code in a haste from this dummy program on this forum, not the best approach as it gave the wrong impression.
    Learn how to write a proper SSCCE if you want help in the future. Point taken, but there is NO need for you to be rude. Your help is appreciated.
    Regards,
    Jose.

  • JTree Selection Behavior with Custom TreeCellEditor

    I've recently had the need to build a custom TreeCellEditor with a JTree that allows single path selection. I've toyed around with it but don't understand it. When a node is clicked, the editor takes over rendering/handling the cell, and a TreeSelectionEvent is fired from the tree, but the isSelected boolean value passed to the TreeCellEditor is initially false. Then on a second click of the same path in the tree, no TreeSelectionEvent is fired, but the isSelected boolean value is true. It's as if the tree selection is occuring after the editor renders the cell. I would like the cell to appear selected on the first click. Can anyone shed some light on why this is happening and how I can fix it?
    I included some code to demonstrate the problem below (though no actual editing takes place; the test code is only to demonstrate how the cells only appear selected with a yellow background after the second click of the same cell; note also that the valueChanged only executes on the first click). This test was run on Windows with Java 1.5.
    public class TestTreeCellEditor extends JLabel implements TreeCellEditor {
         private String st;
         public TestTreeCellEditor() {
              setOpaque(true);
         public Component getTreeCellEditorComponent(JTree tree, Object value,
                   boolean isSelected, boolean expanded, boolean leaf, int row) {
              this.st = value.toString();
              setBackground(isSelected? Color.YELLOW : Color.WHITE);
              setText(st);
              return this;
         public void addCellEditorListener(CellEditorListener l) {
              // not important for test
         public void cancelCellEditing() {
              this.st = null;
         public Object getCellEditorValue() {
              return st;
         public boolean isCellEditable(EventObject anEvent) {
              return true;
         public void removeCellEditorListener(CellEditorListener l) {
              // not important for test
         public boolean shouldSelectCell(EventObject anEvent) {
              return true;
         public boolean stopCellEditing() {
              return true;
    public class TestTreeCellEditorFrame extends JFrame implements TreeSelectionListener {
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        launchGUI();
         private static void launchGUI() {
              TestTreeCellEditorFrame frame = new TestTreeCellEditorFrame();
              JPanel treePanel = new JPanel();
              DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root node");
              DefaultMutableTreeNode childNode = new DefaultMutableTreeNode("Child 1");
              rootNode.add(childNode);
              childNode = new DefaultMutableTreeNode("Child 2");
              rootNode.add(childNode);
              JTree testTree = new JTree(rootNode);
              testTree.addTreeSelectionListener(frame);
              testTree.setCellEditor(new TestTreeCellEditor());
              testTree.setEditable(true);
              testTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
              treePanel.add(testTree);
              frame.setContentPane(treePanel);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(600,400);
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
         public void valueChanged(TreeSelectionEvent event) {
              TreePath path = event.getNewLeadSelectionPath();
              if (path != null) {
                   DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
                   System.out.println("TreeSelectionEvent on " + node.getUserObject().toString());
    }

    Since my last post, I decided that I do want to be able to edit a cell that is not selected. In particular, when using a tree with checkboxes. What I'm doing for the time being, which works well enough, is to highlight the cell based on the isSelected value in combination with calling tree.stopEditing() in a TreeSelectionListener valueChanged method. This is somewhat of a hack solution, and has the side effect of a cell not appearing selected until the mouseReleased event. I'm still looking for a better solution, but for now it works well enough.

  • Performance decrease with custom cell renderer

    Hi,
    Finally, I have my cell renderer working fine (it was simpler than I thought). Anyway, I'm suspecting something is not working quite well yet. When I try to reorder my colums (by dragging them) they move like slow motion. If I don't register my custom cell renderer, I can move my columns fine. Next is the code of my custom renderer.
    class PriorityRenderer extends DefaultTableCellRenderer {   
      public Component getTableCellRendererComponent(
      JTable table, Object value,     boolean isSelected,
      boolean hasFocus, int row, int column) {              
        if(value instanceof coloredValue) {
        coloredValue cv = (coloredValue)value;
        if(isSelected) this.setBackground(table.getSelectionBackground());
        else this.setBackground(cv.getbkColor());
        this.setForeground(cv.gettxColor());
        this.setText(value.toString());
        this.setOpaque(true);
        return this;
    }All the cells of my JTable are "coloredValue"s. This is a little class with a String, two colors and some getter methods.
    Can anyone giveme a hint ?
    Thanks!!

    OK! Now the performance problem is gone!! (I don't know why, I didn't touch a thing)
    Thanks anyway

  • JTable custom renderer never calls getTableCellRendererComponent()

    I have a custom renderer for Dates in my JTable. I've set it as the renderer on Date columns and I've also tried setting it as the table default for the Date type. In both cases the getTableCellRendererComponent() method never gets called.
    I've also tried right-justifying String columns with
              DefaultTableCellRenderer renderer = (DefaultTableCellRenderer)table.getDefaultRenderer(String.class);
              renderer.setHorizontalAlignment(JLabel.RIGHT);
    but the Strings are always left-justified. Same with integers.
    I verify that the new renderer / alignments are actually set immediately after setting them. A few method calls later I notice that the alignments have changed back. My custom date renderer is still set, however.
    My code calls fireTableStructureChanged(). I set/reset all renderers after the call to fireTableStructureChanged(). I wonder if fireTableStructureChanged() rebuilds the table some teim later wiping out the renderer / alignments that I've set and replacing them with the defaults.
    Is there a callback or some method that I need to override after calling fireTableStructureChanged() in order to get my renderer / alignments to remain in effect?

    I can't post the code because it is proprietary and the application itself is large.
    The trouble seems to start when I call fireTableStructureChanged(). None of the toy examples in books that I've seen address fireTableStructureChanged(). The JavaDocs for Swing don't tell you about all of the side effects of fireTableSTructureChanged().
    You're comment about overriding getColumnClass() got my custom data renderer working. The Javadocs for DefaultTableModel and JTable don't mention when you need to override getColumnClass(). Overriding getColumnClass() in the TableModel seems to apply to JTable as well. I don't understand why, but it seems to work.
    I am able to justify my columns be creating a default renderer and calling setHorizontalAlignment() on it and setting it as the default for the JTable. The code below doesn't work, however:
    DefaultTableCellRenderer renderer = (DefaultTableCellRenderer)table.getDefaultRenderer(int.class);
    renderer.setHorizontalAlignment(JLabel.RIGHT);
    It seems that the default renderers reset themselves back to their default state. I have no idea why, but that is what I am seeing.
    There is also a big difference in the way that primitives and wrappers are handled (i.e. int compared to Integer).
    One of the other posters here said that if I call setModel() that I would have to reset the renderers. The Javadocs don't say anything about that. (I only call setModel during initialization. I do update the actual data in the TableModel which can change the structure of the table. That is when I call fireTableStructureChanged() and all the difficulties start.)
    This whole episode has shown that the Swing Javadocs are next-to-worthless for writing real-world Swing applications. I've written several Swing applications over the years, and once they get beyond the simple level they become difficult to write and maintain due to the lack of documentation. For my next Java GUI I'm going to check out JavaFX (as soon as it is available on Linux). I don't see how it could be worse than Swing.
    Thanks for all of your help. You got me on the path to getting this solved.

  • Proble with Custom JTable Header

    Hi
    I want create Custom JTable with JTextField on column header, so that user can enter some text. As of now i am able to create the text box on header using custom TableCellRenderer but i am not able to make it editable.....
    Please help me. if any one need more info, pls let me know.

    KetuRai wrote:
    Then what should i do to achieve this functionality. Do any one have sample code?
    Or other alternative to achieve this.I don't know If this is the best way but my approach is using a InputDialog and a custom renderer.
    just click on the table header and input a text. Good Luck!
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    public class TableHeaderDemo {
        public void createAndShowUI() {
            JFrame frame = new JFrame("Click Table Header to change text");
            String[] columnName = {"CheckBox Column", "Data Column"};
            Object[][] data = {{"Data 1", "Data 2"},
            {"Data 3", "Data 4"}, {"Data 5", "Data 6"}};
            final JTable myTable = new JTable(data, columnName);
            myTable.getTableHeader().setDefaultRenderer(new MyRenderer());
            myTable.getTableHeader().addMouseListener(new java.awt.event.MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    int col = myTable.getTableHeader().columnAtPoint(e.getPoint());
                    String str = javax.swing.JOptionPane.showInputDialog("Enter a text: ");
                    myTable.getColumnModel().getColumn(col).setHeaderRenderer(new MyRenderer(str));
                    myTable.getTableHeader().revalidate();
                    myTable.getTableHeader().repaint();
            JScrollPane scrollPane = new JScrollPane(myTable);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setResizable(false);
            frame.getContentPane().add(scrollPane);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        class MyRenderer implements TableCellRenderer {
            JTextField text = new JTextField();
            MyRenderer(String str) {
                text.setText(str);
            MyRenderer() {
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column) {
                text.setBorder(BorderFactory.createRaisedBevelBorder());
                text.setBackground(Color.BLUE);
                text.setForeground(Color.WHITE);
                text.setHorizontalAlignment(JTextField.CENTER);
                return text;
        public static void main(String[] args){
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new TableHeaderDemo().createAndShowUI();
    }

  • JTable Custom Renderer not working after sort

    Hi All,
    I have a JTable which has a default renderer. The point of the renderer is to color the background based on the second column.
    It all words fine, until I sort by any of the columns. Clicking on a column header sorts, but the original background color remains.
    The JTable was created with a class that extended DefaultTableModel.
    Any help or ideas would be appreciated.
    Thanks.
    table.setDefaultRenderer(Object.class, new MyColorCellRenderer());
    public class MyColorCellRenderer extends javax.swing.table.DefaultTableCellRenderer {
            public MyColorCellRenderer() {
                setForeground(Color.white);
                setOpaque(true);           
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {                   
                Component comp = super.getTableCellRendererComponent(
                         table,  value, isSelected, hasFocus, row, column);
                String s = table.getModel().getValueAt(row, 1).toString();
                if (s.equalsIgnoreCase("Man")) {
                    comp.setBackground(Color.red);
                } else if (s.equalsIgnoreCase("Woman")) {
                    comp.setBackground(Color.orange);
                } else if (s.equalsIgnoreCase("Child")) {
                    comp.setBackground(Color.lightGray);
                } else if (s.equalsIgnoreCase("Pet")) {
                    comp.setBackground(Color.darkGray);
                } else {
                    comp.setForeground(null);
                return (comp);
        }Edited by: PeterG on Sep 23, 2008 7:54 AM

    Absolutely correct and fantastic!
    Thank you very much.
    New code below.
    public class MyColorCellRenderer extends javax.swing.table.DefaultTableCellRenderer {
            private JTable m_Table;
            public MyColorCellRenderer(JTable table) {
                m_Table = table;
                setForeground(Color.white);
                setOpaque(true);           
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {                   
                Component comp = super.getTableCellRendererComponent(
                         table,  value, isSelected, hasFocus, row, column);
                String s = table.getModel().getValueAt(m_Table.convertRowIndexToModel(row), 1).toString();
                if (s.equalsIgnoreCase("Man")) {
                    comp.setBackground(Color.red);
                } else if (s.equalsIgnoreCase("Woman")) {
                    comp.setBackground(Color.orange);
                } else if (s.equalsIgnoreCase("Child")) {
                    comp.setBackground(Color.lightGray);
                } else if (s.equalsIgnoreCase("Pet")) {
                    comp.setBackground(Color.darkGray);
                } else {
                    comp.setForeground(null);
                return (comp);
    }

Maybe you are looking for

  • Problems opening applications

    Hello! I have been reading tutorials on using the mac book. When I tried opening an application it just bounced up and down in the dock. The applications I tried are font book, dictionary, calculator, ichat and even dashboard. Consequently they are j

  • Document Templates in MS Word (Office-Integration)

    Hi there, i´m desperately looking for help concerning the following problem with integration of MS Word-Templates to our CRM: We are using CRM 5.0 (as well as PCUI) and Office Integration with MS Word 2003. We created Document Templates (for Object T

  • Cropping with rounded corners

    I am preparing portrait images to be put on a page. I would like to use the cropping tool to a specific size and end up with rounded corners on the image. How can this be done? Thanks, Mary Lou

  • ACL error when sending email from Oracle 11g

    Hi, It returned something like "error...ACL security" when I tried to send email from Oracle 11g. Is there any security thing that I need to release in Oracle 11g? I used to send emails from Oracle 10g and didn't find any problem. Thanks. Andy

  • Task List - Create New Form for Subtasks

    Hi, Is this possible to create a new form for SubTasks in SharePoint 2013 task List probably using Infopath. Out of Box, Sharepoint opens datasheet view to add the subtask for a main task. just want to know whether it is possible. Any help will be hi