Jtree Inside a Jtree

Can i embed a Jtree inside a Jtree?
Is it possible to link two different Jtree's? both of them implementing a different renderer and model ?

Why don't you simply add the "inner" tree as yet
another branch?Yeah. Any sub-tree is a tree in its own right.
Per-node rendering is possible.

Similar Messages

  • How remove (or change) children inside a JTree

    hi,
    I did a program where there are informations with a structure of dependence that should be showed inside JTree components.
    I realized this purpose in my program .
    But I am findind very difficult (after having put the information inside the JTre in the start) to show them again inside the JTrees when they are changed.
    I don't know how to remove or change the informations after they are put on the children of the JTree using the methods that I found in the documentation to reach this purpose...
    I need some help ...
    To explain well my problem, and facilitate the helpers, I post some code that show my problem..
    The program show a GUI with some JTrees.
    The informations are contained in two strings, and in the GUI are also two buttons that can load the informations inside the JTree when they are clicked.
    Thank you in advance
    regards
    tonyMrsangelo
    public class JTree_TryToUseIt_ChangingNodes extends javax.swing.JFrame {
        private PanelFulViewConteiner jPanelFulViewConteiner;
        Dimension dimPrefArcPanels = new Dimension(910, 150);
        Dimension dimMinArcPanels = new Dimension(700, 100);
        Dimension dimPrefSemiArcPanels = new Dimension(850, 140);
        Dimension dimMinSemiArcPanels = new Dimension(550, 90);
        Dimension dimPrefBodyXpicPanels = new Dimension(900, 150);
        Dimension dimMinBodyXpicPanels = new Dimension(700, 150);
        Dimension treePrefDim = new Dimension(90, 110); //
        Dimension treeMinDim = new Dimension(60, 110);
        PanelToShowTrees panel_trees;
        public JTree_TryToUseIt_ChangingNodes() {
            getContentPane().setLayout(new GridBagLayout());
            GridBagConstraints gBC = new GridBagConstraints();
            jPanelFulViewConteiner = new PanelFulViewConteiner();
            gBC.gridx = 0;
            gBC.gridy = 0;
            gBC.gridwidth = 10;
            add(jPanelFulViewConteiner, new GridBagConstraints());
            gBC.gridx = 0;
            gBC.gridy = 1;
            gBC.gridwidth = 10;
            pack();
            panel_trees = this.jPanelFulViewConteiner.jPanelFulContainerTop.panelToShowTrees;
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setLocation(50, 50);
            setVisible(true);
        private void fillTrees(String[] strings) {
            collapseTrees();
            removeNodes();
            for (int index = 0; index < strings.length; index++) {
                DefaultMutableTreeNode dmt = new DefaultMutableTreeNode(strings[index]);
                String knotStr = strings[index].substring(0, 1);
                int knot = -1;
                try {
                    knot = Integer.parseInt(knotStr);
                } catch (NumberFormatException e) {
                panel_trees.root_Node[knot].add(dmt);
                panel_trees.validate();
                panel_trees.repaint();
            collapseTrees();
        void collapseTrees() {
            for (int i = 0; i < 8; i++) {
                panel_trees.jTree.collapseRow(0);
    panel_trees.jTree[i].expandRow(0);
    panel_trees.validate();
    panel_trees.repaint();
    void removeNodes() {
    for (int i = 0; i < 8; i++) {
    panel_trees.jTree[i].removeAll();
    panel_trees.validate();
    panel_trees.repaint();
    public static void main(String args[]) {
    JTree_TryToUseIt_ChangingNodes xx = new JTree_TryToUseIt_ChangingNodes();
    class PanelFulViewConteiner extends JPanel {
    PanelFulContainerTop jPanelFulContainerTop;
    PanelFulContainerBottom jPanelFulContainerBottom;
    public PanelFulViewConteiner() {
    GridBagLayout gbl = new GridBagLayout();
    this.setLayout(gbl);
    GridBagConstraints gBC = new GridBagConstraints();
    jPanelFulContainerTop = new PanelFulContainerTop();
    gBC.gridx = 0;
    gBC.gridy = 0;
    add(jPanelFulContainerTop, gBC);
    jPanelFulContainerBottom = new PanelFulContainerBottom();
    gBC.gridx = 0;
    gBC.gridy = 2;
    add(jPanelFulContainerBottom, gBC);
    class PanelFulContainerTop extends JPanel {
    PanelToShowTrees panelToShowTrees;
    public PanelFulContainerTop() { // costruttore
    this.setMinimumSize(dimMinArcPanels);
    this.setPreferredSize(dimPrefArcPanels);
    setLayout(new FlowLayout());
    panelToShowTrees = new PanelToShowTrees();
    add(panelToShowTrees);
    }// costruttore
    class PanelFulContainerBottom extends JPanel {
    JButton but1 = new JButton("load string1");
    JButton but2 = new JButton("load string2");
    String[] str1 = {"0-AAA", "0-BBBBBB", "2-CCCCC", "2-DDDDDD", "2-EEEEEEE", "5-FFFFFF", "5-GGGGGG", "5-HHHHHH", "7-IIIIII", "7-KKKKKKK", "7-LLLLLL", "7-MMMMMM"};
    String[] str2 = {"0-aaaaa", "0-bbbbb", "0-cccc", "2-ddddd", "2-eeee", "3-ffffff", "3-gggggg", "3-hhhhh", "4-iiiiii", "4-kkkkk", "7-lllllll", "7-mmmmm", "7-nnnnn"};
    public PanelFulContainerBottom() {// costruttore
    this.setMinimumSize(dimMinArcPanels);
    this.setPreferredSize(dimPrefArcPanels);
    add(but1);
    but1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fillTrees(str1);
    add(but2);
    but2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fillTrees(str2);
    class PanelToShowTrees extends JPanel {
    JScrollPane jScrollPane[];
    JTree jTree[];
    DefaultMutableTreeNode[] root_Node;
    public PanelToShowTrees() {
    this.setMinimumSize(dimMinSemiArcPanels);
    this.setPreferredSize(dimPrefSemiArcPanels);
    setLayout(new FlowLayout());
    jScrollPane = new JScrollPane[8];
    jTree = new JTree[8];
    root_Node = new DefaultMutableTreeNode[8];
    for (int i = 0; i < 8; i++) {
    root_Node[i] = new DefaultMutableTreeNode(" " + (8 - i));
    jTree[i] = new JTree(root_Node[i]);
    jScrollPane[i] = new JScrollPane();
    jScrollPane[i].setViewportView(jTree[i]);
    add(jScrollPane[i]);
    jScrollPane[i].setPreferredSize(treePrefDim);
    jScrollPane[i].setMinimumSize(treeMinDim);
    jTree[i].addTreeSelectionListener(new TreeSelectionListener() {
    public void valueChanged(TreeSelectionEvent e) {
    showContentOfTheTree(e);
    private void showContentOfTheTree(TreeSelectionEvent e) {
    String stringaGotFromEvent = e.getPath().toString();
    JOptionPane.showMessageDialog(rootPane, "found =---> " + stringaGotFromEvent);

    hi Andre,
    thank you for answering me.
    I have not much practice with JTrees so I find some difficulty to use it...
    After I got your advice, I made changed a little the design of my program..
    This it is a program for management of a dentist office, and I would show in 8 JTrees (every jTree root represents the teeth in a dental arch) the treatments that each tooth got.
    How I said, the 8 JTree roots are representing the teeth, and in this architecture the problem is:
    - to add a node to a tree root to indicate a treatment for that tooth;
    - to delete all the children from a jTree root before beginning to add new child, before writing again treatments, when the informations are changed.
    Following your help, I made this two functions to reach this purpose:
    private void assingTreatmentToTooth(int toothNmbr, String strTreatment) {
            DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(strTreatment); // new treatment to add
            DefaultTreeModel model = (DefaultTreeModel) panel_trees.jTreeXdentalRoots[toothNmbr].getModel(); // get model for the root Tree
            DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) model.getRoot();
            model.insertNodeInto(newChild, parentNode, 0); // always assign 0 as first node
        } // assingTreatmentToTooth()
    private void removeTreatmentFromAtooth(int toothNmbr, int childNmbr) {
            DefaultTreeModel model = (DefaultTreeModel) panel_trees.jTreeXdentalRoots[toothNmbr].getModel();  // get model for the root Tree
            DefaultMutableTreeNode child = (DefaultMutableTreeNode) model.getChild(model, childNmbr);
            model.removeNodeFromParent(child);
        } // removeTreatmentToTooth()when the second function is executed, I get this error:
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.tree.DefaultTreeModel cannot be cast to javax.swing.tree.TreeNode
    at the line : DefaultMutableTreeNode child = (DefaultMutableTreeNode) model.getChild(model, childNmbr);
    DefaultMutableTreeNode child = (DefaultMutableTreeNode) model.getChild(model, childNmbr);
    could you tell me what is wrong ?
    regards
    TonyMrsangelo

  • Editable jtable inside a jtree

    I want to create an editable jtable inside a jtree. can anyone show me how to do it? thank you.

    I want to create an editable jtable inside a jtree. can anyone show me how to do it? thank you.

  • Problem in refreshing JTree inside Jscrollpane on Button click

    hi sir,
    i have problem in refreshing JTree on Button click inside JscrollPane
    Actually I am removing scrollPane from panel and then again creating tree inside scrollpane and adding it to Jpanel but the tree is not shown inside scrollpane. here is the dummy code.
    please help me.
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.tree.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    public class Test
    public static void main(String[] args)
         JFrame jf=new TestTreeRefresh();
         jf.addWindowListener( new
         WindowAdapter()
         public void windowClosing(WindowEvent e )
         System.exit(0);
         jf.setVisible(true);
    class TestTreeRefresh extends JFrame
         DefaultMutableTreeNode top;
    JTree tree;
         JScrollPane treeView;
         JPanel jp=new JPanel();
         JButton jb= new JButton("Refresh");
    TestTreeRefresh()
    setTitle("TestTree");
    setSize(500,500);
    getContentPane().setLayout(null);
    jp.setBounds(new Rectangle(1,1,490,490));
    jp.setLayout(null);
    top =new DefaultMutableTreeNode("The Java Series");
    createNodes(top);
    tree = new JTree(top);
    treeView = new JScrollPane(tree);
    treeView.setBounds(new Rectangle(50,50,200,200));
    jb.setBounds(new Rectangle(50,300,100,50));
    jb.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
              jp.remove(treeView);
              top =new DefaultMutableTreeNode("The Java ");
    createNodes(top);
              tree = new JTree(top);
                   treeView = new JScrollPane(tree);
                   treeView.setBounds(new Rectangle(50,50,200,200));
                   jp.add(treeView);     
                   jp.repaint();     
    jp.add(jb);     
    jp.add(treeView);
    getContentPane().add(jp);
    private void createNodes(DefaultMutableTreeNode top) {
    DefaultMutableTreeNode category = null;
    DefaultMutableTreeNode book = null;
    category = new DefaultMutableTreeNode("Books for Java Programmers");
    top.add(category);
    book = new DefaultMutableTreeNode("The Java Tutorial: A Short Course on the Basics");
    category.add(book);
    book = new DefaultMutableTreeNode("The Java Tutorial Continued: The Rest of the JDK");
    category.add(book);
    book = new DefaultMutableTreeNode("The JFC Swing Tutorial: A Guide to Constructing GUIs");
    category.add(book);
    book = new DefaultMutableTreeNode("Effective Java Programming Language Guide");
    category.add(book);
    book = new DefaultMutableTreeNode("The Java Programming Language");
    category.add(book);
    book = new DefaultMutableTreeNode("The Java Developers Almanac");
    category.add(book);
    category = new DefaultMutableTreeNode("Books for Java Implementers");
    top.add(category);
    book = new DefaultMutableTreeNode("The Java Virtual Machine Specification");
    category.add(book);
    book = new DefaultMutableTreeNode("The Java Language Specification");
    category.add(book);
    }

    hi sir ,
    thaks for u'r suggession.Its working fine but the
    properties of the previous tree were not working
    after setModel() property .like action at leaf node
    is not working,I'm sorry but I don't understand. I think you are saying that the problem is solved but I can read it to mean that you still have a problem.
    If you still have a problem then please post some code (using the [code] tags of course).

  • How can I show JTree inside the ComboBox!!!!!!!

    hi,
    Is there a way to show JTree in a JComboBox. As JComboBox have the following constructors..
    JComboBox()
    JComboBox(ComboBoxModel aModel)
    JComboBox(Object[] items)
    JComboBox(Vector items)
    Is there a way That I can put JTree in a JComboBox i.e.
    to have a constructor like this
    JComboBo(JTree jTree)
    thanks for help....

    actually I have built a custom FIleDialog. I am getting a tree structure in my JComboBox. But I am stuck at one point whenever I click on the directory that is shown in the table the name of the directory is added to the comboBox under the parent directory and is selected by default and it's contents are shown in the Table now my problem is that if I have the folder whose name is same is it's parent directory and when I click on that it's contents are shown in the Table but the it's name is not added in the comBobox instead it shows me the parent directory. Infact it should add the name in my Combobox and get this one selected not it's parent with the same name. I want it to work like file dialog. Like in FileDialog if we have a parent directory and child directory with the same name they are shown and selected properly, I am trying to do the same way but no success.So to get arround this I was thinking if I can use the JTree instead of directly adding nodes to my TableModel. Or any hints how to get arround this. I do have the custom renderer and model too. Thanks for any help.

  • Dynamic JTree; updating the Jtree during app execution

    I have a JTree that renders a DOM Tree. All is well. I can set different icons in the tree depending on the type of node. The functionality I need is to dynamically change the icon in the JTree for a given node. I have a wrapper object that extends DefaultMutableTreeNode and contains an Icon member varrialbe. The problem is that this varriable is initialized by a custom TreeCellRenderer depending on the contents of the node.
    I have also tried having a node_status flag inside my wrapper node, to give the Cell Renderer something to check to determine what to make the icon. The problem, I think, is that the JTree gets rerendered everytime an AWT event is fired; rerendering the JTree causes my wrapper nodes to be reinstanticated thus clearing all information in the Node, including the node_status flag.
    Has anyone done anything similar, or does anyone have any insight into what is going on?
    thanks.
    -karl

    I have figured out my problem and am posting it in the hopes that it helps others.
    I created a custom TreeModel to deal with taking an XML (DOM) Tree and rendering it in a JTree. The problem comes from the custom class that I created to wrap the DOM nodes. The geometry for the DOM tree is contained in the DOM Node (getChild(x), an XML Tree is really just a single node with children, etc) and the problem stems from the wrapper object not knowing about the geometry of the tree except by traversing the tree through the DOM Nodes; since the DOM Node is a member of the wrapper node, traversal through the DOM tree breaks any data stored in the wrapper node which is reinitialized whenever you try to get a node's child.
    Solution:
    Do not render the tree recursivly with the DOM Nodes: render the tree itteratively with wrapper nodes. Because of the frequency the JTree gets redrawn, and thus the TreeModel gets hit with events, maintaining a semi-static tree will keep the information in the nodes.
    -Karl

  • JTree problem (inside JSplitpane)

    Hello All,
    I am trying to place a Jtree inside left side of jsplitpane. But it didn't appear in it and no error or exception thrown. For testing, i placed some other component like a panel inside that left pane of splitpane and it worked fine. For further testing, when I placed my jtree's panel in applet (to test whether it has something wrong with splitpane or some other thing), it didn't appear in it too. Below is the code to illustrate what I do for my last try (in applet):
    public class TRDB extends JApplet {
         public void init() {
              p("init() called");
         public void start() {
              p("start() called");
              //MainWindow mw = new MainWindow();
              //mw.setSize(400,450);
              //mw.setVisible(true);
              TreeViewPane mcp = new TreeViewPane();
              getContentPane().setLayout(null);
              getContentPane().add(mcp);
              mcp.setBounds(0,0,100,300);
              mcp.setBackground(Color.blue);
              p("start() finish!!!!!");
         private void p(String str) {
              System.out.println(str);
    // TreeViewPane class
    public class TreeViewPane extends JPanel {
         JTree tree;
         DefaultMutableTreeNode top;
         public TreeViewPane() {
              top = new DefaultMutableTreeNode("GDAMS");
             createNodes(top);
             tree = new JTree(top);
              tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
             //setOpaque(true);      //content panes must be opaque
         private void createNodes(DefaultMutableTreeNode top) {
             DefaultMutableTreeNode category = null;
             DefaultMutableTreeNode book = null;
             category = new DefaultMutableTreeNode("Books for Java Programmers");
             top.add(category);
             //...add more books for programmers...
             category = new DefaultMutableTreeNode("Books for Java Implementers");
             top.add(category);
    }Please have a look at see if something is wrong. I just saw a blue rectangular box (depicting my jtree panel) on applet without any table in it.
    Plz HELP!!

    I must take some coffee or strong cup of tea. i m exhaust, really. Yah i got it what i did wrong. sorry !!

  • JTree TransferHandler problems (SSCE inside)

    Hi JAvaers.
    Appreciate the help as always, hopefully one of you will pinpoint the demon. I'd have thought that I could build these gizmos eyes closed by now -- except for this one! I'm examining code against those that work, and I can't play the find-the-mistakes game successfully at all. Here's an SSCE that reproduces the problem:
    Expected Behavior:
    When I drag a node onto another node, it is simply deleted from its original parent.
    Actual Behavior:
    No deletion takes place.
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.UnsupportedFlavorException;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreePath;
    import java.io.*;
    * Dragging and dropping chocolate milk onto default category should remove
    * the node from its parent, but it doesn't. *puzzle*
    public class Test extends JFrame{
         private static final long serialVersionUID = 1L;
         private static Category root;
         static{
              root = new Category( "root category" );
              Category milk = new Category( "milk" );
              Category cmilk = new Category( "chocolate milk" );
              Category choco = new Category( "choco" );
              milk.add( cmilk );
              root.add( milk );
              root.add( choco );
         public static void main( String args[]) throws Exception {
              JFrame f = new JFrame();
              f.setSize( 400, 400 );
              f.getContentPane().add( new JScrollPane( new TestTree() ) );
              f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              f.setVisible( true );     
          * Our tree
         private static final class TestTree extends JTree {
              private static final long serialVersionUID = 1L;
              private DefaultTreeModel      model;
              private TreePath               selectedPath;
              private Category               originalTransferable;
              public TestTree(){
                   model = new DefaultTreeModel( root );
                   setModel( model );
                   setDragEnabled( true );
                   setTransferHandler( new TreeNodeTransferHandler() );
                   setDropMode( DropMode.ON_OR_INSERT );
                   addTreeSelectionListener( new TreeSelectionListener() {
                        public void valueChanged( TreeSelectionEvent e ){     
                             TreePath path = e.getNewLeadSelectionPath();
                             if( path != null ){
                                  selectedPath = path;
              private class TreeNodeTransferHandler extends TransferHandler {          
                   private static final long serialVersionUID = 1L;
                   public boolean importData( TransferSupport info ) {
                        if( !canImport(info) )
                           return false;     
                        try{
                            // fetch the drop location
                            JTree.DropLocation           dl                = (JTree.DropLocation)info.getDropLocation();
                            TreePath                     path           = dl.getPath();   
                            Category                    dragged          = (Category)info.getTransferable().getTransferData( Category.categoryFlavor );
                            Category                    target          = (Category)path.getLastPathComponent();
                            System.out.println(
                                      " --> Original transferable hashcode : " +
                                      originalTransferable.hashCode() +
                                      "\n --> Actual transferable hashcode : " +
                                      ((Category)info.getTransferable().getTransferData( Category.categoryFlavor )).hashCode()                       
                            System.out.println( "droppped " + dragged + " onto " + target );
                            // doesn't work
                            ((Category)dragged.getParent()).removeSubcategory( dragged, model );
                            // -- or --
                            // works
                            //((Category)originalTransferable.getParent()).removeSubcategory( originalTransferable, model );
                            return true;
                        catch( Exception x ){
                             x.printStackTrace();
                        return false;
                   public int getSourceActions( JComponent c ){
                        return TransferHandler.MOVE;
                   @Override
                   protected Transferable createTransferable( JComponent c ){
                        if( c.equals( TestTree.this ) ){          
                             if( selectedPath != null && !((Category)selectedPath.getLastPathComponent()).isRoot() ){
                                  originalTransferable = (Category)selectedPath.getLastPathComponent();
                                  return originalTransferable;
                        return null;
                   public boolean canImport( TransferSupport info ){
                        if( !info.isDrop() )
                             return false;
                        if( !info.isDataFlavorSupported( Category.categoryFlavor ) )
                           return false;
                        JTree.DropLocation dl = (JTree.DropLocation)info.getDropLocation();
                        if( dl == null || dl.getPath() == null )
                             return false;
                        Object transferdata   = null;
                        try{
                             transferdata = info.getTransferable().getTransferData( Category.categoryFlavor );
                        catch( Exception e ){
                             e.printStackTrace();
                        // can't drop a null node, nor can a node be dropped onto itself
                        return dl.getPath().getLastPathComponent() != null &&
                                  dl.getPath().getLastPathComponent() != transferdata;
          * Dummy node object
         private static final class Category extends DefaultMutableTreeNode implements Transferable{
              private static final long serialVersionUID = 1L;
              public static final DataFlavor categoryFlavor = new DataFlavor( Category.class, "Category" );
              public static final DataFlavor[] transferDataFlavors = new DataFlavor[]{ categoryFlavor };
              private String title;
              public Category( String t ){
                   title = t;
              @Override
              public String toString() {
                   return title;
              @Override
              public Object getTransferData(DataFlavor flavor)
                   throws UnsupportedFlavorException, IOException {
                   if( flavor.equals( categoryFlavor ) )
                        return this;
                   return null;
              @Override
              public DataFlavor[] getTransferDataFlavors() {
                   return transferDataFlavors;
              @Override
              public boolean isDataFlavorSupported(DataFlavor flavor) {
                   return flavor.equals( categoryFlavor );
               * Remove a child category from this category
               * @param n
              public void removeSubcategory( final Category n, final DefaultTreeModel model ){
                   int[]          childIndex   = new int[1];
                 Object[]    removedArray = new Object[1];                 
                 childIndex[0]                 = getIndex( n );
                 removedArray[0]            = n;       
                 remove( n );       
                 model.nodesWereRemoved( this, childIndex, removedArray );
    }Thanks again!
    Alex

    As other detail, if we resort to using the user objects inside of the Trasferables to transmit the categories themselves, it appears that the object integrity is maintained.
    so either:
    1 - Transferables are not guaranteed to be persistent in memory space
    2 - There's a bug here that is causing some kind of improper cloning of the transferables themselves, that is otherwise preserving their user objects.
    I'd call #2 a gotcha. I'll try bugging this at Sun to see if they'll fix it.

  • JTree Inserting Problem

    Please help me ..
    i have write a code ..which is when the user clicks the button...
    a jtree table will come and the values inside the jtree will be filled by the contents of the selected items in the form...
    but my problem is jtree only is comming
    i created the object class ... but ...
    the initialisation is not happening...
    plz check the code below .. this is my class
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    public class Reservation extends JFrame implements ItemListener,ActionListener{
         JComboBox fromCity = null;
         JComboBox toCity = null;
         JComboBox dDay = null;
         JComboBox dMonth = null;
         JComboBox dYear = null;
         JComboBox rDay = null;
         JComboBox rMonth = null;
         JComboBox rYear = null;
         JComboBox adult = null;
         JComboBox Cabin = null;
         JFrame table;
         public Reservation()
              setSize(600,400);
              JPanel p = new JPanel();
              //getContentPane().setLayout(new BorderLayout());
              GridBagLayout gbl = new GridBagLayout();
              GridBagConstraints gbc = new GridBagConstraints();
              p.setLayout(gbl);
              String []cities = {"New York","Chicago","Miami","Pittsburgh","Memphis","New Orleans"};
              String [] days={"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","27","28","29","30","31"};
              String [] months = {"January","Feburary","March","April","May","June","July","August","September","October","November","December"};
              String [] year = {"2006","2007"};
              String [] adt = {"1","2","3","4"};
              String [] cab = {"Buisness","Economy"};
              fromCity = new JComboBox(cities);
              fromCity.setSelectedIndex(0);
              toCity = new JComboBox(cities);
              toCity.setSelectedIndex(0);
              dDay = new JComboBox(days);
              dMonth = new JComboBox(months);
              dYear = new JComboBox(year);
              rDay = new JComboBox(days);
              rMonth = new JComboBox(months);
              rYear = new JComboBox(year);
              adult = new JComboBox(adt);
              Cabin = new JComboBox(cab);
              JLabel frmCity = new JLabel("From");
              frmCity.setLabelFor(fromCity);
              JLabel tCity = new JLabel("To");
              tCity.setLabelFor(tCity);
              JLabel dDate = new JLabel("Departure Date");
              dDate.setLabelFor(dDate);
              JLabel rDate = new JLabel("Return Date");
              rDate.setLabelFor(rDate);
              JLabel Psg = new JLabel("Pasengers");
              Psg.setLabelFor(Psg);
              JLabel Adults = new JLabel("Adults");
              Adults.setLabelFor(Adults);
              JLabel cabin = new JLabel("Cabin");
              cabin.setLabelFor(cabin);
              JLabel search = new JLabel("Search By");
              search.setLabelFor(search);
              JRadioButton ROneWay = new JRadioButton("One Way");
              JRadioButton RRoundTrip = new JRadioButton("Round Trip");
              JButton searchbutton = new JButton("Date");
              ButtonGroup group = new ButtonGroup();
              group.add(ROneWay);
              group.add(RRoundTrip);
              gbc.gridx = 0;
              gbc.gridy = 0;
              gbc.insets = new Insets(0,30,0,0);
              p.add(frmCity,gbc);
              gbc.gridx =1;
              gbc.gridy = 0;
              gbc.insets = new Insets(0,30,0,0);
              p.add(fromCity,gbc);
              gbc.gridx =0;
              gbc.gridy = 1;
              gbc.insets = new Insets(0,30,0,0);
              p.add(tCity,gbc);
              gbc.gridx =1;
              gbc.gridy = 1;
              gbc.insets = new Insets(10,30,0,0);
              p.add(toCity,gbc);
              gbc.gridx = 0;
              gbc.gridy = 2;
              gbc.insets = new Insets(10,50,0,0);
              p.add(ROneWay,gbc);
              gbc.gridx = 1;
              gbc.gridy = 2;
              gbc.insets = new Insets(10,30,0,0);
              p.add(RRoundTrip,gbc);
              gbc.gridx = 1;
              gbc.gridy = 3;
              gbc.insets = new Insets(0,0,0,0);
              p.add(dDate,gbc);
              gbc.gridx = 0;
              gbc.gridy = 4;
              p.add(dDay,gbc);
              gbc.gridx = 1;
              gbc.gridy = 4;
              p.add(dMonth,gbc);
              gbc.gridx = 2;
              gbc.gridy = 4;
              p.add(dYear,gbc);
              gbc.gridx = 1;
              gbc.gridy = 5;
              gbc.insets = new Insets(0,0,0,0);
              p.add(rDate,gbc);
              gbc.gridx = 0;
              gbc.gridy = 6;
              p.add(rDay,gbc);
              gbc.gridx = 1;
              gbc.gridy = 6;
              p.add(rMonth,gbc);
              gbc.gridx = 2;
              gbc.gridy = 6;
              p.add(rYear,gbc);
              gbc.gridx = 1;
              gbc.gridy = 7;
              p.add(Psg,gbc);
              gbc.gridx = 0;
              gbc.gridy = 8;
              p.add(Adults,gbc);
              gbc.gridx = 1;
              gbc.gridy = 8;
              p.add(adult,gbc);
              gbc.gridx = 0;
              gbc.gridy = 9;
              p.add(cabin,gbc);
              gbc.gridx = 1;
              gbc.gridy = 9;
              gbc.insets = new Insets(10,0,0,0);
              p.add(Cabin,gbc);
              gbc.gridx = 0;
              gbc.gridy = 10;
              p.add(search,gbc);
              gbc.gridx = 1;
              gbc.gridy = 10;
              gbc.insets = new Insets(10,0,0,0);
              p.add(searchbutton,gbc);
              getContentPane().add(p);
              fromCity.addItemListener(this);
              toCity.addItemListener(this);
              dDay.addItemListener( this);
              dMonth.addItemListener( this);
              dYear.addItemListener(this);
              adult.addItemListener(this);
              Cabin.addItemListener(this);
              searchbutton.addActionListener(this);
              //Jtable form
              table = new JFrame();
              Container container;
              container = table.getContentPane();
              JPanel jpanel = new JPanel(new GridLayout(2,1));
              container.setLayout(new GridLayout(2,1));
              JLabel l1 = new JLabel("Departure Journey");
              l1.setLabelFor(l1);
              container.add(l1);
              final String[] colHeads = {"","Flightno","Date","Departure Time","Arrival Time","Flight","Duration","Fare"};
              final Object[ ][ ] data = new Object[10][10];
              JTable table = new JTable(data,colHeads);
              int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;     
              int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
              JScrollPane jsp = new JScrollPane(table,v,h);
              container.add(jsp,BorderLayout.CENTER);
         String ffcity,ttcity,dday,dmon,dyear,adt,cab;
         public void itemStateChanged(ItemEvent e)
              ffcity = (String)fromCity.getSelectedItem();
              ttcity = (String)toCity.getSelectedItem();
              dday = (String)dDay.getSelectedItem();
              dmon = (String)dMonth.getSelectedItem();
              dyear = (String)dYear.getSelectedItem();
              adt = (String)adult.getSelectedItem();
              cab = (String)Cabin.getSelectedItem();
         public void actionPerformed(ActionEvent ae)
         if(ae.getActionCommand() == "Date")
              try
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              Connection con = DriverManager.getConnection("jdbc:odbc:ds","sa", "");
              PreparedStatement stmt = con.prepareStatement("select ifno,vdtime,vatime,vdate1,vdate2,vdate3,efare from airways where fcity = ? and tcity = ? and vdate1 = ? and vdate2 = ? and vdate3 = ?");
              stmt.setString(1,ffcity);
              stmt.setString(2,ttcity);
              stmt.setString(3,dday);
              stmt.setString(4,dmon);
              stmt.setString(5,dyear);
              ResultSet d = stmt.executeQuery();
              /* int count=0;
              while(d.next())
              {count++;
              int i = 0;*/
              while(d.next())
              /*for(int j =1;j<=7;j++)
              data[i][j] = rs.getString(j);
              System.out.println(" " + data[i][j]);
              }i++;*/
              System.out.println(d.getInt(1));
              System.out.println(d.getDouble(2));
              catch(Exception ex)
                   System.out.println("Error occurred");
                   System.out.println("Error:"+ex);
              table.setVisible(true);
              table.setSize(300,200);
         private static void createAndShowGUI()
              JFrame.setDefaultLookAndFeelDecorated(true);
              Reservation r=new Reservation();
              JFrame frame = new JFrame("Reservation Form");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //r.pack();
              r.setVisible(true);
         public static void main(String[] args)
              SwingUtilities.invokeLater(new Runnable(){
                   public void run()
                        createAndShowGUI();
    in this object creation is not happening
    when i run this code ...
    only jtree is comming..
    how can i make it the values of seceted items to come in table
    i commented the parts that having error..
    when u uncomment it u will get the problem of this code

    please anyone

  • Buttons not working in jTree cells

    I have modified the defaultTreeCellRenderer to include a jButton and a Label on certain cells. Unfortunately I cannot click on the button. Clicking the button selects that row in the tree, which is fine, but it doesn't send the action on to the button. The Button doesn't depress and the buttons action listener isn't called. Anyone have any ideas?
    Thanks

    Renderers just create a picture of a component, they do not cause the component to actually appear. A cell in JTree cannot behave the way a JButton does. You can simulate a JButton to an extent, by painting it in a depressed state if the node is selected, but you cannot use that component for any kind of action processing.
    Remember that your renderer is never really added to your GUI - the component is used only to make it paint itself inside the JTree component. This is what allows you, for example, to use only one instance of a renderer for all the nodes in a tree.
    Mitch Goldstein
    Author, Hardcore JFC (Cambridge Univ Press)
    [email protected]

  • Help with JTree refresh

    I am having trouble displaying a JTree with newly added nodes.
    I have a JTree, inside a JPanel, JScrollPane and JSplitPane.
    I create the JTree with a single root node which displays correctly.
    I update the JTree with new children which displays correctly.
    Using the same exact routine as above - I add additional new children to the root, the new children do not display in the JTree.
    I have confirmed that I am using the correct tree and root node in debug that the tree/node objects has been correctly updated. It is just not displaying the new children to the root.
    I can expand and collapse the tree which does not show the new children, just the original populated root.
    After the root has been updated, I have tried a number of methods to resolve: tree/jpanel/jscrollpane/jsplitpane .revalidate, invalidate, repaint, etc.
    I am using v1.4.1.
    What am I missing here?
    Thanks in advance.

    i use two classes fro add or insert nodes in a tree, one adds the node at the same level of the current selected node, and the other intert it inside:
    // InsertaTreeConfAction.java
    package ayto;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import javax.swing.tree.*;
    public class InsertaTreeConfAction extends AbstractAction {
    TreeConf treeConf;
    MenuTreeConf menuPrincipal;
    TreeConfAppAyto confNodo;
    DefaultTreeModel model;
    TreeTreeConf tree;
    public InsertaTreeConfAction(TreeConf treeConf,String text) {
    super(text);
    this.treeConf = treeConf;
         InitAction();
    public InsertaTreeConfAction(TreeConf treeConf, String text, Icon icon) {
    super(text, icon);
    this.treeConf = treeConf;
         InitAction();
    public void InitAction(){
         menuPrincipal = treeConf.getMenu();
         confNodo = treeConf.selNodo;
         model = treeConf.getTree().getMyModel();
         tree = treeConf.getTree();
    public void actionPerformed(ActionEvent ev) {
              model = treeConf.getTree().getMyModel();
              TreePath tp = tree.getSelectionPath( );
         MutableTreeNode insertNode = (MutableTreeNode)tp.getLastPathComponent( );
         int insertIndex = 0;
              if (insertNode.getParent( ) != null) {
              MutableTreeNode parent = (MutableTreeNode)insertNode.getParent( );
              //insertIndex = parent.getIndex(insertNode) + 1;
              //insertNode = parent;
         MutableTreeNode node = new DefaultMutableTreeNode(new TreeConfAppAyto("Nodo Insertado"));
         model.insertNodeInto(node, insertNode, insertIndex);
    treeConf.estadoConfApp = TreeConf.NODO_MODIFICADO;
    treeConf.updater.update(); // esto no colapsa el arbol
    treeConf.setTitle("AYTO de Huelva - Configuraci�n de men�s: "+treeConf.fileAct);
    // AnadeTreeConfAction.java
    package ayto;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import javax.swing.tree.*;
    public class AnadeTreeConfAction extends AbstractAction {
    TreeConf treeConf;
    MenuTreeConf menuPrincipal;
    TreeConfAppAyto confNodo;
    DefaultTreeModel model;
    TreeTreeConf tree;
    public AnadeTreeConfAction(TreeConf treeConf,String text) {
    super(text);
    this.treeConf = treeConf;
         InitAction();
    public AnadeTreeConfAction(TreeConf treeConf, String text, Icon icon) {
    super(text, icon);
    this.treeConf = treeConf;
         InitAction();
    public void InitAction(){
         menuPrincipal = treeConf.getMenu();
         confNodo = treeConf.selNodo;
         model = treeConf.getTree().getMyModel();
         tree = treeConf.getTree();
    public void actionPerformed(ActionEvent ev) {
              model = treeConf.getTree().getMyModel();
              TreePath tp = tree.getSelectionPath( );
         MutableTreeNode insertNode = (MutableTreeNode)tp.getLastPathComponent( );
         int insertIndex = 0;
              if (insertNode.getParent( ) != null) {
              MutableTreeNode parent = (MutableTreeNode)insertNode.getParent( );
              insertIndex = parent.getIndex(insertNode) + 1;
              insertNode = parent;
         MutableTreeNode node = new DefaultMutableTreeNode(new TreeConfAppAyto("Nodo A�adido"));
         model.insertNodeInto(node, insertNode, insertIndex);
    treeConf.estadoConfApp = TreeConf.NODO_MODIFICADO;
    treeConf.updater.update(); // esto no colapsa el arbol
    treeConf.setTitle("AYTO de Huelva - Configuraci�n de men�s: "+treeConf.fileAct);

  • JTree node alias?

    Using
    the Sun Tutorial program DropDemo.java as a reference point, the question I have deals with how the List nodes are displayed. The list elements in the demo are called List Item 1, List Item 2, List Item 3, List Item 4. I am looking for a technique to just display the *1*, *2*, *3*, and *4* respective portions of the four elements created by the demo. Other portions of the application need for the list element to have the complete text, List Item 1, etc. So the text in the addElement can't change. I am also using a JTree inside of the JPanel instead of the demo's JList. Any suggestions? Thanks.

    J,
    Thank you for posting. I think I can accomplish what we are trying to do by using the following code. Unfortunately it suppresses the ability to highlight a selected cell. I'll post that problem under a separate topic.
    Thanks,
    Peter
             private SimpleTreeCellRenderer stcr = new SimpleTreeCellRenderer();
             SimpleTreeCellRenderer stcr = new SimpleTreeCellRenderer();
                public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
                     String newValue="";
                     if( value.toString().equals"something" )
                          newValue = value.toString().concat(" good");
                          else
                               newValue = value.toString();
                     setText(newValue);
                     return this;

  • Highlighting nodes in a JTree

    Hi,
    I'd like to know how I can produce the efect of highlighting nodes in a JTree when the mouse moves over the JTree.
    Thanks

    You say to get the mouseevent coordinates with a mouse
    listener, but which component should be the caller of
    the methos addMouseListener?
    If I choose the jtree, I can't get the 'mouseevent
    coordinates' each time the mouse moves over a node,
    because the methods mouseEntered and mouseExited are
    invoked just once (when the mouse enter inside the
    jtree's area (mouseEntered), and when the mouse gets
    out the jtree's area(mouseExited)), so I can't change
    the boolean field to true for nodes which have the
    mouse over.just use mouseMoved of the MouseMotionListener.
    however, i have my doubts that you will have a lot of fun with the suggested method (correct though it is).
    at least make sure you only call the repaint method if the mouse moved into a new node. you might want to try the the nodeChanged method, that way you don't repaint the whole tree every time.
    thomas

  • Problem in refreshing a JTree

    Hi,
    Can anyone tell how to refresh a JTree(javax.swing.Jtree) used for displaying file system(both local and remote).
    I'm getting a problem if a file/directoy is added to the file system, after my Applet is loaded. Actually, i have used DefaultTreeModel's reload() method and calling it inside SwingUtilities.invokeLater() using Thread, but its not working.
    Plz help me out.
    Thanks

    Hi everybody,
    CAN ANYONE HELP ME OUT?????????

  • How to Refresh JTree if a file System got changed during Run-time

    Hi,
    Can anyone tell me how to refresh a JTree(javax.swing.JTree) used for displaying file system(both local and remote).
    I'm getting a problem if a file/directoy is added to the file system, after my Applet is loaded. Actually, i have used DefaultTreeModel's reload() method for refreshing and calling it inside SwingUtilities.invokeLater() using Thread, but its not working.
    I want that the tree should reflect the latest Files/Directories on the click of a node, if any file or directory is added under that node.
    Plz tell me if this is possible or not.
    Thanks

    Hi Shay_te,
    Thanx for ur reply as i was eagerly waiting for the one.
    but the example is using the TreeTable
    and i have used JTree and DefaultTreeModel.
    I'm calling reload(node) within treeExpand() method
    Then, i'm regestring addTreeModelListener() as
    m_model.addTreeModelListener(new javax.swing.event. TreeModelListener(){ }
    inside which all 4 methods are over-ridden
    code snippet is as follows so plz help me and tell if this the right way:
    class DirExpansionListener implements TreeExpansionListener{
            DirExpansionListener(){
            public void treeExpanded(TreeExpansionEvent event) {
                final DefaultMutableTreeNode node = getTreeNode(event.getPath());
                final FileNode fnode = getFileNode(node);
                Thread runner = new Thread() {
                    public void run() {
                        if (fnode != null && fnode.expand(node)) {
                            Runnable runnable = new Runnable() {
                                public void run() {
                                    try{
                                       m_model.reload(node);
                                        m_model.addTreeModelListener(new javax.swing.event.TreeModelListener() {
                                            public void treeNodesChanged(javax.swing.event.TreeModelEvent evt) {
                                            public void treeStructureChanged(javax.swing.event.TreeModelEvent evt) {
                                                System.out.println("Path of node changed->"+evt.getTreePath());
                                            public void treeNodesInserted(javax.swing.event.TreeModelEvent evt) {
                                                System.out.println("Nodes Inserted method called..");
                                            public void treeNodesRemoved(javax.swing.event.TreeModelEvent evt) {
                                        System.out.println("Run inside DEvent called..");
                                        //Thread.sleep(500);
                                        //fnode.expand(node);
                                    }catch(Exception e){System.out.println("err :" +e);}
                            SwingUtilities.invokeLater(runnable);
                runner.start();
            public void treeCollapsed(TreeExpansionEvent event) {}
        Please reply...

Maybe you are looking for

  • Missing Album Covers

    2 Questions: 1. In my library on my computer, I have all of the album cover, but 1 (I manually put in most of them). But when I sync to my Ipod, I am missing 3 album covers. ...Does anyone know why? 2. One of my songs in my library wont let me manual

  • Connections to target databases and directories

    Hi All, I'm creating a few custom provisioning connectors to databases and directories using the GTC framework -- http://download.oracle.com/docs/cd/E10391_01/doc.910/e10360/custom_prov.htm#Toc153968045. I'm using the initialize() method in the Trans

  • Audio book stops periodically when using headphones - Iphone 5

    Anyone having this problem on iPhone 5?  I have used 2 different headphones with the same result. Using Etymotic HF2 and HF3 with the same problem. I am listening to an audio book and then it stops.  Pressing pause and play does not get it going, but

  • User stuck on "Changing Password" screen after updating expired password, Windows 8.1 Pro

    Hi, We have recently upgraded to Windows 8.1 Professional in our domain (Domain & Forest Functional Level at Windows Server 2003). I am facing an issue where, when a users' password is expired and the user changes his/her password (after being prompt

  • Connection Timeout/Lost on C350:

    Hello, We've got a C350 installed at an ISP customer and recently, they've started to experience some major mail receiving problems with a specific domain(one of their major partners). Connections are lost and some even get the 501 5.5.4 Invalid Addr