JTree as cell renderer for JList

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

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

Similar Messages

  • Custom Cell Renderer for JList

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

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

  • Setting a cell renderer for a Cell?

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

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

  • A different cell renderer for the root node ??

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

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

  • JTree custom cell renderer question

    When using a custom cell renderer is their anyway to tell the offset of the current node?
    For example if you have a tree with the parent node "Parent" that has a few children nodes it will look something like this:
    Parent
    |----Child 1
    |----Child 2
    |----Child 3
    So the parent would have an offset of zero. I want to know how to get the childrens offset? If this is possible?
    What I am trying to accomplish:
    I have a JTree as a scrollpane rowHeader. While the main body of the scrollpane is a JTable. I need the tree's nodes to fill the entire width so that it looks like part of the table. I figure the row header width - current node offset should be the width that I will need each node to be. Any help is welcome. Thanks.

    the renderer tells you the row, the tree can get you a treepath for a row
    TreePath getPathForRow(int row)
    That can tell you the depth of the node.

  • Facing problem in using JEditorPane as renderer for JList

    I am trying to use JEditorPane as renderer for a list. But I am facing some problems. First problem is the output in the editorpane is not shown properly. I want to show a html file, but only portion of the first line that is viewable in the editorpane is shown. I, of course, need to show the total content of the file. Again sometimes the editorpane looks blank. If I click on the list then some text are shown in the editor pane. Please help me to overcome these problems.
    Here goes the code for the renderer.
    list.setCellRenderer(new ListCellRenderer() {
                private JEditorPane editor = new JEditorPane();
                public Component getListCellRendererComponent(JList mList, Object value, int index,
                                                            boolean isSelected, boolean hasFocus) {
                    try {
                        editor.setPage("file://localhost/C:/networks/network1/description.html");
                        editor.setBackground(isSelected ? mList.getSelectionBackground() : mList.getBackground());
                        editor.setForeground(isSelected ? mList.getSelectionForeground() : mList.getForeground());
                        editor.setBorder(BorderFactory.createRaisedBevelBorder());
                        editor.setOpaque(true);
                    } catch(Exception e) {
                        e.printStackTrace();
                    return editor;
            });

    hai ahmad,
    it could be bcoz of the size of the pane.... the size content might be too large to fit in that pane....... y dont u increase the width of the pane..
    or set the size of the pane..... its surely bcoz of the size only....
    hope this helps u...... or else revert back for further clarifications...
    Regards,
    Ciya.

  • Custom Cell Renderer for JTable

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

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

  • Setting Table Cell Renderer for a row or cell

    I need to make a JTable that has the following formats:
    Row 1 = number with no decimals and columns
    Row 2 = number with no decimals and columns
    Row 3 = percent with 4 decimals
    I can use a table cell renderer to set each COLUMN as one or the other formats like this:
    NumDispRenderer ndr = new NumDispRenderer();
    for(int i = 1;i<dates.size();i++) {
    table.getColumnModel().getColumn(i).setCellRenderer(ndr);
    Where NumDispRenderer is a class as follows:
    public class NumDispRenderer extends DefaultTableCellRenderer {
    public Component getTableCellRendererComponent (JTable table, Object value,boolean isSelected, boolean isFocused, int row, int column) {
    Component component = super.getTableCellRendererComponent (table,value,isSelected,isFocused,row,column);
    if (value != null && value instanceof Double) {
    DecimalFormat df = new DecimalFormat("###,###");
    String output = df.format(value);
    ((JLabel)component).setText(output);
    ((JLabel)component).setHorizontalAlignment(JLabel.RIGHT);
    } else {
    ((JLabel)component).setText(value == null ? "" : value.toString());
    return component;
    This is fine for the first two rows, but the third row (which is also an instance of Double) I would like to format differently.
    The tutorial and other postings have not given a solution to this problem. Any suggestions would be very appreciated.

    Hi,
    the method getTableCellRendererComponent() of your renderer gets the row as a parameter. So just create the label depending on that value. For 0<=row<=1 you create the label as is, and for row=2 you create another label with the Double formatted as you wish.
    Andre

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

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

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

  • Skinning Cell Renderer for ComboBox

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

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

  • JTable custom cell renderer for each cell

    Hi,
    Iam trying to implement a JTable in which each cell in a column can be of a different type. i.e it can be a tree node or plain text. Can someone point me to examples where this has been done.
    Iam trying to override getColumnClass but it only takes a column no as parameter. I would like to return a different type depending on the row for which getColumnClass is called. It would help if getColumnClass could take 2 params (row and column). Can someone help.
    Cheers,
    vidyut

    You can override getCellRenderer(int row, int column) of JTable

  • How to build a custom movie clip that will be used as a cell renderer for column in a grid ?

    i want to build a datagrid that shows a picture and underneath it a name.
    the problem is i dont want to see all of the pictures, but all the pictures that have certain requirements, so i cant just make one movie clip that includes all the pictures and names.
    so my question is how do i build a movie clip that contains photo and text?.

    You do not create movieclips on the timeline using code, though you can create them and add them as children of something that has been manually placed in the timeline.
    To create a MovieClip using code you use: 
        var mc:MovieClip = new MovieClip();
    If you need to add an image, then however you intend to acquire the image, after it has been acquired, you add it to the MovieClip using:  
        mc.addChild(img); 
    where img is the instance of whatever form of object the image takes (Bitmap, Loader)
    If you need to add a TextField to the MovieClip then you use: 
        var tf:TextField = new TextField();
        mc.addChild(tf);
    and you can set up properties for the textfield such as the font and color and position as well after it has been instantiated (the first line).

  • Custom cell Renderer for datagrid

    For a long while now (way too long) I've being searching for
    a decent example for using components such as a checkbox or
    combobox inside of a datagrid.
    The only examples that i could find where all AS2 examples.
    The closest thing I find to an AS3 example for adding checkboxes,
    buttons etc to a datagrid was here
    http://www.adobe.com/devnet/flash/quickstart/datagrid_pt3/
    but it is in no way clear how to alter the example for other
    components.
    Could somebody please please please show me a working example
    of how to add a checkbox / button to a datagrid using flash cs3

    TypeError: Error #2007: 参数 text
    不能为空。
    at flash.text::TextField/set text()
    at fl.controls::LabelButton/set label()
    at xttmo::MyRowBgColorRender/set listData()
    at fl.controls::DataGrid/drawList()
    at xttmo::MyDataGrid/drawList()
    at fl.controls::DataGrid/draw()
    at fl.core::UIComponent/callLaterDispatcher()
    TypeError: Error #1009:
    无法访问空对象引用的属性或方法。
    at fl.controls::ComboBox/addCloseListener()
    TypeError: Error #2007: 参数 text
    不能为空。
    at flash.text::TextField/set text()
    at fl.controls::LabelButton/set label()
    at xttmo::MyRowBgColorRender/set listData()
    at fl.controls::DataGrid/drawList()
    at xttmo::MyDataGrid/drawList()
    at fl.controls::DataGrid/draw()
    at fl.core::UIComponent/callLaterDispatcher()
    TypeError: Error #1009:
    无法访问空对象引用的属性或方法。
    at fl.controls::ComboBox/close()
    at fl.controls::ComboBox/focusOutHandler()
    TypeError: Error #2007: 参数 child
    不能为空。
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::BaseButton/draw()
    at fl.core::UIComponent/callLaterDispatcher()
    package xttmo{
    import fl.controls.CheckBox;
    import fl.controls.listClasses.ICellRenderer;
    import fl.controls.listClasses.ListData;
    import flash.display.Graphics;
    import flash.display.Shape;
    import flash.events.MouseEvent;
    import flash.events.Event;
    import fl.core.InvalidationType;
    public class MyCheckboxRender extends CheckBox implements
    ICellRenderer {
    private var _data:Object;
    private var _listData:ListData;// column row
    protected var textOverlay:Shape;
    override public function dispatchEvent(event:Event):Boolean
    if (event.type==MouseEvent.CLICK) {
    setSelected1();
    return super.dispatchEvent(event);
    public function MyCheckboxRender():void {
    super();
    this.label="";
    this.move(0, 0);
    this.setSize(23, 22);
    var _t:MyCheckboxRender=this;
    this.addEventListener(MouseEvent.CLICK,
    function(e:MouseEvent):void{;
    _t.setSelected1();
    public function set data(item:Object):void {
    _data=item;
    // name = "sex";
    public function get data():Object {
    return _data;
    /*override public function set selected(value:Boolean):void
    {// this._selected=value;
    public function setSelected1():void {
    this._selected=Boolean(! this._selected);
    public override function get selected():Boolean {
    invalidate(InvalidationType.STATE);
    return _selected;
    private function myDraw():void {
    graphics.lineStyle(1, 0xB7BABC);
    var h:uint=19;// height;
    graphics.moveTo(0, -1),
    graphics.lineTo(0, h);
    graphics.lineTo(width, h);
    this.textField.text=_data["sex"];
    this._selected=Boolean(1==_data["sex"]);
    public function set listData(item:ListData):void {
    _listData=item;
    myDraw();
    public function get listData():ListData {
    return _listData;
    override protected function drawBackground():void {
    if (_listData.index%2==0) {
    setStyle("upSkin", CellRenderer_upSkinGray);
    } else {
    setStyle("upSkin", CellRenderer_upSkin);
    super.drawBackground();

  • Changing JList cell renderer on selection

    Hi,
    In our application we need to change the renderer of the selected cell of JList to JTextArea while maintaining default cell renderer for unselected cells. I tried by providing custom cell renderer (code is given below) but it does not work..:-(. Though the component used by JList for rendering the cell is JTextArea, the height of the cell remains same as that of unselected cells. Our requirement is to change the cell height of the selected row so as to give a feel that selected row expands and shows some more information about the selected item to the user.
    Here is the code snippet of the cell renderer that I wrote:
    class CellRenderer1 extends DefaultListCellRenderer{
    private JTextArea selTxtArea;
    CellRenderer1() {
    selTxtArea = new JTextArea(3,20);
    this.setOpaque(true);
    public Component getListCellRendererComponent(JList list,
    Object value, int index,
    boolean isSelected, boolean cellHasFocus) {
    String name = (String) value;
    if ( isSelected ) {
    selTxtArea.setBackground(list.getSelectionBackground());
    selTxtArea.setForeground(list.getSelectionForeground());
    selTxtArea.setText(name + "\n" + name);
    return selTxtArea;
    else {
    this.setBackground(list.getBackground());
    this.setForeground(list.getForeground());
    this.setText(name);
    return this;
    //return this;
    Any pointers or help will be highly appreciated.
    Thanks
    Atul

    JList calculates fixedCellHeight and then uses the same for every cell. This was causing the problem. By overriding the getRowHeight method of BasicListUI class I was able to achieve different cell heights for selected and unselected rows. Following is the code snippet which shows how this was achieved:
    protected int getRowHeight(int row) {
    if ( (cellHeights == null) || (cellHeights.length < row )) {
    cellHeights = new int[row];
    ListModel model = list.getModel();
    Object value = model.getElementAt(row);
    ListSelectionModel selModel = list.getSelectionModel();
    boolean isSelected = selModel.isSelectedIndex(row);
    Component comp = list.getCellRenderer().
    getListCellRendererComponent( list, value, row,
    isSelected, false);
    Dimension dim = comp.getPreferredSize();
    int height = dim.height;
    cellHeights[row] = height;
    return cellHeights[row];
    }

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

Maybe you are looking for

  • IMac Hardware Advice

    So I've decided to buy a new iMac (27 inch) in the next few weeks- Can anyone suggest a good hardware configuration? When buying the computer, they list a few customization options here: http://store.apple.com/us/buy-mac/imac?product=ME089LL/A&step=c

  • WriteMultiSamplePort is slow

    Using WriteMultiSamplePort() (in C# and .NET3.5) to output an array of ints to the 4 digital output lines of a USB-6211 is very slow. (It's thankfully a lot faster than my first attempt, which used WriteSingleSampleSingleLine() in nested loops .) The

  • Error exception

    Hi Gurs, I am getting this error. Can any one tell me how can solve this error The following error text was processed in the system E60 : Exception condition "DATE_INVALID" raised. The error occurred on the application server sapecc6ides_E60_01 and i

  • Can not copy a file larger then 4 GB in to usb driver

    I have the AirPort Extreme (802.11n) and have a usb driver connected on it. every time i wanna copy a large file say 4GB one, it just won't , and show me a error says the network connection problem.

  • I cant find my ipod

    I cant find my ipod touch