JTree - JComboBox interaction

I have a program that displays editable information for each node in a tree. I've run into a problem where a user may update the contents of a JComboBox and then click on a new node without saving their changes. If the information was just lost (as it is with a JTextField), I would have no problem, but the information is saved under the node that was just clicked. Below is an oversimplified example of my problem.
1) Click TreeNode 1, type something in the JComboBox, hit enter, and then click back and forth from TreeNode 2. Everything is as it should be.
2) Now restart the example (there is only a problem if the JComboBox is blank to begin with), and do the same thing without hitting enter.
In the actual program I have a custom TreeModel, a custom TreeSelectionListener, a custom TreeRenderer, etc. but nothing I've tried does any good (and I've tried so many different things, including creating a previousNode variable and an isBeingEditted variable, all to no avail).
The JComboBox and the automatic update both serve important purposes, so I'd like to keep that functionality. Any help would be greatly appreciated.
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.awt.event.*;
import java.awt.*;
public class TreeComboBoxProblem extends JFrame {
    private JTree tree;
    private JLabel nodeName;
    private JComboBox nodeValue;
    public TreeComboBoxProblem(String name) {
        super(name);
        DefaultMutableTreeNode top = new DefaultMutableTreeNode(new TreeNode("TreeNode 0"));
        top.add(new DefaultMutableTreeNode(new TreeNode("TreeNode 1")));
        top.add(new DefaultMutableTreeNode(new TreeNode("TreeNode 2")));
        top.add(new DefaultMutableTreeNode(new TreeNode("TreeNode 3")));
        getContentPane().add( tree = new JTree(top), BorderLayout.NORTH );
        tree.addTreeSelectionListener( new TreeListener() );
        JPanel info = new JPanel();
        info.add( nodeName = new JLabel("TreeNode 0"));
        info.add( nodeValue = new JComboBox());
        nodeValue.setPreferredSize(new Dimension(102, 20));
        nodeValue.setEditable(true);
        nodeValue.addActionListener(new infoActionListener());
        getContentPane().add( info, BorderLayout.SOUTH );
    class TreeNode {
        String name;
        String value;
        public TreeNode(String name) {
            this.name = name;
            value = "";
        public String toString() {
            return name;
    protected class TreeListener implements TreeSelectionListener {
        public void valueChanged(TreeSelectionEvent e) {
            showInfo();
    public void showInfo() {
        TreeNode node = (TreeNode)((DefaultMutableTreeNode)tree.getSelectionPath().getLastPathComponent()).getUserObject();
        nodeName.setText(node.name);
        nodeValue.setSelectedItem(node.value);
    protected class infoActionListener implements ActionListener {
        public void actionPerformed(ActionEvent ae) {
            updateInfoSource();
    public void updateInfoSource() {
        TreeNode node = (TreeNode)((DefaultMutableTreeNode)tree.getSelectionPath().getLastPathComponent()).getUserObject();
        node.value = (String)nodeValue.getSelectedItem();
    public static void main(String[] args) {
        JFrame frame = new TreeComboBoxProblem("TreeComboBoxProblem");
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible( true );
}

This is another solution for the problem:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeComboBoxProblem extends JFrame {
    private JTree tree;
    private JLabel nodeName;
    private JComboBox nodeValue;
    private TreeNode selectedNode;
    public TreeComboBoxProblem(String name) {
        super(name);
        DefaultMutableTreeNode top = new DefaultMutableTreeNode(new TreeNode("TreeNode 0"));
        top.add(new DefaultMutableTreeNode(new TreeNode("TreeNode 1")));
        top.add(new DefaultMutableTreeNode(new TreeNode("TreeNode 2")));
        top.add(new DefaultMutableTreeNode(new TreeNode("TreeNode 3")));
        getContentPane().add( tree = new JTree(top), BorderLayout.NORTH );
        tree.addTreeSelectionListener( new TreeListener() );
        JPanel info = new JPanel();
        info.add( nodeName = new JLabel("TreeNode 0"));
        info.add( nodeValue = new JComboBox(new String[] {}));       
        nodeValue.setPreferredSize(new Dimension(102, 20));
        nodeValue.setEditable(true);
        nodeValue.addActionListener(new infoActionListener());
        getContentPane().add( info, BorderLayout.SOUTH );
    class TreeNode {
        String name;
        String value;
        public TreeNode(String name) {
            this.name = name;
            value = "";
        public String toString() {
            return name;
    protected class TreeListener implements TreeSelectionListener {
        public void valueChanged(TreeSelectionEvent e) {
            showInfo();
    public void showInfo() {
        if (selectedNode != null)
            selectedNode.value = nodeValue.getEditor().getItem().toString();
        selectedNode = (TreeNode)((DefaultMutableTreeNode)tree.getSelectionPath().getLastPathComponent()).getUserObject();
        nodeName.setText(selectedNode.name);
        nodeValue.getEditor().setItem(selectedNode.value);
        nodeValue.setSelectedItem(selectedNode.value);
    protected class infoActionListener implements ActionListener {
        public void actionPerformed(ActionEvent ae) {
            updateInfoSource();
    public void updateInfoSource() {
        selectedNode.value = (String)nodeValue.getSelectedItem();
    public static void main(String[] args) {
        JFrame frame = new TreeComboBoxProblem("TreeComboBoxProblem");
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible( true );
}

Similar Messages

  • Jtree Node with JComboBox don't work properly in Windows Vista!

    Hi people!
    i create a Jtree component and create a special node, that is a <strong>JPanel with a JLabel + JCombobox</strong>!
    Only the direct childs of root have this special node.
    A can put this work properly in Windows XP, like the picture:
    [XP Image|http://feupload.fe.up.pt/get/jcgd0rY5p9PoFPG]
    And in Windows Vista the same code appear like this:
    [Vista Image|http://feupload.fe.up.pt/get/Ylajl6hlCUFc0xe]
    <strong>Hence, in Vista something append behind the JLabel and show something wyerd!</strong>
    I can't understant this and if someone can help i appreciate!
    The TreeNodeRender class is :
    public class MetaDataTreeNodeRenderer implements TreeCellRenderer {
        private JLabel tip = new JLabel();
        private JPanel panel = new JPanel();   
        private JComboBox dataMartsRenderer = new JComboBox();
        private DefaultTreeCellRenderer nonEditableNodeRenderer = new DefaultTreeCellRenderer();
        private HashMap<String, String> valueSaver = null;
        public MetaDataTreeNodeRenderer(Component treeContainer, HashMap<String, String> valueSaver, String[] valuesComboBox) {
            this.valueSaver = valueSaver;
            int width = (int)treeContainer.getPreferredSize().getWidth();
            panel.setLayout(new GridBagLayout());
            java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
            panel.setMaximumSize(new Dimension(width, 15));
            panel.setBackground(new Color(255, 255, 255, 0));
            dataMartsRenderer = new JComboBox(valuesComboBox);
            gridBagConstraints.gridx = 0;
            gridBagConstraints.gridy = 0;
            panel.add(tip, gridBagConstraints);
            gridBagConstraints.gridx = 1;
            panel.add(dataMartsRenderer, gridBagConstraints);
            tip.setLabelFor(dataMartsRenderer);       
        public JComboBox getEditableNodeRenderer() {
            return dataMartsRenderer;
        public String getTipText(){
            return this.tip.getText();
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                boolean expanded, boolean leaf, int row, boolean hasFocus) {
            Component returnValue = null;
            DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)value;
            DefaultMutableTreeNode currentNodeFather = (DefaultMutableTreeNode)currentNode.getParent();
            if(currentNodeFather != null && currentNodeFather.isRoot()){//se o meu pai &eacute; a raiz, ent&atilde;o eu sou um datamart
                                                                        //se sou um datamart, ent&atilde;o sou edit&aacute;vel.
                String dataMart = (String)currentNode.getUserObject();
                String dataMartValue = this.valueSaver.get(dataMart);
                tip.setText(dataMart);
                if(dataMartValue != null) {
                    dataMartsRenderer.setSelectedItem(dataMartValue);
                returnValue = panel;
            }else{//sou um n&oacute; n&atilde;o edit&aacute;vel.
                 returnValue = nonEditableNodeRenderer.getTreeCellRendererComponent(tree,
                         value, selected, expanded, leaf, row, hasFocus);
            return returnValue;
    }The TreeNodeEditor class is :
    public class MetaDataTreeNodeEditor extends AbstractCellEditor implements TreeCellEditor {
        MetaDataTreeNodeRenderer renderer = null;
        JTree tree;
        //Where i save all JComboBox values ( name of label, selected item in combobox), for all combbox
        HashMap<String, String> valueSaver = null;
        public MetaDataTreeNodeEditor(JTree tree, Component treeContainer, HashMap<String, String> valueSaver, String[] valuesComboBox) {
            this.tree = tree;
            this.renderer = new MetaDataTreeNodeRenderer(treeContainer, valueSaver, valuesComboBox);
            this.valueSaver = valueSaver;
        public Object getCellEditorValue() {
            JComboBox comboBox = renderer.getEditableNodeRenderer();
            String dataMart = renderer.getTipText();
            this.valueSaver.put(dataMart, (String)comboBox.getSelectedItem() );
            return dataMart;
        @Override
        public boolean isCellEditable(EventObject event) {
            boolean returnValue = false;
            if (event instanceof MouseEvent) {
                MouseEvent mouseEvent = (MouseEvent) event;
                if (mouseEvent.getClickCount() > 1) {
                    TreePath path = tree.getPathForLocation(mouseEvent.getX(), mouseEvent.getY());
                    if (path != null) {
                        Object node = path.getLastPathComponent();
                        if ((node != null) && (node instanceof DefaultMutableTreeNode)) {
                            DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node;
                            if ( treeNode.getParent() != null && ((DefaultMutableTreeNode) treeNode.getParent()).isRoot()) {
                                returnValue = true;
                            } else {
                                returnValue = false;
            return returnValue;
        public Component getTreeCellEditorComponent(final JTree tree, final Object value, boolean selected,
                boolean expanded, boolean leaf, int row) {
            Component editor = renderer.getTreeCellRendererComponent(tree, value, true, expanded, leaf,
                    row, true);
            ActionListener actionListener = new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    if (stopCellEditing()) {
                        fireEditingStopped();
            if (editor instanceof JPanel) {
                Object component = ((JPanel) editor).getComponent(1);
                JComboBox field = (JComboBox) component;
                field.addActionListener(actionListener);
            return editor;
        }

    Hi people!
    i create a Jtree component and create a special node, that is a <strong>JPanel with a JLabel + JCombobox</strong>!
    Only the direct childs of root have this special node.
    A can put this work properly in Windows XP, like the picture:
    [XP Image|http://feupload.fe.up.pt/get/jcgd0rY5p9PoFPG]
    And in Windows Vista the same code appear like this:
    [Vista Image|http://feupload.fe.up.pt/get/Ylajl6hlCUFc0xe]
    <strong>Hence, in Vista something append behind the JLabel and show something wyerd!</strong>
    I can't understant this and if someone can help i appreciate!
    The TreeNodeRender class is :
    public class MetaDataTreeNodeRenderer implements TreeCellRenderer {
        private JLabel tip = new JLabel();
        private JPanel panel = new JPanel();   
        private JComboBox dataMartsRenderer = new JComboBox();
        private DefaultTreeCellRenderer nonEditableNodeRenderer = new DefaultTreeCellRenderer();
        private HashMap<String, String> valueSaver = null;
        public MetaDataTreeNodeRenderer(Component treeContainer, HashMap<String, String> valueSaver, String[] valuesComboBox) {
            this.valueSaver = valueSaver;
            int width = (int)treeContainer.getPreferredSize().getWidth();
            panel.setLayout(new GridBagLayout());
            java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
            panel.setMaximumSize(new Dimension(width, 15));
            panel.setBackground(new Color(255, 255, 255, 0));
            dataMartsRenderer = new JComboBox(valuesComboBox);
            gridBagConstraints.gridx = 0;
            gridBagConstraints.gridy = 0;
            panel.add(tip, gridBagConstraints);
            gridBagConstraints.gridx = 1;
            panel.add(dataMartsRenderer, gridBagConstraints);
            tip.setLabelFor(dataMartsRenderer);       
        public JComboBox getEditableNodeRenderer() {
            return dataMartsRenderer;
        public String getTipText(){
            return this.tip.getText();
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                boolean expanded, boolean leaf, int row, boolean hasFocus) {
            Component returnValue = null;
            DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)value;
            DefaultMutableTreeNode currentNodeFather = (DefaultMutableTreeNode)currentNode.getParent();
            if(currentNodeFather != null && currentNodeFather.isRoot()){//se o meu pai &eacute; a raiz, ent&atilde;o eu sou um datamart
                                                                        //se sou um datamart, ent&atilde;o sou edit&aacute;vel.
                String dataMart = (String)currentNode.getUserObject();
                String dataMartValue = this.valueSaver.get(dataMart);
                tip.setText(dataMart);
                if(dataMartValue != null) {
                    dataMartsRenderer.setSelectedItem(dataMartValue);
                returnValue = panel;
            }else{//sou um n&oacute; n&atilde;o edit&aacute;vel.
                 returnValue = nonEditableNodeRenderer.getTreeCellRendererComponent(tree,
                         value, selected, expanded, leaf, row, hasFocus);
            return returnValue;
    }The TreeNodeEditor class is :
    public class MetaDataTreeNodeEditor extends AbstractCellEditor implements TreeCellEditor {
        MetaDataTreeNodeRenderer renderer = null;
        JTree tree;
        //Where i save all JComboBox values ( name of label, selected item in combobox), for all combbox
        HashMap<String, String> valueSaver = null;
        public MetaDataTreeNodeEditor(JTree tree, Component treeContainer, HashMap<String, String> valueSaver, String[] valuesComboBox) {
            this.tree = tree;
            this.renderer = new MetaDataTreeNodeRenderer(treeContainer, valueSaver, valuesComboBox);
            this.valueSaver = valueSaver;
        public Object getCellEditorValue() {
            JComboBox comboBox = renderer.getEditableNodeRenderer();
            String dataMart = renderer.getTipText();
            this.valueSaver.put(dataMart, (String)comboBox.getSelectedItem() );
            return dataMart;
        @Override
        public boolean isCellEditable(EventObject event) {
            boolean returnValue = false;
            if (event instanceof MouseEvent) {
                MouseEvent mouseEvent = (MouseEvent) event;
                if (mouseEvent.getClickCount() > 1) {
                    TreePath path = tree.getPathForLocation(mouseEvent.getX(), mouseEvent.getY());
                    if (path != null) {
                        Object node = path.getLastPathComponent();
                        if ((node != null) && (node instanceof DefaultMutableTreeNode)) {
                            DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node;
                            if ( treeNode.getParent() != null && ((DefaultMutableTreeNode) treeNode.getParent()).isRoot()) {
                                returnValue = true;
                            } else {
                                returnValue = false;
            return returnValue;
        public Component getTreeCellEditorComponent(final JTree tree, final Object value, boolean selected,
                boolean expanded, boolean leaf, int row) {
            Component editor = renderer.getTreeCellRendererComponent(tree, value, true, expanded, leaf,
                    row, true);
            ActionListener actionListener = new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    if (stopCellEditing()) {
                        fireEditingStopped();
            if (editor instanceof JPanel) {
                Object component = ((JPanel) editor).getComponent(1);
                JComboBox field = (JComboBox) component;
                field.addActionListener(actionListener);
            return editor;
        }

  • JTree has to update a JComboBox (URGENT!)

    Hi all,
    I have a problem using a JTree and a JComboBox. I would like my JComboBox to be updated when a user clicks on a node of the JTree. I wrote a JPanel containing the JComboBox and implementing the TreeSelectionListener. It turns out that my JPanels listens, ok. In the implementation of the listener, I just wrote code which has to empty my JComboBox... and it does it! When I use the getItemCount() method it returns 0. Great. But now, why isn't my JComboBox updated graphically?? The problem is there: although the JComboBox should be empty, the previous items stay there...Why?
    By the way, I use a DefaultComboBoxModel... so that any change to this model should be transmitted to the JComboBox. But it doesn't work (at least graphically).
    I hope someone will answer, this is a truly desesperate call! Thanks,
    Jack

    sounds like you need to revalidate() the panel after your listener on the JTree has done it stuff

  • JComboBox in JTree

    I have tried to implement the example from
    http://www.mutualinstrument.com/Easy/easy.html
    The method where I construct the body of the tree is here:
         public DefaultTreeModel createParticipantTree(Set participantSet) {
              javax.swing.tree.TreePath path = participantTree.getPathForRow(0);
              DefaultMutableTreeNode node =
                   (DefaultMutableTreeNode) path.getLastPathComponent();
              DefaultTreeModel model = (DefaultTreeModel) participantTree.getModel();
              UserObject object = null;
              UserTreeNode child = null;
              JLabel textCellRenderer = new JLabel();
              TextCellEditor textCellEditor =
                   new TextCellEditor(new javax.swing.JTextField());
              JComboBox comboBoxCellRenderer = null;
              ComboBoxCellEditor comboBoxCellEditor = null;
              PriceData priceData = null;
              VolumeData volumeData = null;
              Vector genVector = null;
              ItemListener listener = new ItemListener() {
                   public void itemStateChanged(java.awt.event.ItemEvent e) {
                        JComboBox combo = (JComboBox) e.getSource();
                        if (e.getStateChange() == java.awt.event.ItemEvent.SELECTED) {
                             recreateCurve(combo.getName(), (String) e.getItem());
              for (Iterator iter = participantSet.iterator(); iter.hasNext();) {
                   Participant participant = (Participant) iter.next();
                   LegendItemCollection legendItems =
                        chart.getXYPlot().getLegendItems();
                   String participantName = participant.getName();
                   LegendItem legendItem = null;
                   // Find appropriate legend item.
                   for (int i = 0; i < legendItems.getItemCount(); i++) {
                        legendItem = legendItems.get(i);
                        if (participantName.equals(legendItem.getLabel())) {
                             break;
                   UserObject partobject =
                        new UserText(
                             new JLabel(
                                  new TreeIcon(legendItem.getPaint()),
                                  SwingConstants.LEFT),
                             new TextCellEditor(new JTextField()),
                             participantName);
                   UserTreeNode partchild = new UserTreeNode(partobject);
                   DefaultMutableTreeNode partnode =
                        (DefaultMutableTreeNode) partchild;
                   node.add(partchild);
                   int[] newIndex = new int[1];
                   newIndex[0] = node.getChildCount() - 1;
                   model.nodesWereInserted(node, newIndex);
                   List genList = participant.getGeneratorList();
                   for (Iterator listIter = genList.iterator(); listIter.hasNext();) {
                        Generator generator = (Generator) listIter.next();
                        String duid = generator.getDuid();
                        object = new UserText(duid);
                        Vector dataVector = (Vector) generatorMap.get(duid);
                        genVector = new Vector();
                        if (dataVector != null) {
                             for (Iterator vectIter = dataVector.iterator();
                                  vectIter.hasNext();
                                  BidData bidData = (BidData) vectIter.next();
                                  if (bidData instanceof PriceData) {
                                  } else if (bidData instanceof VolumeData) {
                                       volumeData = (VolumeData) bidData;
                                       String bidText =
                                            volumeData.getBidType()
                                                 + (volumeData.getRebidNumber() > 0
                                                           + String.valueOf(
                                                                volumeData.getRebidNumber())
                                       genVector.add(bidText);
                        } else {
                             continue;
                        child = new UserTreeNode(object);
                        partnode.add(child);
                        DefaultMutableTreeNode genNode = (DefaultMutableTreeNode)child;
                        int[] newIndex1 = new int[1];
                        newIndex1[0] = partnode.getChildCount() - 1;
                        model.nodesWereInserted(partnode, newIndex1);
                        if (genVector.size() > 0 && genNode != null) {
                             java.util.Collections.reverse(genVector);
                             Object[] objects = (Object[]) genVector.toArray();
                             String[] generators = new String[objects.length];
                             for (int n = 0; n < objects.length; n++) {
                                  generators[n] = (String) objects[n];
                             comboBoxCellRenderer = new JComboBox();
                             comboBoxCellRenderer.setName(
                                  (String) ((UserText) child.getUser()).getValue());
                             comboBoxCellRenderer.addItemListener(listener);
                             comboBoxCellEditor =
                                  new ComboBoxCellEditor(comboBoxCellRenderer);
                             object =
                                  new UserComboBox(
                                       comboBoxCellRenderer,
                                       comboBoxCellEditor,
                                       generators,
                                       generators[0]);
                             genNode = (DefaultMutableTreeNode)child;
                             child = new UserTreeNode(object);
                             genNode.add(child);
                             int[] newIndex2 = new int[1];
                             newIndex2[0] = genNode.getChildCount() - 1;
                             model.nodesWereInserted(genNode, newIndex2);
                        if (genNode.getChildCount() > 0 && genNode != null) {
                             partnode.add(genNode);
                             int[] newIndex3 = new int[1];
                             newIndex3[0] = partchild.getChildCount() - 1;
                             model.nodesWereInserted(partnode, newIndex3);
                   if (partnode.getChildCount() == 0) {
                        node.remove(partnode);
                        int[] newIndex4 = new int[1];
                        newIndex4[0] = node.getChildCount() - 1;
                        model.nodesWereRemoved(
                             node,
                             newIndex4,
                             new Object[] { partchild });
              return null; //new DefaultTreeModel(top);
         }Basically the problem is that there is no problem selecting a combo box for the first time. However, on each subsequent occassion the combo box can only be selected if it is the only combobox visible in the tree.
    If anyone can see any obvious problems, please advise.

    Hi,
    I've tried the new CellRenederer but I have to then create a custom CellEditor too implementing TreeCellEditor which I have done. However, I'm not sure its right:
    class MyCellEditor implements TreeCellEditor {
    public Component getTreeCellEditorComponent( JTree tree, Object value,
    boolean selected, boolean expanded,
    boolean leaf, int row ) {
    if( value instanceof Component ) {
    return (Component )value;
    else {
    return new JLabel( value.toString() );
    public Object getCellEditorValue()
    return (new JComboBox()); // I don't know what to return here.
    public boolean isCellEditable(EventObject e) { return true; }
    public boolean shouldSelectCell(EventObject e) {  return true; }
    public boolean stopCellEditing() { return false; }
    public void cancelCellEditing() {}
    public void addCellEditorListener(CellEditorListener c) {}
    public void removeCellEditorListener(CellEditorListener c) {}
    Then when I run the code, I still just seem to be getting a textual version of the combo box. This time though, it doesn't update on double-clicking so it really must be the toString() representation.

  • How can I put JTree into drop-down List of JCombobox

    I want to create a drop-down list which shows a list of nodes. When the user clicks on a node, it should open to show the leafs. Clicking on a leaf should close the ComboboxPopup and show its value. Creating a renderer only represent my tree, but I can't trap the events.
    Here is my simplified code.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.border.*;
    import java.util.*;
    public class ComboBoxTreeDemo  extends JPanel
         static JFrame frame;
         ComboBoxRenderer renderer;
         JTree tree;
         public ComboBoxTreeDemo()
              setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
              DefaultMutableTreeNode root =  new DefaultMutableTreeNode("top");
              DefaultMutableTreeNode sub1 =  new DefaultMutableTreeNode("sub1");
              DefaultMutableTreeNode sub2 =  new DefaultMutableTreeNode("sub2");
              root.add(sub1);
              root.add(sub2);
              tree = new JTree(root);
              String[] string = {"1" };
              JComboBox jcb = new JComboBox(string);
              renderer = new ComboBoxRenderer(this);
              jcb.setPreferredSize(new Dimension(100,22));
              jcb.setEditable(true);
              jcb.setRenderer(renderer);
              JPanel jpa = new JPanel();
              jpa.setLayout(new BoxLayout(jpa, BoxLayout.PAGE_AXIS));
              jpa.setAlignmentX(Component.LEFT_ALIGNMENT);
              jpa.add(jcb);
              add(jpa);
              setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
         private static void createAndShowGUI()
              JFrame.setDefaultLookAndFeelDecorated(true);
              JFrame frame = new JFrame("ComboBoxTreeDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JComponent newContentPane = new ComboBoxTreeDemo();
              newContentPane.setOpaque(true);
              frame.setContentPane(newContentPane);
              frame.pack();
              frame.setVisible(true);
          class ComboBoxRenderer extends JPanel implements ListCellRenderer
              ComboBoxTreeDemo cbt;
              public ComboBoxRenderer(ComboBoxTreeDemo cbt)
                   this.cbt = cbt;
                   setLayout(new BorderLayout());
                   add(cbt.tree);
              public Component getListCellRendererComponent(JList list,Object value,int index, boolean isSelected,boolean cellHasFocus)
                   return this;
         public static void main(String[] args)
              javax.swing.SwingUtilities.invokeLater(new Runnable()
                   public void run()
                        createAndShowGUI();
    }

    Thank you for the excellent reference Peddi. I had played with the OAMessageChoiceBean component yesterday, but I was able to tell from your instructions that "Picklist Display Attribute" and "Picklist Value Attribute" really are not for binding to the database EO. That was the key piece of information that had me confused.
    In addition to adding the messageChoice component to the page, I needed to write some code to synchronize the picklist value with the corresponding code value, which I placed in am OAFormValueBean (hidden form field) which I could then bind to my application's database EO in the controller, running in the processFormRequest procedure:
    /** Synchronize the catalog code with the selected catalog name */
    protected void syncCatalogValues(OAPageContext pageContext,
    OAWebBean webBean, MyApplicationAMImpl am) {   
    OAMessageChoiceBean mcb =
    (OAMessageChoiceBean) webBean.findChildRecursive("CatalogName");
    OAFormValueBean cc =
    (OAFormValueBean) webBean.findChildRecursive("CatalogCode");
    String catalogDescription = mcb.getText(pageContext);
    if (catalogDescription != null) {
    String catalogCode = am.getCatalogCode(catalogDescription);
    cc.setValue(pageContext, catalogCode);
    Along with a little code to get the catalogCode value from the LOVVO, that's all it took.
    Thanks again. This was a great help.
    Pete

  • Interact with indesign javascript through Jtree

    i can display indesign script files in tree view. what is my question is if i click the indesign javascript file i want
    to execute. that means i want to interact with java swing to indesign cs3. How it is possible could anyone tell me.

    Welcome to the Sun forums.
    >
    i can display indesign script files in tree view. what is my question is if i click the indesign javascript file i want
    to execute. that means i want to interact with java swing to indesign cs3. How it is possible could anyone tell me.>About the only way you will be able to get interaction between a JTree and JavaScript is to put the JTree in a JApplet and put that applet in a web page that also references the scripts.
    As far as Java/JS interaction go, look to [Real's HowTo|http://www.rgagnon.com/howto.html] (<- link) and the categories 'Java|JavaScript Interaction' & 'JavaScript|Interaction with Java'.
    Testing will be a hassle, since the AppletViewer does not support Java/JS interaction and browsers cache the classes. Not that applet development is not a PITA to start with.
    And a few points before closing:
    - All sentences should start with a single upper case letter. This helps the reader to quickly scan text, looking for ways they can help. You would not want to make it harder for people who are trying to help, would you?
    - The word 'I' should be always upper case, always.
    - ..and it is JTree, not Jtree. Please be very careful with class names so we can all be sure you refer to J2SE classes, and not some 3rd part class about which we know nothing and do not support.
    Edited by: AndrewThompson64 on Jul 6, 2009 9:19 PM

  • JTree and JComboBox Topic

    how can i add a JTree to a JComboBox?
    Also i should be able to expand the JTree by clicking at the nodes..

    what do you want to do.
    A tree to appear when you press the button on the combo box?
    or do you want a tree to appear as one of the items in the list.
    Onve I wanted to create a multi column combo box.
    I tried lots of things to make it a subclass of JComboBox but the implementation of the popup list of the combo box highly depend on the Look And Feel so I had to write my own combo box combining a JTextArea and a JButton in a JPanel.
    I made the popup by putting a JTable inside a JScrollPane inside a JPanel inside a JPopupMenu

  • Jtree in JComboBox -- anyone have a good implementation

    Hi,
    I was just curious if anyone has created a working JTree in a JComboBox? I have searched around but haven't found much in the way of an answer. If you have, can you post some code or a link?
    thanks

    I have seen, JTreeCombo....but it is not free. Anyone have anything like it?
    thanks

  • JClient - How to use multiple interacting JComboBox controls?

    Hi there,
    I would like to use 2 or more combobox controls that interact with each other, there data is master detail (detail...). When the master is selected the detail gets filtered. Also it would be nice if the master is null that all detail items would be shown and when detail is selected the master would be set accordingly.
    For an example think of an address with the combination of country - state - city.
    Country
     â€¢ State
      o City
    USA
    ʉۢNY
      o ALBANY
      o BROOKLYN
      o BUFFALO
      o NEW YORK CITY
      o QUEENS
    ʉۢ PA
      o ALLENTOWN
      o PHILADELPHIA
      o PITTSBURGH
    ʉۢ NJ
      o ATLANTIC CITY
      o JERSEY CITY
      o TRENTON
      o NEWARK
    ʉۢ FL
      o ORLANDO
      o ST. PETERSBURG
      o TAMPA
      o MIAMI
      o DAYTONA BEACH
    CANADA
    ʉۢ ONTARIO
      o AJAX
      o TORONTO
    ʉۢ NOVA SCOTIA
      o HALIFAX
    ʉۢ BRITISH COLUMBIA
      o VANCOUVER
      o RICHMOND
    When USA is selected in the country combobox, only its states are shown in the state combobox, then when NY is selected in the state combobox only its city's are shown in the city combobox.
    If possible as a bonus it would be nice to be able to select any state when country is null and any city when both country and state are null (not selected). And when selected the parent's would be set.
    Example if country and state are not selected and MIAMI is selected as the city then state would be set to FL and country to USA automatically. This would be nice to have but not necessary.
    Only the filtering part is really needed. When country is first selected and that filters state, followed be selection of state that filters city's.
    Thank you in advance
    James

    Found a previus post about the same topic in UIX
    Master-Detail Pulldown-Menu's With PPR
    Going to try using Navigation List and see what happens.

  • JTree in JComboBox

    Hi,
    i have create a own combobox popup editor. The editor is a JPanel and contains a JTree and a JButton.
    Now when the user clicks on the combobox the user see the JTree and the Button. When now selecting a tree node or pressing the button, always the popup editor close. I cant't find out from where the event to close the editor came. What i wantis, when the user select a node this node should be expanded or when he press the button some action should be done, but without closing the combobox editor.
    Can anybody help me???
    Thanks in advance
    Wolf

    More info
    i found out that the problem is that i add the tree in a jscrollpane.
    But without a scrollpane the popup size is to large and has no horizontal scrollbar.

  • How do I use JPanel as a leaf in JTree ?

    Hi All,
    I am a bit of a newbie and I've been trying to change the behavior of my application.
    I have a JTree that I now want to change the rendering of a leaf to be a JPanel. The JPanel will have a couple of JButtons and some text and the user can interact with the JButtons. I was successful in creating the JPanel, adding the buttons and then making my own TreeCellRenderer. Everything displays fine, but the user can not interact with the JButtons, whenever I click on a button in the leaf, the whole leaf is highlighted - I suppose I should not be surprised because this is probably behaving just a cell in a JTree should.
    So I searched the forums and used Google and have found several examples of people using JCheckBox as nodes/leaf(s) in a JTree but none with a JPanel as a leaf. I took one of the check box demos from here ( [http://www.coderanch.com/t/330630/Swing-AWT-SWT-JFace/java/add-swing-component-tree]) and then hacked it a bit but am stuck with the following error :
    Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to javax.swing.JPanel
    which is pointing to the line with JPanel temp2 = (JPanel) temp.getUserObject();
    Does anyone have either some code or suggestions to accomplish a leaf as a JPanel with some buttons ?
    Thanks in advance !
    import javax.swing.*;*
    *import javax.swing.tree.*;
    import java.awt.event.*;*
    *import java.awt.*;
    public class treedemo1 extends JFrame {
        public treedemo1() {
            super("TreeDemo");
            setSize(1500, 1500);
            JPanel p = new JPanel();
            p.setLayout(new BorderLayout());
            customLeafPanel cp1 = new customLeafPanel();
            customLeafPanel cp2 = new customLeafPanel();
            customLeafPanel cp3 = new customLeafPanel();
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("Query Results");
            DefaultMutableTreeNode n1 = new DefaultMutableTreeNode(cp1, false);
            DefaultMutableTreeNode n2 = new DefaultMutableTreeNode(cp2, false);
            DefaultMutableTreeNode n3 = new DefaultMutableTreeNode(cp3, false);
            root.add(n1);
            root.add(n2);
            root.add(n3);
            JTree tree = new JTree(root);
            p.add(tree, BorderLayout.NORTH);
            getContentPane().add(p);
            TestRenderer tr = new TestRenderer();
            tree.setEditable(false);
            tree.setCellRenderer(tr);
        public class customLeafPanel extends JPanel {
            public customLeafPanel() {
                JPanel clpPanel = new JPanel();
                JButton helloJButton = new JButton("Hello");
                this.add(helloJButton);
        public class TestRenderer implements TreeCellRenderer {
            transient protected Icon closedIcon;
            transient protected Icon openIcon;
            public TestRenderer() {
            public Component getTreeCellRendererComponent(JTree tree,
                    Object value,
                    boolean selected,
                    boolean expanded,
                    boolean leaf,
                    int row,
                    boolean hasFocus) {
                DefaultMutableTreeNode temp = (DefaultMutableTreeNode) value;
                JPanel temp2 = (JPanel) temp.getUserObject();
                return temp2;
            public void setClosedIcon(Icon newIcon) {
                closedIcon = newIcon;
            public void setOpenIcon(Icon newIcon) {
                openIcon = newIcon;
        public static void main(String args[]) {
            JFrame frame = new treedemo1();
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            frame.pack();
            frame.setVisible(true);
    }

    Thank you TBM and DB for your replies ! Adding TBM's code does indeed fix the JPanel issue and as TBM indicated this does not actually solve my ultimate problem (Can I give you each 1/2 the Duke points?)
    As a newbie, I am still learning and DB pointed out that "You can however interact with an editor". So after reading the suggested tutorials and looking back at the example code that I hacked. I added the cellEditor back in and it WORKS ! Its funny, I deleted that bits of code from the example, assuming the cellEditor allows you to "edit" (ie change), not interact with it (symantics I guess)
    Thanks again guys for pointing this newbie in the right direction. Frankly I am somewhat surprised that I could finally begin to read and understand what the tutorial and suggestions are telling me ! What is one step up from a newbie ?
    unfortunately I can not post the code because the length of the message is > 5000 :(

  • 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

  • How do I make nodes in my JTree render as JTextPanes ?

    As a newbie to Java, I developed an application which started out by by having a user select a value in a JList and associated information was formatted nicely into a JTextPane (really it is just making some bold/italic/regular font switches).
    I now think it may be more visually appealing to represent the whole thing as a JTree, and the user would just click the +/- to access the associated information.
    So I would like substitute the JTree for the JList, while keep my nicely formatted JTextPane and am a bit stuck. I'd like each item in the JList to be a node and the information is going to be a leaf.
    Searching through the forums and other tutorials it I think I need to create a TreeCellRenderer that uses my JTextPane.
    Aside from advice such as Prior Planning Prevents Poor Performance, can someone give me a gentle kick in the right direction ? Pseudo-code or links would be great !
    Thanks in advance.

    Hi codingMonkey,
    I've looked at both of those (previously) but I've not got enough experience to figure out the coding bits for my application.
    So lets say I wanted to hack the JTextPane example here http://java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html and put a simple JTree in its place with three nodes and use the provided JTextPane as a text for the leafs.
    I think the important bits (except are addStylesToDocument) are this:
    private JTextPane createTextPane() {
            String[] initString =
                    { "This is an editable JTextPane, ",            //regular
                      "another ",                                   //italic
                      "styled ",                                    //bold
                      "text ",                                      //small
                      "component, ",                                //large
                      "which supports embedded components..." + newline,//regular
                      " " + newline,                                //button
                      "...and embedded icons..." + newline,         //regular
                      " ",                                          //icon
                      newline + "JTextPane is a subclass of JEditorPane that " +
                        "uses a StyledEditorKit and StyledDocument, and provides " +
                        "cover methods for interacting with those objects."
            String[] initStyles =
                    { "regular", "italic", "bold", "small", "large",
                      "regular", "button", "regular", "icon",
                      "regular"
            JTextPane textPane = new JTextPane();
            StyledDocument doc = textPane.getStyledDocument();
            addStylesToDocument(doc);
            try {
                for (int i=0; i < initString.length; i++) {
                    doc.insertString(doc.getLength(), initString,
    doc.getStyle(initStyles[i]));
    } catch (BadLocationException ble) {
    System.err.println("Couldn't insert initial text into text pane.");
    return textPane;
    I don't really understand the TreeCellRenderer API link you sent and how to link the above JTextPane to the TreeCellRenderer.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to use cell editors in JTree?

    Hi,
    I have a component where I am placing JTable in JTree node.The table cells should be editable.
    I was unable to do that.
    I am giving code for 2 classes below,which I used.
    To test this compile the classes seperately.
    /**************************TableInTree.java(main class)**************/
    import java.awt.Component;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.util.*;
    public class TableInTree extends JFrame
    public TableInTree()
    super("TableInTree");
    JTree tree = new JTree(this.createTreeModel());
    tree.setCellRenderer(new ResultTreeCellRenderer());
    tree.setEditable(true);
    this.getContentPane().add(new JScrollPane(tree));
    public static void main(String[] args)
    TableInTree frame = new TableInTree();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(800, 600);
    frame.show();
    // * Method createRootNodes.
    private TreeModel createTreeModel()
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
    DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("test1");
    node1.add(new DefaultMutableTreeNode(new TableRenderDemo)));
    root.add(node1);
    root.add(new DefaultMutableTreeNode("test2"));
    return new DefaultTreeModel(root, true);
    public static class ResultTreeCellRenderer extends DefaultTreeCellRenderer
    public Component getTreeCellRendererComponent(JTree t, Object value,boolean s, boolean o,boolean l, int r, boolean h)
    if (value instanceof DefaultMutableTreeNode)
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
    if (node.getUserObject() instanceof TableRenderDemo)
    return new JScrollPane((TableRenderDemo) node.getUserObject());
    return super.getTreeCellRendererComponent(t, value, s, o, l, r, h);
    /*******************TreeRenderDemo.java**************************/
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.table.*;
    import java.awt.*;
    * TableRenderDemo is just like TableDemo, except that it
    * explicitly initializes column sizes and it uses a combo box
    * as an editor for the Sport column.
    public class TableRenderDemo extends JPanel {
    private boolean DEBUG = false;
    public TableRenderDemo() {
    super(new GridLayout(1,0));
    JTable table = new JTable(new MyTableModel());
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Set up column sizes.
    initColumnSizes(table);
    //Fiddle with the Sport column's cell editors/renderers.
    setUpSportColumn(table, table.getColumnModel().getColumn(2));
    //Add the scroll pane to this panel.
    add(scrollPane);
    * This method picks good column sizes.
    * If all column heads are wider than the column's cells'
    * contents, then you can just use column.sizeWidthToFit().
    private void initColumnSizes(JTable table) {
    MyTableModel model = (MyTableModel)table.getModel();
    TableColumn column = null;
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    Object[] longValues = model.longValues;
    TableCellRenderer headerRenderer =
    ((JTableHeader)table.getTableHeader()).getDefaultRenderer();
    for (int i = 0; i < 5; i++) {
    column = table.getColumnModel().getColumn(i);
    comp = headerRenderer.getTableCellRendererComponent(
    null, column.getHeaderValue(),
    false, false, 0, 0);
    headerWidth = comp.getPreferredSize().width;
    comp = table.getDefaultRenderer(model.getColumnClass(i)).
    getTableCellRendererComponent(
    table, longValues,
    false, false, 0, i);
    cellWidth = comp.getPreferredSize().width;
    if (DEBUG) {
    System.out.println("Initializing width of column "
    + i + ". "
    + "headerWidth = " + headerWidth
    + "; cellWidth = " + cellWidth);
    //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
    column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    public void setUpSportColumn(JTable table,
    TableColumn sportColumn) {
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Snowboarding");
    comboBox.addItem("Rowing");
    comboBox.addItem("Knitting");
    comboBox.addItem("Speed reading");
    comboBox.addItem("Pool");
    comboBox.addItem("None of the above");
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    sportColumn.setCellRenderer(renderer);
    class MyTableModel extends AbstractTableModel {
    private String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian"};
    private Object[][] data = {
    {"Mary", "Campione",
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Huml",
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Walrath",
    "Knitting", new Integer(2), new Boolean(false)},
    {"Sharon", "Zakhour",
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Philip", "Milne",
    "Pool", new Integer(10), new Boolean(false)}
    public final Object[] longValues = {"Sharon", "Campione",
    "None of the above",
    new Integer(20), Boolean.TRUE};
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col < 2) {
    return false;
    } else {
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col
    + " to " + value
    + " (an instance of "
    + value.getClass() + ")");
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    if (DEBUG) {
    System.out.println("New value of data:");
    printDebugData();
    private void printDebugData() {
    int numRows = getRowCount();
    int numCols = getColumnCount();
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + data[j]);
    System.out.println();
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    //JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("TableRenderDemo");
    //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    TableRenderDemo newContentPane = new TableRenderDemo();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    Please give me a solution.
    thanks in advance

    rebounce

  • Popup JTree

    I created a subclass of JWindow which acts as a popup when the appropriate mousebutton is clicked. A JTree is shown in an etched border and when the user selects an item in the tree it updates the JTextField the popup is connected to. It is similar in concept to a JComboBox but rather then a list, it uses a tree. It is connected to two JTextFields in a subclass of JDialog. This works great when dialog box is run in the applet window under VAJ. However, when the dialog box is created (.show()) from within a JApplet in the browser it appears fine when the right mouse button is pressed in the appropriate JTextField but as soon as a mouse button is pressed within the popped up JTree, the popped up window (JWindow subclass) is forced behind the other window. If the roller on the microsoft mouse is used the jtree can be scrolled but if I try to manipulate the scrollbar the window disappears behind the parent window. How can I lock the window in place until I dispose of it??
    Thanks,
    Walt

    The problem is actually a problem in VAJ. The code generated by the VCE does not allow for creating the popup with a parent window. It is still unclear why when it was created on top of the 'parent' window and the scrollbar should have digested the mouse event, that the mouse event percolated through the popup to the underlying window, causing it to gain focus and be placed on top in the Z order. Anyone that can answer that one get the duke bucks too. What I did was modify the alternative constructors for the popup to initialize the window (set the listeners) which appears to be another bug in VAJ and then manually create the popup as invisible. Normally VAJ uses lazy construction to only construct the object upon first reference. Since that code is automatically regenerated by the VCE I couldn't modify it.
    Another question is why does the JWindow appear with the foolish "Java Applet Window" text in a status area. And why does a JWindow even have a status area? The drop down list of a JComboBox doesn't have one. And that was really all I wanted was a JComboBox with a tree instead of a list. So if anyone can address that, there are duke dollars available for it as well.
    So the questions are:
    1) why does the mouse action percolate through the popup window, which should have captured and digested it, even if only through the scrollbar logic?
    2) what does the JWindow based popup get stuck with the "Java Applet Window" text in an unwanted status area.
    3) how could this simply be like a JComboBox with a drop down JTree, as opposed to drop down list?
    Thanks,
    Walt

Maybe you are looking for