Flattening a JTreeTable to a JTable

Has anybody done something along the following lines...
Taking a JTreeTable that looks like this:
Parent 1
                Child 1
                Child 2
                Child 3
Parent 2
                Child 4
                Child 5
and converting into a JTable that looks like this:
Parent 1        Child 1
Parent 1        Child 2
Parent 1        Child 3
Parent 2        Child 4
Parent 2        Child 5

Hi,
I need some help regarding the same.I need to show the Jtree in two columns.The first level of the root in one column and the children of these in second column.The nodes in the second column will have their children shown in second column.
Thanks in Advance

Similar Messages

  • Custom Renderers in JTreeTable (or extending JTable)?

    I am wondering about what the best approach is to display a table in a Swing component. My table will by default have all rows collapsed (occupying a single line), but someone may click on a row to expand it (so it occupies multiple lines and displays more information). Nothing in the table should be editable.
    Example:
    (collapsed) 1. data     data     data
    (expanded) 2. data     data     data
    ...more data that wouldn't fit on on one line...
    ... still more data (additional data doesn't have same column format as collapsed rows)...
    (collapsed) 3. data     data     dataSo the additional data displayed when a row is expanded aren't conceptually `children' of the data in the collapsed display. I've looked at JTreeTable, but I'm not sure it's right for this purpose, and it seems complicated.
    For one thing, I need some of my columns to have custom renderers--for example, renderers that display a button with text or an image instead of just a label. However, it looks like the JTreeTable approach forces you to declare the JTree (extension) as the renderer of everything in a row, so would that prevent me from specifying custom renderers for other columns, or am I misunderstanding?
    Another feature I need is to be able to filter out entire rows from the view (so they don't show up at all). I will also want to add custom sort buttons that can apply four different sorts to each column.
    Would I be better off using a JTreeTable for this or somehow using custom renderers or otherwise extending an ordinary JTable to make the column larger and display additional information when the user clicks the expand icon?
    Also, how do I specify a different renderer for header rows than for other rows?
    Message was edited by:
    The.Joy.of.Java

    Check how editingStopped is being done. For a ComboBox there is no common operation that one can assume means that the user is done with the editing component. By default JTable leaves it active until the mouse clicks somewhere outside it, then does, essentially, fireEditingStopped() to give the cell back to the renderer. Then a second mouse click is required to start a new cell editor.
    If you're using ComboBox as a custom editor, you have to decide what event you want to be final and call fireEditingStopped() yourself. For instance, in your TableCellEditor:
        @Override
        public Component getTableCellEditorComponent(final JTable table,
                                                     final Object value,
                                                     final boolean isSelected,
                                                     final int row,
                                                     final int column) {
    ...             if( editor.supportsCustomEditor() )  {
                        JComboBox c = (JComboBox)editor.getCustomEditor();
                        c.removeActionListener( this );
                        c.addActionListener( this );
                        return c;
        @Override
        public void actionPerformed ( final ActionEvent ev ) {
            else if( "comboBoxChanged".equals( ev.getActionCommand() ) )  {
                fireEditingStopped();
        }The actionEvent is fired when just about anything happens in the ComboBox, including selection of the currently selected item. But unless you have a more specific requirement, it should be good enough.

  • Using JTreeTable as a Bean

    Hi,
    I've been looking at the JTreeTable class available at:
    http://java.sun.com/products/jfc/tsc/articles/treetable1/
    This is not a standard Swing component but I'd like to use it as a Bean so that I can load it into my NetBeans IDE. Problem is there does not appear to be a means to set the model (for tree and table) other than using the constructor that takes a TreeTableModel parameter.
    Has this been done before? Any help is appreciated.
    Thanks,
    Derek.

    Mabe you also should rewrite the other constructor:
    public JTreeTable(TreeTableModel treeTableModel) {
         super();
            setTreeTableModel(treeTableModel);
            // Installs the tree editor.
            setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor());
         // No grid.
         setShowGrid(false);
         // No intercell spacing
         setIntercellSpacing(new Dimension(0, 0));     
    public void setTreeTableModel(TreeTableModel treeTableModel){
         // Creates the tree. It will be used as a renderer and editor.
         tree = new TreeTableCellRenderer(treeTableModel);
         // Installs a tableModel representing the visible rows in the tree.
         super.setModel(new TreeTableModelAdapter(treeTableModel, tree));
         // Forces the JTable and JTree to share their row selection models.
         ListToTreeSelectionModelWrapper selectionWrapper = new
                                 ListToTreeSelectionModelWrapper();
         tree.setSelectionModel(selectionWrapper);
         setSelectionModel(selectionWrapper.getListSelectionModel());
         // Installs the tree renderer
         setDefaultRenderer(TreeTableModel.class, tree);
         // And update the height of the trees row to match that of
         // the table.
         if (tree.getRowHeight() < 1) {
             // Metal looks better like this.
             setRowHeight(20);
        public TreeTableModel getTreeTableModel(){
          return getModel();
        }Something like this. Didn't test it!
    -Puce

  • Cell alignment in JTreeTable

    hi,
    how can i set alignment of a cell in a JTreeTable?

    i have the following renderer :
    public class TreeTableCellRenderer extends JTree implements TableCellRenderer,SwingConstants
    protected int visibleRow;
    public TreeTableCellRenderer(TreeModel model) {
    super(model);
    public void setBounds(int x, int y, int w, int h) {
    super.setBounds(x, 0, w, JTreeTable.this.getHeight());
    public void paint(Graphics g) {
    g.translate(0, -visibleRow * getRowHeight());
    super.paint(g);
    public Component getTableCellRendererComponent(JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus,
    int row, int column) {
    if(isSelected)
    setBackground(table.getSelectionBackground());
    else
    setBackground(table.getBackground());
    visibleRow = row;
    return this;

  • JTreeTable and LookandFeel

    Hi, All
    Currently I have some troubles with subj.The main problem -- painting time of the tree/table cells.Best perfomance in "standard" java L&F,after Win L&F and at least Motif. I'm not sure but think that is trouble of L&F.I amcorrect?
    and one more.May be somebody know examples of using JTreeTable classes.
    Thank to all.

    I have figured out why JTreeTable is not working with Motif L&F.
    The row hieght of the JTable has to be adjusted for Motif. You may use
    the following code in the JTreeTable contructor.
    // And update the height of the table row to match that of the tree.
    int rowHeight = UIManager.getInt("Tree.rowHeight");
    if (rowHeight > 0) {
    setRowHeight(rowHeight);
    } else {
    if (tree.getRowHeight() < 1) {
    // Metal looks better like this.
    setRowHeight(20);

  • Problem when printing JTreeTable

    Hi,
    I've datas wich i display in a JTable or in a JTreeTable (see http://java.sun.com/products/jfc/tsc/articles/treetable1/ ).
    Now, i'd like to print the JTable or the JTreeTable, i use the code i've found here : http://developer.java.sun.com/developer/onlineTraining/Programming/JDCBook/advprint.html .
    There was a bug ( see http://forum.java.sun.com/thread.jsp?forum=57&thread=263303 ).
    The JTable prints itself very fine but i've two problems with the JTreeTable :
    1) I've always some last rows on a page and on the next page, even if i include the table.getRowMargin() or not.
    2) Almost all the node are printed with "...", for instance : TRES -> TR... although they are well displayed on screen.
    It doesn't depend on the width of the column and i can't know how Swing decide or not to display the "..." (for instance, i've "C..." and "CR..." but they are at the same x-location with the same icons, the same font and the same font's size; just not the same number of caracters)
    I don't post any code because it's long, it's just a mix between the links.
    Any help would be great before i kill hundreds of tree.
    Thanks in adavance.
    Fade.

    Hi Fade,
    I am having the same problem in printing a JTreeTable. The nodes of the JTree are getting clipped and are followed by ellipsis(...). A similar problem occurs for the other table columns, if the column separators(borders) are closely aligned with the text. It seems that the space required for rendering the components within the table, is more while printing. The problem is more prominent in case of the tree nodes. In case you have found a solution for the same, it would be nice if u could help me with it. Or if there's any one out there who could be of help, pls. reply.
    Thanx.

  • JTreeTable rendering problems

    Hi all!
    I have used some clesses to create a JTable containing a JTree, basing on the example in the sun's site. The costructor is:
    JFrame frame = new JFrame("TITLE");
    JTreeTable table = createTable(); //Creates the treetable
    JScrollPane scrollPane = new JScrollPane(table); //it puts the newly created table in a scrollPane
    frame.getContentPane().add(scrollPane,BorderLayout.CENTER);
    frame.pack();
    frame.show();
    I have the following problems:
    1. If I have not many nodes in the tree, I have a bad renderer effect: the table doesn't fit the whole window but just the upper part of that, at the bottom it's all gray (the JFrame color, I think).Even if I set the JFrame background color to white, I still have that problem.
    2. If I don't add the table to the scrollbar, I can't see the headers, but I don't have the problem of the gray panel.
    Does anyone know how I can work out this? Has anybody examples of JTreeTables that don't have this rendering problem (with the table fitting the whole window even though they don't have many nodes)?
    Feedbacks are welcome, this is really showstopper for me...
    Thanks a lot!

    Hi there.
    Try setting the viewport color of your scrollpane. I don't have my API's on hand but you go something like myScrollPane.getViewport().setBackgroundColor(Color.white);
    How does that go for you?
    Cheers,
    Rachel

  • Help with JTreeTable custom cell renderer!

    Hi.
    I've followed diligently the complete TreeTable2 example found on the Sun site. http://java.sun.com/products/jfc/tsc/articles/treetable2/
    What I'm trying to do is to add alternate-row shading on the Column(0) of the JTreeTable where the Column class is "TreeTableModel".
    so, from the example, I've added the following setCellRenderer declaration to TreeTableExample2.java:
         protected JTreeTable createTreeTable() {
              JTreeTable       treeTable = new JTreeTable(model);
              treeTable.getColumnModel().getColumn(1).setCellRenderer
              (new IndicatorRenderer());
              treeTable.getColumnModel().getColumn(0).setCellRenderer
              (new MyTableCellRenderer());Then, I subclass DefaultTableCellRenderer as shown below, in a new class called "MyTableCellRenderer"
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    public class MyTableCellRenderer extends DefaultTableCellRenderer implements TableCellRenderer
         private static final long serialVersionUID = 1L;
         public MyTableCellRenderer() {
         public Component getTableCellRendererComponent(JTable jtable, Object obj, boolean isSelected, boolean hasFocus, int i, int j)
              if (i % 2 == 0 && !isSelected) {
                   this.setBackground(new Color(214,226,255));
                   this.setForeground(Color.BLACK);
              } else if (isSelected)
                   this.setBackground(new Color(204, 204, 255));
              else {
                   this.setBackground(Color.white);
              //if (obj != null)
              this.setValue(obj.toString());
              System.out.println("obj: " + obj.toString());
              System.out.println("obj type: " + obj.getClass().getName());
              return ((Component) (this));
    }I've been pulling out whatever few hairs I have left in my sparse scalp to get this working, but it's looking grim thus far.
    Here are links to screenshots of my progress, or lack thereof:
    Original Working TreeTable II
    http://www.pharmalytix.com/original_treetable.jpg
    My Not-working Tree Table II w/ Custom Cell Renderer
    http://www.pharmalytix.com/customtablecellrenderer_treetable.jpg
    thanks again - !!

    phew! finally got this sucker working. I had to retrieve the default rendererer of my TreeTable's TreeTableModel class column, which is the JTree and then, in its component-form, start mucking about with its stylings. The real black-hole of progress was caused by my brain imploding from not being able to understand that a "Component" was what represented the "thing" whose behaviour I wanted to alter, be it a Jtree node or Jtable cell.
              treeTable.getColumnModel().getColumn(0).setCellRenderer(new TableCellRenderer() {
                   public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
                        Component comp = treeTable.getDefaultRenderer(TreeTableModel.class).getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
                        if (row % 2 == 0 && !isSelected) {
                             comp.setBackground(new Color(214,226,255));
                             comp.setForeground(Color.BLACK);
                        } else
                             if (isSelected)
                                  comp.setBackground(new Color(204, 204, 255));
                             else {
                                  comp.setBackground(Color.white);
                        return comp;
              });In all of its ravishing glory:
    http://www.pharmalytix.com/alternateshading_treetable.jpg
    Edited by: DataHog on Nov 6, 2007 10:21 AM

  • JTreeTable+add a password field in it

    Hi All
    I was successful in writing a code for JTreeTable but now I want to add a password field in it which is editable by the users.
    Any help would be appreciated...
    Thanks
    apoorva

    Sorry for the long code that I pasted.
    My issue is this :
    a) I created a renderer and editor for having one column act as a password field.When I used this renderer and editor in a simple JTable it worked well but when i added the same to my JTreeTable code the editor worked fine(I guess!!!) cos when I typed something it showed as hidden characters but on hitting enter key the value would disappear (the renderer messing it up I guess!!! ) :(
    Here is my renderer and editor for JPasswordField
    public static class PasswordTableCellRenderer extends JPasswordField implements TableCellRenderer
    public Component getTableCellRendererComponent(
    JTable table,Object value, boolean isSelected, boolean hasFocus, int row,
    int column) {
    setText((value ==null) ? "" : value.toString());
    return this;
    public class MyEditor extends DefaultCellEditor
    public MyEditor(){super(new JPasswordField());}
    }b) Also the model I use for the JTreeTable extends AbstractTableModel and hence I override the getValueAt() method. I am not understanding how renderer/editor works with this getValueAt() method.
    Hope I am a little clearer this time
    Thanks
    apoorva
    Edited by: apugupt on Jun 20, 2008 8:16 PM

  • Simulate JTreeTable

    Hi,
    I have a leftward JPanel with a JTree in it and a rightward JTabbedPane in which one of the components is a JTable. the JTree and the JTable act most like a JTreeTable, but they are in diffrent components.
    Is there any easy way to finish the base function, for example, line up node of JTree and row of JTable?
    Thanks.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class Test extends JFrame {
      JTree tree = new JTree();
      String[] head = {"One"};
      String[][] data = {{"DD"}};
      DefaultTableModel dtm = new DefaultTableModel(data,head);
      JTable table = new JTable(dtm);
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        JSplitPane jsp = new JSplitPane();
        jsp.setDividerLocation(150);
        content.add(jsp, BorderLayout.CENTER);
        jsp.add(new JScrollPane(tree), JSplitPane.LEFT);
        tree.addTreeExpansionListener(new TreeExpansionListener() {
          public void treeExpanded(TreeExpansionEvent te) { refreshTable(); }
          public void treeCollapsed(TreeExpansionEvent tse) { refreshTable(); }
        jsp.add(new JScrollPane(table), JSplitPane.RIGHT);
        setSize(500, 300);
        show();
      private void refreshTable() {
        while (dtm.getRowCount()>0) dtm.removeRow(0);
        int rows = tree.getRowCount();
        for (int i=0; i<rows; i++) {
          Object[] obj = { tree.getPathForRow(i).getLastPathComponent() };
          dtm.addRow(obj);
      public static void main(String[] args) { new Test(); }
    }

  • Where to consume expansion click in JTreeTable?

    Hi!
    I have the following question concerning a JTreeTable (tried it with the classic TreeTableExample2 from http://java.sun.com/products/jfc/tsc/articles/treetable2/index.html ) :
    I want that whenever I click an expand/collapse button of the Tree either the JTable does not change the selection or it does not call my ListSelectionListeners. Where do I have to consume the mouse event on the button so that the JTable does not react? is it possible at all?
    thanks,
    Nils

    To install javascripts in Bridge go to the app preferences and select startup scripts from the list…
    You will then see a button if you click that your folder is revealed… Just pop them in that and restart the app…
    You may be prompted to add new at restart of the app…

  • JComboBox in JTreeTable

    One column in my JTreeTable (or JTable, doesn't matter) is a JComboBox. If it's a Checkbox the cell must be a "Boolean" and it's selected automatically if it's true. If I have a JLabel of JTextField the cell must be a String.
    But how do I set the selectedIndex of the ComboBox from my DataTable? For Instance:
    The ComboxBox has the items: "Michael", "Peter" and "Paul". The Cell is a String and is "Peter".
    What do I have to do in my ColumnModel that the ComboxBox for that cell shows "Peter". For all rows is always the first item visible.
    Thank you
    Jonas

    hi
    this is one link u can refer
    http://www.codeguru.com/java/articles/185.shtml
    http://www.devx.com/premier/mgznarch/javapro/2001/01jan01/vc0101/vc0101.asp
    i have tried first link that works fine
    Hope this helped u
    Renjith

  • JTable with custom cell for folding and unfolding rows

    Hi,
    I am trying to implement a JTable, whereas one of the columns is a custom component, which has a small + in the right upper corner.
    When you push this + the JTable should unfold other rows, giving more detail on the current row.
    So something like this :
    |--------------------------------|
    |   <some-string>              + |
    |--------------------------------|Drawing this custom component for the column is no problem but I am having trouble implementing the MouseMotionListener events over this.
    If I add a mouseMotionListener to the JTable, I am able to forward these events to my custom class which draws this custom component.
    But off course the X and Y coordinates of this MouseEvent are not mapped into the grid of my custom component, which poses my question.
    How can I attach to each cell of this custom column of my JTable, a listener as to implement some mouseover and mouseclick stuff ?
    In case this post is not all that clear, I will try to add a demo showing my problem.
    Kind regards,
    Wim.

    You're reinventing a wheel that's been done a few times. One example is JTreeTable (http://community.java.net/javadesktop/) but there are others.

  • Need to add checkbox to JTreeTables..HELP plz

    hello everybody,
    I am having problems adding a checkbox to a JTreeTable example from sun .
    i also have a woriking checkbox Jtree class and it is working fine, i tried to add jtable to the jtree and i couldnt.
    can anybody help me, either how ti add a checkbox to a JTreeTable or how to add a JTable to a JCheckBoxTree.
    thanks lots.

    http://forum.java.sun.com/thread.jspa?threadID=461659&messageID=4024652#4024652

  • JTreeTable problem

    Hi,
    I am trying to modify the JTreeTable example available on java.sun.com in 3 parts at
    http://java.sun.com/products/jfc/tsc/articles/treetable1/index.html
    http://java.sun.com/products/jfc/tsc/articles/treetable2/index.html
    http://java.sun.com/products/jfc/tsc/articles/bookmarks/
    to display hierarchical data. At present, the JTree nodes are displayed in the first column of the JTable. I would like to remove this restriction and display the root node at location (0,0) of the JTable and each subsequent node indented by one row and one column.
    For eaxmple, for the markup
    <employee>
    <name></name>
    <address>
    <work></work>
    </address>
    The JTable should look like
    Employee
    |
    |________ Name
    |
    |________address
    |
    |_______work
    Iam able to get the tree as I expect but there are any problems. When a node is not expanded, its children are getting painted often with incorrect icon or label. When I double click to edit it shows different text than the one that gets displayed. I also have problems with viewing the complete tree even though I have scrollbars. Also, the address node isn;t displayed until I expand the 'name' node though that is not the behavior with the example sun has provided.
    I would like to furnish the code here but it is quite big ( some 4 or 5 classes).
    Any help would be very much appreicated.
    cheers,
    vidyut

    Hi Thomas,
    Thanks for the reply. Let me make it clear to you what Iam trying to do. Iam working on developing a grid in which to edit XML data. The root node of the xml should appear at the top left corner of the JTable (which I had mentioned as 0,0 in my earlier posting). This could be anywhere as long as it is the top-leftmost node. The children of root node should be indented 1 table cell to the left and downward direction. The children of the first child of root should be indented 2 table cells and so on. This is to provide the user a cue about the parent-child relationships of the nodes and also allow easy editing of the node content.
    Now to the technical part.
    I saw your example where the tree is set as the row header. This will not work in my case as I expect for any column of the JTable there could be treenodes as well as plain text nodes. So the JTreeTable approach adopted by the example at java.sun.com is more apt I think.
    Like you have said, it is a highly complex example and I just about managed to get the grid. But Iam facing few (!!!) problems.
    You are right about point 3 you have mentioned. When a node isn't expanded the child nodes should'nt be visible. But it is in my case.
    Here's a simplified diagram which should hopefully explain the other problem Iam facing.
    At start
            |
            v ---- slideshow
               |    
               |_________ --> slide 
                                                |
                                                |_______ [ ]
                                                                   |
                                                                   |______wake up and smell the ...
    pic 2 (slide opened)
            |
            v ---- slideshow
               |    
               |_________ |  
                                     V  -------slide
                                                       |
                                                       | _______
                                                                          --> -- title
                                                                                     |
                                                                                     |______wake up  ...
                                                       |
                                                       |
    pic 3 (title opened)
            |
            v ---- slideshow
               |    
               |_________ |  
                                     V  -------slide
                                                       |
                                                       | _______ |
                                                                          V -- title
                                                                                     |
                                                                                     |______wake up  ...
                                                       |
                                                       |
                                                       --> slide
    Legend:
        --> collapsed node
           |
          V  -- expanded node
         [] - leaf node
         My xml snippet is:
    <slideshow>
    <slide>
    <title>Wake up and smell the coffee</title>
    </slide>
    <slide>
    <title></title>
    </slide>
    </slideshow>
    I will leave the point no 4 for later as this posting has already become too long. I would be glad to post the source code if you think that would help.
    cheers,
    vidyut

Maybe you are looking for

  • Problem accessing EJB's in KM Scheduler Task

    Hi, I have created a new SchedulerTask which implements com.sapportals.wcm.service.scheduler.ISchedulerTask. In the run method of the SchedulerTask, I was trying to access the Session bean as below      try {           Context initial = new InitialCo

  • How can I make Safari and Firefox remember a password?

    I changed some of my website passwords recently.  In most cases, Safari and Firefox asked me if I wanted them to remember the new password, I said Yes (I'm not on a shared computer), and when I entered my email address or username, it would appear in

  • Garbage characters inserted in message when files are attached

    Warning: this is an obscure problem. I have changed my default encoding from UTF-8 to ISO-88591-1 using this command: defaults write com.apple.mail NSPreferredMailCharset "ISO-8859-1" The reason I have changed my default encoding from UTF-8 is that O

  • [certain number] item(s) could not be synced.  See itunes for more information????

    Okay so recently I got a gift card with a £10 credit.  Now i have tried to buy an app for my iphone.  My iphone is on a different account to my itunes on my mac and so I authorized the account on my phone onto itunes.  Then I plugged in my phone and

  • Button Component Html Text

    How to Apply htmlText for Button component. var str:String="my name is <b>Kiran</b>" button.label=str i need look like as "my name is Kiran" in this way not only  bold tag. Font family, color also.