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.

Similar Messages

  • Updating a Jtree

    Hello frens ,
    I'm designing my project of file uploading in swings and am i'm using JCombobox n JTree.
    JCombobox contains system drives(A:,C:,D:) as the combo elemnts.
    By default the selected item in the JCombobox is C:
    The JTree contains elemnts ofthe drive(C:/D:)By default it contains elemnts C:.
    Now wht i want is when the elemnts in the Jcombobox are changed the Jtree contents shud also changed.
    Suppoose the user changes the selction in JComboBox to D:.
    Then the JTree elemnts elemnst shud consist of elemnts in D:.
    So how do i do this.I have different classes for JComboBox and JTree.
    How do i fire evnts to update the Tree.
    Thanking you
    jyo

    Just modify the tree model with the data u have.

  • Using a component as a rubber stamp

    I need to do something similar to what JTables, JLists, JComboBoxes, and JTrees do to render their individual elements. From what I understand, to save memory, they have one component which they then set whatever value on, use the component to draw, set a new value, draw the component in a new position, instead of using many individual components, saving a lot of time and memory.
    actual question
    I need to do this with a component. I want the appearance of a JComboBox, but without any of the annoying functionality.
    Right now, my paintComponent method looks like this:
      //public because the the code I'm overriding upgraded it from
      //public to protected
      public void paintComponent(Graphics g)
        //The following two lines are there to see if
        //the component actually draws. It does.
        g.setColor(java.awt.Color.RED);
        g.drawLine(0, 0, getWidth(), getHeight());
        if (!isDesignTime())
          //Draw in run time
          super.paintComponent(g);
        else
          //Draw in design time
          //This is how I am attempting to use the component as
          //a rubber stamp.
          cmbSpeakerList.setBounds(getBounds());
          cmbSpeakerList.paint(g);
      }cmbSpeakerList is a JComboBox. When in design time, it is not contained in the JPanel. I use removeAll to take it out, then in paintComponent, set its bounds to be the same as the panel's, then call paint, passing it the same Graphics object I was given. Does this make any sense?
    So, my question is, how can I make the JComboBox (and really, any JComponent, although I don't imagine I'll need this functionality too often) draw itself, but only draw itself, and not do anything else.

    I'm not using a JTree. I mentioned the JTree as an example of a component that does the same thing I want to do. Basically, all I want is the appearance of a JComboBox, but without the functionality. So, I create the component, but don't add it. Then I call paint on it with the Graphics object swing gives me. All it does is draw its background color and then exit, though. That's the problem.

  • Editing JTables

    When exactly does the isEditing() method of a JTable return FALSE, following a user edit?
    I have a table with four columns, the first three of which have JComboBoxes as DefaultCellEditors, while the last column has a custom editor allocated dependent on the combo box item selected in the second column. (It's a Query Builder!) The custom editors are/will be modelled upon the ColorEditor example in Sun's How To Use Tables guide.
    I want to disable some JButtons whenever a cell in the table is being edited, and re-enable them whenever the edit stops.
    I attempted that by testing isEditing() in the valueChanged method of a TableModelListener. However, it's always TRUE.
    I over-rode the editingStopped() method of my extended JTable class, and I can see that isEditing() does eventually become FALSE.
    I guess that answers my question, but... I can't see how I can implement the behaviour that I need. Any suggestions folks?

    I'm sure you don't want to be a personal mentor... but could I ask you to assist me further with my JTable QueryBuilder? I guess it can't hurt to ask.
    The Builder seems to be fully functional, loading other custom editors (including JTextFields, JComboBoxes, and JTrees) into the "value" column, as appropriate to the selection in the "field" column.
    There seems to be one last problem though... well, that I've found. I'll try to describe it.
    Clicking for a second time in the 'hot' (display) area of the JComboBox editor for the "field" column after bringing up the list causes the the list to disappear, and the 'hot' area to be in editable mode. Fine. But then attempting to click in any of the other table cells causes the following exception:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.plaf.basic.BasicTableUI$Handler.setDispatchComponent(BasicTableUI.java:852)
    at javax.swing.plaf.basic.BasicTableUI$Handler.adjustFocusAndSelection(BasicTableUI.java:923)
    at javax.swing.plaf.basic.BasicTableUI$Handler.mousePressed(BasicTableUI.java:889)
    at java.awt.AWTEventMulticaster.mousePressed(AWTEventMulticaster.java:222)
    at java.awt.Component.processMouseEvent(Component.java:5485)
    I'm sure my code is causing it, and I suspect that somehow it's related to the way I'm re-setting the editor in the "value" column for that row. I don't know if it's a good idea, but I'm doing that in the setValueAt() method of my TableModel class. Whenever I detect a change in value in the "field" cell, I reset the editor in the "value" cell, and ascribe a new default value to that cell.
    The exception is only thrown when attempting to move from the "field" column to any another column. It cannot be reproduced performing the same behaviour in the other columns.
    I'd be happy to provide code if you are willing to help. Cheers.

  • 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

  • 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

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

  • 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

  • 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.

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

  • JTree - changed content, refresh

    Hello,
    I have a problem in my program I can`t solve...
    basically I am using drop-down menu with different drives (c:, d:, etc.). Don`t ask me why I don`t use the JTree to display all the drives, I simply need to display each drive separately.
    when I select the drive, JTree pops up with the content of the drive.
    Problem comes in, when the JTree is already displayed and I go into my drop-down menu to select a different drive.... Everything seems to work fine in background.... The tree gets build up, I just somehow cannot update (or refresh) the screen....
    did anyone experienced similar problem?
    thank you
    Otakar

    No, I am not using TreeModel.. Let me post the code... I am using 3 different files:
    MainModule.java
    DetectDrives.java
    FileSystem.java
    I think You might wanna see the ChoiceListener in MainModule
    thank you for you time
    MainModule.java
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    import java.awt.*;
    import java.awt.event.*;
    public class MainModule{
         private JFrame aFrame;         // BASE frame
         private JPanel driveListPane;
         private JList  driveList;
         // MENU Bar Components
         private JMenuBar aMenuBar;
         private JMenu fileMenu, editMenu, viewMenu, settingsMenu, helpMenu;
         private JMenuItem newMenuItem, openMenuItem, saveMenuItem,                // FILE menu Items
                                           saveAsMenuItem, exitMenuItem,                     //
                                           selectDriveMenuItem, selectOutputMenuItem;        // SETTINGS menu Items
          // ComboBox
         private JComboBox aComboBox;
          // Buttons
         private JButton selectDriveButton, printButton;
         // Listeners
         private PrintButtonListener prtListener;
         private ChoiceListener choiceListener;
         // Labels
         private JLabel sourceLabel, label1, label2;
         private int listRows;
         public static String drive;
         private DetectDrives dd;
         private FileSystem fs;
         private int ct;
         /*============ CONSTRUCTOR ===========================================================\
         |
         public MainModule(){
             ct = 0;
              // create a MAIN WINDOW (Frame)
              drive = new String("C:\\");
              aFrame = new JFrame("Otax Drive Printer 0.99b");
              aFrame.setSize(800, 600);
              aFrame.setLocation(100, 50);
              aFrame.getContentPane().setLayout(null);
              aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // create the categories in a menu bar
              aMenuBar = new JMenuBar();
              fileMenu = new JMenu("File");
              editMenu = new JMenu("Edit");
              viewMenu = new JMenu("View");
              settingsMenu = new JMenu("Settings");
              helpMenu = new JMenu("Help");
              // create menu items for FILE menu
              newMenuItem = new JMenuItem("New", 'N');
              openMenuItem = new JMenuItem( "Open", 'O');
              saveMenuItem = new JMenuItem( "Save", 'S' );
                     saveAsMenuItem = new JMenuItem( "Save As", 'A');
                     exitMenuItem = new JMenuItem("Exit", 'E');
              // create menu items for SETTINGS menu
                     selectDriveMenuItem = new JMenuItem("Select Drive", 'D');
                     selectOutputMenuItem = new JMenuItem("Select Output", 'O');
              // detect drives mounted to system and put them into JComboBox
              dd = new DetectDrives();
              aComboBox = new JComboBox(dd.detectCdDrives());
              aComboBox.setBounds(100, 5, 180, 20);
              //create labels
              sourceLabel = new JLabel("Select Source:");
              sourceLabel.setBounds(6, 4, 90, 20);
                     label1 = new JLabel("Current Drive: ");
              label1.setBounds(2, 500, 90, 20);
              label2 = new JLabel();
              label2.setBounds(85, 500, 50, 20);
              //create buttons
              printButton = new JButton("Print");
              printButton.setBounds(2, 50, 101, 16);
                     //create Accelerators for FILE MenuItems
                     newMenuItem.setAccelerator(KeyStroke.getKeyStroke(
                   KeyEvent.VK_N, InputEvent.CTRL_MASK, false));
              saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(
                   KeyEvent.VK_S, InputEvent.CTRL_MASK, false));
              //create the action listeners (listener definitions bellow)
              prtListener = new PrintButtonListener();
              choiceListener = new ChoiceListener();
              //connect the action listeners with menu items
              printButton.addActionListener(prtListener);
              aComboBox.addActionListener(choiceListener);
         // LISTENERS Definitions start HERE ====================================
         public class PrintButtonListener implements ActionListener{
              public void actionPerformed(ActionEvent e){
                   System.out.println("print action performed: " + drive);
         public class ChoiceListener implements ActionListener{
             public void actionPerformed( ActionEvent e)
                  ct++;
                  System.out.println(ct + " event started");
               String drive = new String(aComboBox.getSelectedItem().toString().substring(0,2));
               label2.setText(drive);
               fs = new FileSystem(drive + "//");
               fs.sortFiles();
               fs.addNodes(drive);
               DefaultMutableTreeNode top = fs.getNodes();
               JTree tree = new JTree(top);
               tree.setBounds(10, 30, 500, 450);
                  aFrame.getContentPane().add(tree);
               aFrame.repaint();
         public void addComponents(){
              aMenuBar.add(fileMenu);        // create menu
              aMenuBar.add(editMenu);
              aMenuBar.add(settingsMenu);
              aMenuBar.add(helpMenu);
              fileMenu.add(newMenuItem);     //add items to the FILE menu
              fileMenu.add(openMenuItem);
              fileMenu.addSeparator();
              fileMenu.add(saveMenuItem);
                     fileMenu.add(saveAsMenuItem);
                     fileMenu.addSeparator();
                     fileMenu.add(exitMenuItem);
              settingsMenu.add(selectDriveMenuItem);
              settingsMenu.add(selectOutputMenuItem);
              aFrame.setJMenuBar(aMenuBar);
              aFrame.getContentPane().add(aComboBox);
              aFrame.getContentPane().add(sourceLabel);
              aFrame.getContentPane().add(label1);
              aFrame.getContentPane().add(label2);
              aFrame.setVisible(true);
         public static void main(String [] args){
              MainModule m1 = new MainModule();
              m1.addComponents();
    DetectDrives.java
    import java.io.*;
    import java.util.Vector;
    import javax.swing.filechooser.*;
    public class DetectDrives{
         private FileSystemView fsv;
         private File[] roots;
         private Vector drives;
         /*======== CONSTRUCTOR =====================================================================\
         |Purpose: To INITIALIZE the object                                                          |
         |Variables: (FileSystemView) fsv - creates the Object containing info about current system  |
         |           (File[]) roots - array used to store all drives currently mounted to system     |
         |           (Vector) drives - vector used for storage of selected info about drives         |
           \==========================================================================================*/
         public DetectDrives(){
              drives = new Vector(0,1); // *Create empty Vector(0) with expansion capacity (1)
              //--- Get a FileSystemView object for the current system
             fsv = FileSystemView.getFileSystemView();
            //--- Get an array of File objects describing the 'roots' attached to the system
              roots = File.listRoots();
         /*SD1)==== Method detectCdDrives() ========================================================\
         |Purpose: To SCAN the system for any drives mounted and add DRIVE LETTER and DRIVE NAME    |
         |         to a Vector. It Also CHECKS if drive CONTAINS any DATA or if it`s EMPTY.         |
         |Variables: (int) i - a loop iterator                                                      |
         |           (String) cdInfo - temporary storage for drive information during drive check   |
         |           (Vector) drives - storage for driveletter and drive name for all drives        |
         |                             This Vector is returned upon function call                   |
         public Vector detectCdDrives(){
              String cdInfo;
              //SCAN system and RETRIEVE drives
              for(int i = 0; i < roots.length; i++){
                   if((fsv.getSystemDisplayName(roots)).equals("")) //--FIND OUT if any DATA on DRIVE
                        cdInfo = fsv.getSystemTypeDescription(roots[i]) + " ";
                   else
                   cdInfo = fsv.getSystemDisplayName(roots[i]);
                   drives.addElement(roots[i].getPath() + " " + cdInfo.substring(0, cdInfo.length()-5));
              return drives;
    FileSystem.java
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    import java.io.File;
    import java.io.*;
    import java.util.Vector;
    public class FileSystem{
         private String driveLetter;
         private Vector root;
         private Vector dirs;
         private Vector files;
         private File dir;
         private File [] allFiles;
         private DefaultMutableTreeNode top;
         /*================= File System Constructor ================================\
         |Purpose: To initialize the conject and to accept drive letter selected in  |
         |         main module                                                       |
         public FileSystem(String dl){
              driveLetter = dl;
        /*================= Method: sortFiles() ====================================\
         |Purpose: To sort content of selected drive, directories (alphabetically),  |
         |         followed by files (alphabeticaly)                                 |
         public void sortFiles(){
              dir = new File (driveLetter);
              allFiles = dir.listFiles();
              root  = new Vector(2,1);
              dirs  = new Vector(0,1);
             files = new Vector(0,1);
             //---- Separate Directories and Files into 2 different vectors
             for(int i = 0; i < allFiles.length; i++){
                   if(allFiles.isDirectory())
                   dirs.add(allFiles[i]);
                   else
                   files.add(allFiles[i]);
              //---- Add elements from dirs and files Vectors into root vector
              for(int i = 0; i < dirs.size(); i++){
                   root.add(dirs.elementAt(i));
              for(int i = 0; i < files.size(); i++){
                   root.add(files.elementAt(i));
    /*================= Method: addNodes() =====================================\
         |Purpose: to build the file structure which will be used to create the tree |
         |Variables: drive = used to accept the drive letter representing the root |
         | top = primary (root) node in the structure) |
    | root = vector of all files in the drive |
         public void addNodes(String drive){
              top = new DefaultMutableTreeNode(drive);
              DefaultMutableTreeNode node = null;
              for(int i = 0; i < root.size(); i++){
                   node = new DefaultMutableTreeNode(root.elementAt(i));
                   top.add(node);
    /*================= Method: getNodes() =====================================\
         |Purpose: To return variable top, which holds the files structure and will |
         | be used to build the tree |
    public DefaultMutableTreeNode getNodes(){
              return top;

Maybe you are looking for

  • Page Display setting problem in Form 10g

    Hi All: I am using Oracle Developer Forms [32 Bit] Version 10.1.2.0.2. I have created a Form. When I execute the form it does not maximize the MDI window on the Page. Form doest not fit into the window although I have tried to change the Width and He

  • MacMini white Pixels

    Hallo everyone, I am having a problem with my Mac Mini. When I start it up normally I have a lot of white pixels on my display. When I start it up in Safe Boot everything is normal. I already changed the RAM, installed OS Tiger new, reseted the smc.

  • Premiere Elements 8 - Still pictures in PE are blurred compared to original

    My system is Intel Q6600 CPU, Windows 7 64bit, 6GB memory, 1TB C: drive, 2TB E:drive, NVIDIA GeForce GT 220 video card, Premiere Elements 8, using Microsoft Office Picture manager to look at still originals. The Premiere Elements 8 project settings i

  • Watermark PDF Action (Offset x,y now working)

    I can create a watermarked PDF just fine, however, Automator freezes when I try to change the x and y offsets. As soon as I put the cursor in the box and try to change the value from 0, Automator will freeze. Any workarounds?

  • Adobe xi std will not print to pdf access denied

    Upgraded to XI std from v9 pro OS is Win7 XI will not print to pdf access denied v9 pro prints to pdf found no solution from web and forum search found others the issue will this issue be corrected in XI? thanks hime