ZipFiles and JTree

I am developing a tool which compares to source zip files and generate report. I got stuck in the middle of the project.
Do anybody help in extracting z zip file and displaying the whole contents in zip file using JTree format. I was able to extract the contents from the zip file but couldn't display those contents using JTree.

Follow the bouncing link. As always Google is your friend.
http://www.google.com/search?hl=en&q=Java+%2B+extracting+zip+file
Cheers,
PS

Similar Messages

  • Zipfile and zipinputstream code

    Hi!
    I need to unzip something that is in a bytearrayoutputstream. Since zipfile and zipinputstream does not receive bytearrayoutputstream I thought of creating my own but I don't know how to do that. I need someone to help me with the code. I need a code not advice please.
    All I know is that it should extend to zipfile .
    Please help

    ** a simple unZIP tool
    ** ex.  java UnZip file.zip file1   to unzip file 1 from file.zip
    **      java UnZip file.zip         to unzip file.zip
    import java.io.*;
    import java.util.*;
    import java.util.zip.*;
    import java.text.*;
    class UnZip {
      public static void main(String args[]) throws IOException {
        InputStream in = new BufferedInputStream(new FileInputStream(args[0]));
        ZipInputStream zin = new ZipInputStream(in);
        ZipEntry e;
        while((e=zin.getNextEntry())!= null) {
          if (args.length > 1) {
            if (e.getName().equals(args[1])) {
               unzip(zin, args[1]);
               break;
           unzip(zin, e.getName());
        zin.close();
      public static void unzip(ZipInputStream zin, String s) throws IOException {
        System.out.println("unzipping " + s);
        FileOutputStream out = new FileOutputStream(s);
        byte [] b = new byte[512];
        int len = 0;
        while ( (len=zin.read(b))!= -1 ) {
          out.write(b,0,len);
        out.close();
    Courtesy of : http://www.rgagnon.com/javadetails/java-0067.html and http://www.rgagnon.com/howto.html

  • Consume MouseEvent to prevent JList and JTree from receiving?!

    I have a JTree and a JList where I have made the CellRenderer so that it has a "button" area. When this button is clicked, I want something to happen. This I have achieved just nicely with a MouseListener, as per suggestion from JavaDocs.
    However, the problem is that when a click is deemed to be within the "button", I do not want the tree or list to process it anymore. But doing e.consume(), both on mousePressed or mouseClicked (though it obviously is pressed the JList and JTree themselves listen to) doesn't do jack.
    How can I achieve this functionality?

    da.futt wrote:
    stolsvik wrote:
    Okay, I managed with a hack: It is the order of listeners that's the problem: The ListUI's MouseListener is installed before mine, and hence will get the MouseEvent before me, so it has already processed it when I get it, and hence consuming it makes no difference. No. Normally, listeners are notified latest-registered to earliest-registered. I don't remember seeing an exception to that rule in the core API. well, you are both right (or wrong ;-) - the rule is: the order of listener notification is undefined, it's an implementation detail which listeners must not rely on. "Anecdotical" experience is that AWTListeners are notified first-registered-first-served, while listeners to swing specific events are notified last-registered-first-served. Below is a snippet (formulated in context of SwingX convenience classes, too lazy ...) showing that difference.
    The latter probably stems from hefty c&p of notification by walking the EventListenerList: the earliest code was implemented very near the beginning of Swing when every little drop of assumed performance optimization was squeezed, such as walking from back to front. Using EventListenerList involves lots of code duplication ... so lazy devs as we all are, simply c&p'ed that loop and just changed the concrete event type and method name. More recently, as in the we-use-all-those-nifty-cool-language-features ;-) I've seen more usage of forEach loops (f.i. in beansbinding) so notification is back to first-in-first-served :-)
    Bottom line: don't rely on any sequence - if needed, use an eventBus (or proxy or however it's called) and define the order there. Darryl's suggestion is as close as we can get in Swing (as it's not supported) but not entirely safe: there's no way to get notified when listeners are added/removed and no hook where to plug-in such a bus into the ui-delegate where it would belong.
    Cheers
    Jeanette
    // output
    02.10.2009 14:21:57 org.jdesktop.swingx.event.EventOrderCheck$1 mousePressed
    INFO: first added mouseListener
    02.10.2009 14:21:57 org.jdesktop.swingx.event.EventOrderCheck$2 mousePressed
    INFO: second added mouseListener
    02.10.2009 14:21:58 org.jdesktop.swingx.event.EventOrderCheck$4 valueChanged
    INFO: second added listSelectionListener
    02.10.2009 14:21:58 org.jdesktop.swingx.event.EventOrderCheck$3 valueChanged
    INFO: first added listSelectionListener
    // produced by
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.util.logging.Logger;
    import javax.swing.JList;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import org.jdesktop.swingx.InteractiveTestCase;
    import org.jdesktop.test.AncientSwingTeam;
    public class EventOrderCheck extends InteractiveTestCase {
        public void interactiveOrderAWTEvent() {
            JList list = new JList(AncientSwingTeam.createNamedColorListModel());
            MouseListener first = new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    LOG.info("first added mouseListener");
            MouseListener second = new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    LOG.info("second added mouseListener");
            list.addMouseListener(first);
            list.addMouseListener(second);
            ListSelectionListener firstSelection = new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if (e.getValueIsAdjusting()) return;
                    LOG.info("first added listSelectionListener");
            ListSelectionListener secondSelection = new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if (e.getValueIsAdjusting()) return;
                    LOG.info("second added listSelectionListener");
            list.addListSelectionListener(firstSelection);
            list.addListSelectionListener(secondSelection);
            showWithScrollingInFrame(list, "event order");
        @SuppressWarnings("unused")
        private static final Logger LOG = Logger.getLogger(EventOrderCheck.class
                .getName());
        public static void main(String[] args) {
            EventOrderCheck test = new EventOrderCheck();
            try {
                test.runInteractiveTests();
            } catch (Exception e) {
                e.printStackTrace();
    }

  • Problem with JPopupMenu and JTree

    Hi,
    Is there any way to have different JPopupMenu for every node.
    When I right click on the treenode there is popup menu have a "*JCheckBoxMenuItem*". By default the value of that checkbox is false. Now when i try to right click on a particular node and select the checkbox the selected value gets applied to rest of all nodes also.
    How can i just set the value of the checkbox to one perticular node.
    my code is
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TreePopupMenuTest {
      public JComponent makeUI() {
        JTree tree = new JTree();
        tree.setComponentPopupMenu(new TreePopupMenu());
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(tree));
        p.setPreferredSize(new Dimension(320, 240));
        return p;
      class TreePopupMenu extends JPopupMenu {
        private TreePath path;
        private JCheckBoxMenuItem compress=new JCheckBoxMenuItem("Compress");
        public TreePopupMenu() {
          super();
          add(compress);
          compress.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ie) {
                            if(compress.getState()){
                                 compress.setState(true);
                                    System.out.println("compress clicked");
                            else{
                                 compress.setState(false);
                                    System.out.println("uncompress");
        public void show(Component c, int x, int y) {
          JTree tree = (JTree)c;
          path = tree.getPathForLocation(x, y);
          if(path!=null && path==tree.getAnchorSelectionPath()) {
            super.show(c, x, y);
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new TreePopupMenuTest().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }Please help me as soon as possible.
    Thanks.
    Edited by: Kavita_S on Apr 23, 2009 11:49 PM

    Hi,
    Do you know this link?
    [How to Use Trees|http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html]
    Please help me as soon as possible.Sorry that I'm not good at English, I don't understand what you mean.
    Anyway, here's a quick example:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TreePopupMenuTest3 {
      public JComponent makeUI() {
        JTree tree = new JTree();
        tree.setComponentPopupMenu(new TreePopupMenu());
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(tree));
        p.setPreferredSize(new Dimension(320, 240));
        return p;
      class TreePopupMenu extends JPopupMenu {
        private TreePath path;
        private JCheckBoxMenuItem compress = new JCheckBoxMenuItem("Compress");
        public TreePopupMenu() {
          super();
          add(compress);
          compress.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ie) {
              if (compress.getState()) {
                System.out.println("compress clicked");
                setSelectedPath(path, true);
              } else {
                System.out.println("uncompress");
                setSelectedPath(path, false);
        public void show(Component c, int x, int y) {
          JTree tree = (JTree)c;
          path = tree.getPathForLocation(x, y);
          if (path!=null && path==tree.getAnchorSelectionPath()) {
            compress.setState(isSelectedPath(path));
            super.show(c, x, y);
      class MyData {
        public boolean flag;
        public String name;
        public MyData(String name, boolean flag) {
          this.name = name;
          this.flag = flag;
        @Override public String toString() {
          return name;
      //private Set<TreePath> selectedPath = new HashSet<TreePath>();
      private void setSelectedPath(TreePath p, boolean flag) {
        //if (flag) selectedPath.add(p);
        //else    selectedPath.remove(p);
        DefaultMutableTreeNode node =
              (DefaultMutableTreeNode)p.getLastPathComponent();
        Object o = node.getUserObject();
        if (o instanceof MyData) {
          ((MyData)o).flag = flag;
        } else {
          node.setUserObject(new MyData(o.toString(), flag));
      private boolean isSelectedPath(TreePath p) {
        //return selectedPath.contains(p);
        Object o =
              ((DefaultMutableTreeNode)p.getLastPathComponent()).getUserObject();
        return (o instanceof MyData)?((MyData)o).flag:false;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new TreePopupMenuTest3().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

  • JSplitPane, JScrollPane and JTree resizing

    Hi,
    In a JSplitPane, I have, in the left part, a JScrollPane, containing a JTree and, in the right part, I have an other panel.
    When I click on different nodes in the JTree, the width of the left part changes, so the JSplitPane separator moves. How to avoid that ? I would prefer a scrolling move inside the JScrollPane !
    I am using JDK 1.3
    Thanks
    Olivier Scalbert

    Try to define the JScrollPane as
    public JScrollPane(Component view, int vsbPolicy, int hsbPolicy)
    Use vsbPolicy and hsbPolicy like the VERTICAL_SCROLLBAR_AS_NEEDED
    HORIZONTAL_SCROLLBAR_AS_NEEDED respectively.
    Then define the setPreferredSize to your JScrollPane. This preferredSize must be smaller than the size of the Component view if you want to see the ScrollBar.
    By the way, when you define your JSplitPane have to define the setOneTouchExpandable(true);?

  • Vector and Jtree 4Duke

    hi
    i am having poblem with my jtree as i am not able to show the object in my vector as a different node
    {each object is node of my tree}
    unfortunately they all appear flat in the root, and in sequence{as one node} ??
    i have done everything but still no answer??
    thanks in advance for any solution
    public class Gui extends JFrame
    {  Vector root = new Vector();
    public JTree theTree ;
    public SERGui( )
    System.out.println(root.size());//root vector is empty
    roott = new DefaultMutableTreeNode (root);
    model = new DefaultTreeModel (roott) ;
    theTree = new JTree (model);      
    public Vector addOne(String newString)
    if (!root.contains(getQuery))
               root.add(newString);
    model.reload();
    // //updateTree(); i also try this method whiich does not work
    return root;
    public void updateTree(){
    DefaultMutableTreeNode v = (DefaultMutableTreeNode)theTree.getModel().getRoot();
    for(int i=0;i<root.size();i++)
                   DefaultMutableTreeNode node = (DefaultMutableTreeNode)root.elementAt(i);
                   roott.add(node);
    ((DefaultTreeModel)theTree.getModel()).reload(v);
    //DefaultMutableTreeNode node = null;
    print_vector(root);
      //root.clear();
         }and my other class
    where i call this methos is as follow
    Class Search()
    public void countWord(String newString)
    {Gui.addOne(newString);
    }}

    You are passing a Vector into the constructor of the DefaultMutableTreeNode to create the root of your tree. The DefaultMutableTreeNode will use this object's string representation (by calling toString on whatever object you pass in its constructor) as the name of the tree node. So basically you will see the entire contents of the vector as the name of your root node.
    You need to traverse your vector, and use each element to create a DefaultMutableTreeNode and add it to your root node.
    here is the modified code
    public class Gui extends JFrame {
    private Vector rootVector = new Vector();
    private JTree theTree;
    private DefaultMutableTreeNode rootNode;
    private DefaultTreeModel model;
    public Gui() {
    System.out.println(rootVector.size());
    //root vector is empty
    rootNode = new DefaultMutableTreeNode("Root");
    model = new DefaultTreeModel(rootNode);
    theTree = new JTree(model);
    public Vector addOne(String newString) {
    if (!rootVector.contains(newString)) {
    rootVector.add(newString);
    updateTree();
    return rootVector;
    public void updateTree() {
    rootNode.removeAllChildren();
    for (int i = 0; i < rootVector.size(); i++) {
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(
    rootVector.elementAt(i));
    rootNode.add(node);
    ((DefaultTreeModel) theTree.getModel()).reload(rootNode);
    Hemant Mahidhara

  • JSplitPane and Jtree

    Hi all,
    in my window I've got a JSplitPane with the left component that is a JScrollPane with a Jtree (used as a menu), while in the right side a customized JPanel that changes depending on the selection in the tree on the left.
    My panels are initially created as follows:
         this.splitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
         this.splitter.setOneTouchExpandable(true);
    JScrollPane leftPanel = new JScrollPane( this.menuTree );
              leftPanel.setMinimumSize( new Dimension(300,300) );     
              leftPanel.setMaximumSize(leftPanel.getMinimumSize());
              // add the leftt and right panels
              this.splitter.setLeftComponent( leftPanel );
              this.imagePanel = new ImagePanel(ComponentBuilder.getLogoPath());
              this.rightPanel = this.imagePanel;
              this.splitter.setRightComponent(this.rightPanel);
              // add the splitter to myself
              this.add(new JScrollPane(this.splitter));where the imagepanel is a working panel that shows the project logo. Now what happens is that:
    1) the logo is cutted to a size I don't know how is calculated, since the image panel is working fine (if I place on a separate window I can see the image right)
    2) most important when a user selects something in the tree on the left panel, so the right panel changes, the left panel is moved around the window depending on the size of the right panel.
    Is it possible to fix the left panel not only as size, but also in the position of the window, thus the remaining part of the window will be occupied by the right panel without moving the left one? In my frame I'm using a BorderLayout, and the panel containing the splitpane is set at the center (no components on the right and on the left).
    Thanks,
    Luca

    Thanks for your reply, but the only thing I noticed is that the code you're showing works a little more with sizes, that is something I've already tried. By the way, the following is a running example that loads a tree/menu and the logo.png image.
    Any idea about its behaviour?
    Thanks,
    Luca
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.awt.image.*;
    class ImagePanel extends JPanel implements ImageObserver
         * The image to display
        protected Image image=null;
         * This flag indicates if the image is complete or not.
        protected boolean isComplete=false;
         * The dimension of the panel.
        protected int width=0,height=0;
         * This is the message to display during loading.
        protected String message="Loading...";
         * Default constructor.
         * @param image the image object.
        public ImagePanel(Image image)
              super();
              this.image=image;
         * Overloaded constructor. It try to load the image itself. You should use
         * this to avoid image flicking problems. This method use all the
         * capabilities of the ImageObserver.
         * @param image the image file name
        public ImagePanel(String image) {
              super();
              /* now load the image */
              Toolkit tk=Toolkit.getDefaultToolkit();
              this.image=tk.getImage(image);
              /* use the media tracker to wait untill the image is not loaded */
              try{
                  MediaTracker tracker=new MediaTracker(this);
                  tracker.addImage(this.image,0);
                  tracker.waitForID(0);
                  this.isComplete=true;
                  /* now that the image is fully loaded I need to resize the panel to
                  the size of the image */
                  this.width=this.image.getWidth(this);
                  this.height=this.image.getHeight(this);
                  this.setSize(width,height);
                  this.setMinimumSize(getSize());
                  this.setMaximumSize(getSize());
                  this.setVisible(true);
              catch(InterruptedException e){
                  this.message="Exception during loading process!";
                  this.isComplete=false;
         * Draw the image.
        public void paint(Graphics device)   {
              super.paint(device);
              if(this.isComplete==true)     {
                  device.drawImage(this.image,0,0,this.width,this.height,this);
              else     {
                  device.setColor(Color.RED);
                  device.drawString(this.message,20,20);
         * The update image method. This method is called for every update and or
         * error.
        public boolean imageUpdate(Image image,int infoFlags, int x, int y,
                        int width, int height)
              if((infoFlags & ALLBITS)==0)
                  /* the image is complete */
                  this.isComplete=true;
                  repaint();
                  this.setVisible(true);
                  return false;
              else
              if((infoFlags & ERROR)==0 || (infoFlags & ABORT)==0 )
                  /* error or abort */
                  this.isComplete=false;
                  this.message="Error during load process (or abort)";
                  this.repaint();
                  return true;
              else
              if((infoFlags & SOMEBITS)==0)
                  /* some other data loaded, show the loading process percent */
                  int originalWidth=this.image.getWidth(this);
                  int originalHeight=this.image.getHeight(this);
                  int currentWidth=image.getWidth(this);
                  int currentHeight=image.getHeight(this);
                  /* now calculate the total of pixels */
                  long originalTotal=originalWidth*originalHeight;
                  long currentTotal=currentWidth*currentHeight;
                  /* now calculate the percent */
                  float percent=(float)currentTotal/(float)originalTotal *100;
                  /* set the string */
                  this.message="Loading progress: "+(int)percent+" % done";
                  this.repaint();
                  return true;
              return true;
    public class MainPanel extends JPanel {
          * The split pane used for this panel.
         protected JSplitPane splitter = null;
          * The menu tree of this panel.
         protected JTree menuTree = null;
          * The parentFrame frame of this panel
         protected JFrame parentFrame = null;
          * The panel on the right of the window.
         protected JComponent rightPanel = null;
          * The menuTreeRoot node of the menu.
         protected DefaultMutableTreeNode menuTreeRoot = null;
          * The action menu of the JFrame that contains this panel. Such menu is changed depending on the panel
          * shown on the right panel.
         protected JMenu actionMenu = null;
          * The image panel with the image of the logo.
         protected ImagePanel imagePanel = null;
         public final String ROOT_STRING = "Gestione delle risorse umane";
         public final String LEVEL1A_STRING = "Parametrizzazione";
         public final String LEVEL2AA_STRING = "Competenze & Famiglie di competenze";
         public final String LEVEL2AB_STRING = "Gestione dei ruoli";
         public final String LEVEL2AC_STRING = "Associazione ruolo-competenza";
         public final String LEVEL1B_STRING   = "Varie";
         public final String LEVEL2BB_STRING = "Province";
         public final String LEVEL2BC_STRING = "Citta'";
         public final String LEVEL2BD_STRING = "Livelli di istruzione";
         public final String LEVEL2BE_STRING = "Livelli di competenza";
         public final String LEVEL3A_STRING   = "Personale";
         public final String LEVEL3AA_STRING = "Anagrafica di base";
         public final String LEVEL3AB_STRING  = "Ruoli, Competenze e Gradi di Istruzione";
         public final String LEVEL3AC_STRING  = "Storia delle valutazioni delle competenze";
         public final String LEVEL3AD_STRING  = "Valutazione";
          * Default constructor.
          * @param parentFrame the jframe that contains this panel
         public MainPanel(JFrame parent, JMenu actionMenu){
              super();
              this.parentFrame = parent;
              this.initGUI();
              this.actionMenu = actionMenu;
          * Shows the components on the main panel.
         public synchronized void initGUI(){
              // create the split pane
              this.splitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
              this.splitter.setOneTouchExpandable(true);
              //this.splitter.setResizeWeight(0);                    // the right panel gets all the extra space
              // create the left panel with the tree
              DefaultMutableTreeNode root = new DefaultMutableTreeNode(ROOT_STRING);
                   DefaultMutableTreeNode level1a = new DefaultMutableTreeNode(LEVEL1A_STRING);
                        ContainerTreeNode level2aa = new ContainerTreeNode(LEVEL2AA_STRING);     // skills and families
                   DefaultMutableTreeNode level2ab = new DefaultMutableTreeNode(LEVEL2AB_STRING);
                        DefaultMutableTreeNode level2ac = new DefaultMutableTreeNode(LEVEL2AC_STRING);
                   DefaultMutableTreeNode level1b = new DefaultMutableTreeNode(LEVEL1B_STRING);
                        DefaultMutableTreeNode level2bb = new DefaultMutableTreeNode(LEVEL2BB_STRING);
                        DefaultMutableTreeNode level2bc = new DefaultMutableTreeNode(LEVEL2BC_STRING);
                        DefaultMutableTreeNode level2bd = new DefaultMutableTreeNode(LEVEL2BD_STRING);
                        DefaultMutableTreeNode level2be = new DefaultMutableTreeNode(LEVEL2BE_STRING);
                   DefaultMutableTreeNode level3a = new DefaultMutableTreeNode(LEVEL3A_STRING);
                        DefaultMutableTreeNode level3aa = new DefaultMutableTreeNode(LEVEL3AA_STRING);
                        DefaultMutableTreeNode level3ab = new DefaultMutableTreeNode(LEVEL3AB_STRING);
                        DefaultMutableTreeNode level3ac = new DefaultMutableTreeNode(LEVEL3AC_STRING);
                        DefaultMutableTreeNode level3ad = new DefaultMutableTreeNode(LEVEL3AD_STRING);
              // create the tree
              this.menuTreeRoot = root;
              level2ab.add(level2ac);
              level1a.add(level2aa);
              level1b.add(level2bc);
              level1b.add(level2bb);
              level1b.add(level2bd);
              level1b.add(level2be);
              level3a.add(level3aa);
              level3a.add(level3ab);
              level3a.add(level3ac);
              level3a.add(level3ad);
              root.add(level3a);
              root.add(level2ab);
              root.add(level1a);
              root.add(level1b);
              this.menuTree = new JTree(root);
              this.menuTree.setSize(200,200);
              JScrollPane leftPanel = new JScrollPane( this.menuTree );
              leftPanel.setMinimumSize( new Dimension(300,300) );     // it does not affects the dimension, but avoid to resize the left panel
              leftPanel.setMaximumSize(leftPanel.getMinimumSize());
              // add the leftt and right panels
              this.splitter.setLeftComponent( leftPanel );
              this.imagePanel = new ImagePanel("logo.png");
              this.rightPanel = this.imagePanel;
              this.rightPanel.setSize(400,400);
              this.splitter.setRightComponent(this.rightPanel);
              // add the splitter to myself
              this.add(new JScrollPane(this.splitter));
         public static void main(String argv[]){
             JFrame f = new JFrame();
             f.setSize(400,400);
             f.add(new MainPanel(f,null));
             f.setVisible(true);
    }

  • Leaf and JTree

    Hi all,
    I would like to ask a small question about JTree. Is there a way to not display leaf without removing them from the tree?
    Actually I used a tricky whay by crating my own DefaultTreeCellRenderer and checking when it's the leaf I set the preferedSize to 0. However, by using this tricky way i have some weird behaviour with scrollPane.
    Does anyone has an idea to not display leaf in a JTree?
    Regards,
    Raffael

    Raffael wrote:
    Hello,
    thanks for your anserw. However, creating your own JTreeModel allow you to specify if a node is a leaf or not. But you will not being able to not draw it via the tree model or I m wrong?Your custom TreeModel will have to 'hide' the leaf nodes from objects that ask about them. Here's an example that wraps a DefaultTreeModel:
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.WindowConstants;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    public class HiddenLeaves {
        HiddenLeaves() {
            JFrame f= new JFrame();
            f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
            DefaultMutableTreeNode nodeA = new DefaultMutableTreeNode("Node A");
            nodeA.add(new DefaultMutableTreeNode("Leaf One"));
            nodeA.add(new DefaultMutableTreeNode("Leaf Two"));
            nodeA.add(new DefaultMutableTreeNode("Leaf Three"));
            DefaultMutableTreeNode nodeB = new DefaultMutableTreeNode("Node B");
            nodeB.add(new DefaultMutableTreeNode("Leaf Four"));
            nodeB.add(new DefaultMutableTreeNode("Leaf Five"));
            nodeB.add(new DefaultMutableTreeNode("Leaf Six"));
            root.add(nodeA);
            root.add(nodeB);
            final FilteredTreeModel model = new FilteredTreeModel(new DefaultTreeModel(root));
            final JTree tree = new JTree(model);
            f.add(new JScrollPane(tree), BorderLayout.CENTER);
            JButton b = new JButton("Toggle Leaf Display");
            b.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    boolean visible = model.isShowingLeaves();
                    model.setShowingLeaves(!visible);
                    tree.repaint();
            f.add(b, BorderLayout.SOUTH);
            f.setSize(400,300);
            f.setVisible(true);
        public static void main(String[] args) {
            new HiddenLeaves();
        private static class FilteredTreeModel implements TreeModel {
            private boolean showingLeaves = true;
            private DefaultTreeModel delegate;
            public FilteredTreeModel(DefaultTreeModel delegate) {
                this.delegate = delegate;
            public void setShowingLeaves(boolean show) {
                this.showingLeaves = show;
                delegate.reload();
            public boolean isShowingLeaves() {
                return showingLeaves;
            public Object getChild(Object parent, int index) {
                Object child = delegate.getChild(parent, index);
                if (!isShowingLeaves() && delegate.isLeaf(child)) {
                    child = null;
                return child;
            public int getChildCount(Object parent) {
                int count = delegate.getChildCount(parent);
                if (!showingLeaves) {
                    int newCount = count;
                    for (int i = 0; i < count; i++) {
                        if (delegate.isLeaf(delegate.getChild(parent, i))) {
                            newCount--;
                    count = newCount;
                return count;
            public int getIndexOfChild(Object parent, Object child) {
                int index = delegate.getIndexOfChild(parent, child);
                if (!showingLeaves) {
                    if (delegate.isLeaf(child)) {
                        index = -1;
                return index;
            public Object getRoot() {
                return delegate.getRoot();
            public boolean isLeaf(Object node) {
                return delegate.isLeaf(node);
            public void valueForPathChanged(TreePath path, Object newValue) {
                delegate.valueForPathChanged(path, newValue);
            public void addTreeModelListener(TreeModelListener l) {
                delegate.addTreeModelListener(l);
            public void removeTreeModelListener(TreeModelListener l) {
                delegate.removeTreeModelListener(l);
    }

  • JList and JTree

    Hello,
    I have a list of servers in a JList( is a seperate class) and when i am selecting a server name from the JList i am calling this value in my main class and I am trying to use this selected value from the Jlist to create a new JTree node but the value is not being displayed as a node.
    Any body having ideas as to why?
    Reg,
    suri

    Hello,
    Thanks for ur replies. I have tried the following way but still no results the node is not appearing in the JTree.
    Here logon(this is a listBox class and contains a JList with a list of server names)
    and root1 is the parent .
    DefaultMutableTreeNode new1 = new DefaultMutableTreeNode(logon.getValue(), true);
         int childCnt = root1.getChildCount();
         treeModel.insertNodeInto(new1, root1, childCnt);
    treeModel.reload(new1);
    treeModel.nodeStructureChanged(new1);
    JTree1.revalidate();
    JPanel1.revalidate();
    Any body any ideas .
    Thanks,
    reg,
    suri

  • JEditorPane and JTree

    Hi,
    I have a tree that lists all objects and I want to do some kind of search feature. Results would be displayed in JEditorPane but I don't know anything about that. In JTree there is TreeSelectionListener (method valueChanged) and that has the functionality I need to have on JEditorPane but I don't know if this is possible?
    Any advices please?

    Hi,
    I have a tree that lists all objects and I want to do some kind of search feature. Results would be displayed in JEditorPane but I don't know anything about that. In JTree there is TreeSelectionListener (method valueChanged) and that has the functionality I need to have on JEditorPane but I don't know if this is possible?
    Any advices please?

  • Database and JTree

    I have table in access entitled employees and wish to generate a JTree to show the organizational heirarchy of the company. I feel like I've followed the steps properly but the Jtrees either don't work or they work with the wrong data.
    "Perform a query to obtain the name of the employee. If you are at the root node (level 0), just change the value of the current node to the name you got from the query, otherwise, create a child node and set its value to be that name. Perform another query to get the employee IDs of all the employees whose manager is the current employee. Loop through this result set, recursively calling the method for each of the employees in the resultset from step (4)."[]
        public static void generateTree(DefaultMutableTreeNode node, int id, int level){
            DbSource dbs = new DbSource("EmpDb");
            if (dbs.isConnected()){
             boolean success = dbs.processQuery("select firstname, lastname from employees", false);
             if(success){
                 while(dbs.nextRecord()){
                  DefaultMutableTreeNode newNode;
                    if (level==0){
                        node.setUserObject(dbs.getField(1)+ " " + dbs.getField(2));
                        newNode=node;
                    else{
                        newNode = new DefaultMutableTreeNode(dbs.getField(1) + " " + dbs.getField(2));
                        node.add(newNode);               
                 boolean success2 = dbs.processQuery("select employeeid from employees where " + id+ " = manager", false);
                 if (success2){
                 while (dbs.nextRecord()){
                      generateTree(newNode, id, level+1);                      
        }Any quick hints are appreciated.

    Well, you didn't say what was wrong with the result of this. But that doesn't matter because I can see a lot of things wrong with the code.
    First you don't have anything that gets the level-zero node. (The president of the company or whatever that is.) You should do this outside the recursively-called method and create a node that contains that person's name. Then call the method, passing it that node.
    Second, in your posted code you have something that reads the entire file at every level. What's that for?
    Third, the last four lines of that method look like the actual code you need: get the employees who report to the manager in the current node. However you need something that creates a new node for each of those employees and adds it to the manager node.
    Fourth, you don't seem to use that "level" parameter anywhere. I don't think you have any need for it.
    Fifth, and I don't know if this is a problem, you will need to be able to process several DbSource objects simultaneously. Possibly you can, but it's possible to code that sort of thing so that you can't.

  • Having trouble with JCheckBox and JTree

    I am trying to render the JTree to display JCheckBox's instead of just ordinary JLabels.
    It's fine, compiles, and when you view it it looks normal, until you try to check one.
    You can't check it at all.
    What am i doing wrong with this?
    Thanks

    OK, here it is...
    public class EmotiTreeCellRenderer extends DefaultTreeCellRenderer {
         protected JCheckBox label;
         public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
              if ( value instanceof DefaultMutableTreeNode ) {
                   label = new JCheckBox();
                   label.setOpaque( false );
                   if ( selected && hasFocus ) {
                        label.setForeground( Color.blue );
                   DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
                   Object userObject = node.getUserObject();
                   if ( userObject instanceof Emoticon ) {
                        Emoticon emoticon = (Emoticon)userObject;
                        String icon = emoticon.getIconKeys();
                        try {
                             label.setText( "<html><body><img src=\"" + new File( emoticon.getRealPathToEmoticon() ).toURL().toString() + "\" alt=\"" + parseAlt( icon ) + "\"> " + parseAlt( icon ) + "</body></html>" );
                        } catch ( MalformedURLException mfe ) {
                             label.setText( "<html><body>" + parseAlt( icon ) + "</body></html>" );
                        return label;
                   } else if ( userObject instanceof EmotiPack ) {
                        EmotiPack pack = (EmotiPack)userObject;
                        label.setText( pack.getName() );
                        return label;
              return super.getTreeCellRendererComponent( tree, value, selected, expanded, leaf, row, hasFocus );
         protected String parseAlt(String html) {
              return html.replace( "<", "<" ).replace( ">", ">" ).replace( "\"", "&#34;" );
    }

  • Xml to JTree, and JTree node to html file.

    I have been trying to figure out a way to do this and I think I have a solution, but I am not sure how to structure the application and methods.
    working with BorderLayout Panel p, JSplitPane split, JTree tree, and JEditorPane rpane
    1st. My JSplitpane is divided with the tree, and rpane. The tree is on the left, and the rpane is on the right. both of these are then added to the Panel p
    2. I will create a method that will read through a modules.xml file, and create a JTree - tree. When you click on the node element it's information is displayed in the right pane - rpane.
    The Problem. I think it would take to long to create the html file on the fly each when I click on each individual node.
    So my idea is to create the html files from many xml files when I run the program. I can then just load the html file when I click on each individual node.
    This means alot of heavy processing in the front end, and everything will be static, but it will be faster when the user is in the program.
    Problem. How do I associate each node element with the correct html file?
    The Tree elements are always the same, but I can have 1 or many modules.
    Here is an example:
    <device>  // - root
       <module1>
          <Status>
             <Network></Network>
             <Device></Device>
             <Chassis></Chassis>
             <Resources></Resources>
          </Status>
          <ProjMngt></ProjMngt>
          <ProjEdit></ProjEdit>
          <Admin>
             <admNetwork></admNetwork>
             <admUsers></admUsers>
          </Admin>
          <Logging></Logging>
       </Module1>
       ...  Now I can have 1 or many Modules depending on what the xml file  has in it.
       <Module*n>
    </device>Other problems. Some of the information I want to store as a sortable Table, but I cannot seem to get any of the sort methods to work. They work if I just open a browser, and run the html file, but if I stick the html file into the JEditorPane it does not work? - any suggestions?
    Also, can I pass a JTabbebPane to the JEditorPane, or can I create a tabbed pane in html that will do the same thing.
    I am working with a very small device. It does not have a web application container like Tomcat on it. Just Apache, and Java. That is why I am using Swing.

    Using 'productAttribute/text()' gets you all three productAttribute nodes and then grabs all the text under that node. It simply concatenates together all the text under the desired node, hence the results you are seeing. If you want to get the text for each child node separately, then you need to do something like (assumes 10.2.x.x or greater)
    WITH your_table AS (SELECT
    '<root><productAttribute>
    <name>Baiying_attr_03</name>
    <required>false</required>
    </productAttribute>
    <productAttribute>
    <name>Baiying_attr_04</name>
    <required>false</required>
    </productAttribute>
    <productAttribute>
    <name>Baiying_attr_05</name>
    <required>false</required>
    </productAttribute></root>' xmldata
    FROM DUAL)
    -- Above simulates your DB table as I don't have it
    -- You only care about the following
    SELECT xt.*
      FROM your_table yt,
           XMLTable('/root/productAttribute'
                    PASSING XMLTYPE(yt.xmldata)
                    COLUMNS
                    prd_nm   VARCHAR2(30)  PATH 'name',
                    prod_rqd VARCHAR2(5)   PATH 'required') xt;Note: I added a <root> node as you had just provided a XML fragment. You will need to adjust accordingly.
    The above produces
    PRD_NM                         PROD_RQD
    Baiying_attr_03                false
    Baiying_attr_04                false
    Baiying_attr_05                false

  • ZipFile and french accent

    Hi,
    I have a problem with using the "java.util.ZipFile" library.
    Imagine that I have a zip file containing text files with names including french accents.
    The code to open and extract the files is simple :
    - I get each "ZipEntry";
    - get an InputStream;
    - convert to a bufferedInputStream;
    - use the read method;
    - save the data.
    But when the read method is executed the "java.io.IOException: Stream closed" message is displayed.
    If my zip file don't have file with name containing french accent, the code run without problem.
    If someone know how to resolve the problem...
    NB : I can't avoid the use of french accent.
    THANKS
    MY CODE :
    try
    String absoluteZipFileName = "C:\\temp\\fichier.zip";
    String destDir = "C:\\temp\\";
    zipfileName = new ZipFile(absoluteZipFileName);
    for (Enumeration iter = zipfileName.entries(); iter.hasMoreElements();)
    FileOutputStream FOS = null;
    BufferedOutputStream BOS = null;
    BufferedInputStream BIS = null;
    try
    int max = 2048;
    ZipEntry zipEntryTest = (ZipEntry) iter.nextElement();
    String fileName = zipEntryTest.getName();
    BIS = new BufferedInputStream(zipfileName.getInputStream(zipEntryTest));
    FOS = new FileOutputStream(destDir + fileName);
    BOS = new BufferedOutputStream(FOS, max);
    int nbr = 0;
    byte data[] = new byte[max];
    while ((nbr = BIS.read(data, 0, max)) != -1)
    BOS.write(data);
    catch (Exception a)
    System.out.println(a.toString());               
    finally
    BOS.close();
    FOS.close();
    catch (Exception e)
    System.out.println(e.toString());
    finally
    try {zipfileName.close();} catch (Exception e) {}
    THE ERRORS :
    java.io.IOException: Stream closed
    java.io.IOException: Stream closed

    Why the java zip classes cannot work with zip files
    created by other utilities (e.g. WinZip or Linux's zip
    program) when they contain accented characters is a
    question that I cannot answer, but it certainly looks
    like a bug within the Java classes. It's not exactly a bug, I don't know what you would call it. When you look at the zip file specification ( http://www.pkware.com/products/enterprise/white_papers/appnote.html for example) you'll notice that the file name needs to be stored in bytes, but there is nothing to indicate which bytes. In particular it doesn't specify what encoding it assumes the file name is in.
    This isn't surprising given that the format dates back to a time when only ASCII characters could occur in file names.
    I suspect that if you used Java to create a zip file containing the file "sacr&eacute;bleu.txt", you would be able to extract that file using Java also. Most likely WinZip and the Java API code use different, incompatible, ways of encoding that file name. Using a hex editor to examine what they produce should display the difference.
    The reason I said it wasn't exactly a bug is that the specification is incomplete. But you could argue that what PKZip actually does is the de facto standard, and presumably WinZip does the same thing that PKZip does.

  • DnD: custom TransferHandler and JTree

    Hi!
    I have seen a similar post like this one before, but there was no real answer.
    When I use the standard TransferHandler for DnD in a JTree, things work the way they should. However, when I use my own custom subclass of TransferHandler, no dragging behaviour is to be seen. Obviously, some crucial piece of code is missing from my class, but what is it?
    public class TopicTransferHandler extends TransferHandler {
        private TM4J_FSControllerFactory factory;
        private Object objectInTree = null;
        public TopicTransferHandler(TM4J_FSControllerFactory factory) {
         super();
         this.factory = factory;
        protected Transferable createTransferable(JComponent c) {
         Transferable trans = null;
         // if we are dragging from a tree (should always be the case)...
         if (c instanceof FSTree) {
             // then we let the HTMController construct a transferable from
             // the currently selected object in the tree
             FSTree tree = (FSTree) c;
             HandleTopicMirrorController mc =
              factory.createMirrorController(true);
             trans = mc.getTransferable(objectInTree);
             System.out.println("createTransferable(): " + trans);
         return trans;
        public int getSourceActions(JComponent c) {
         return COPY_OR_MOVE;
    }I appreciate any help!
    Dunk

    Hello!!
    I was having the same problem, but using the source code of TransferHandler and the tutorial I finally got it!! Eba!!
    /** Check http://java.sun.com/docs/books/tutorial/uiswing/misc/dnd.html
    * @author Stenio L. Ferreira
    * Created on 20/08/2003
    * [email protected]
    import javax.swing.*;
    import java.awt.datatransfer.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import javax.swing.tree.*;
    import com.exactus.vbcomponentes.*;
    public class JTreeTransferHandler extends TransferHandler {
         protected Transferable createTransferable(JComponent c) {
              return new StringSelection(exportString(c));
         public int getSourceActions(JComponent c) {
              return COPY_OR_MOVE;
         protected String exportString(JComponent c) {
              DefaultMutableTreeNode treeNode =
                   (DefaultMutableTreeNode) ((JTree) c)
                        .getSelectionPath()
                        .getLastPathComponent();
              Node meuNode = (Node) treeNode.getUserObject();
              Integer result = new Integer(meuNode.getMeuId());
              return (result.toString());
         private static class DragHandler implements MouseMotionListener {
              MouseEvent firstMouseEvent;
              public void mousePressed(MouseEvent e) {
                   firstMouseEvent = e;
                   e.consume();
              public void mouseDragged(MouseEvent e) {
                   if (firstMouseEvent != null) {
                        e.consume();
                        int dx = Math.abs(e.getX() - firstMouseEvent.getX());
                        int dy = Math.abs(e.getY() - firstMouseEvent.getY());
                        //Arbitrarily define a 5-pixel shift as the
                        //official beginning of a drag.
                        if (dx > 5 || dy > 5) {
                             JComponent c = ((JTree) e.getSource());
                             JTreeTransferHandler th =
                                  (JTreeTransferHandler) c.getTransferHandler();
                             Transferable t = th.createTransferable(c);
                             th.exportDone(c, null, NONE);
                             firstMouseEvent = null;
              public void mouseReleased(MouseEvent e) {
                   firstMouseEvent = null;
              public void mouseMoved(MouseEvent e) {
    }Hope this helps!

Maybe you are looking for

  • REG:- SELECT STATEMENT IN IF CONDITION.

    HI FRIENDS, CAN V USE SELECT STATEMENT IN IF CONDITION LIKE.... IF (SELECT COUNT(EMPID) FROM EMPLOPYEE) > 1 THEN UPDATE STATEMENT; END IF; PLEASE HELP. --RAJNISH                                                                                         

  • ActionListener on commandLink sometimes does not bind

    I'm doing the following:                          <h:commandLink action="loandetail" actionListener="#{loandetailbean.removeDetailAction}" rendered="#{loandetailbean.needPrevNext}">      <h:commandButton type="button" value="<<" actionListener="#{loa

  • Wrong hours in iNotes Calendar (Firefox 4.0.1 FR on Windows 7)

    I am gradually moving from XP SP3 to Windows 7 Pro EN with SP1. On XP, besides the "XUL" problem, iNotes is working fine. But on Windows 7 SP1, the iNotes calendar times are wrong, my first meetings starting at midnight (!) instead of, usually, 9 or

  • TV out doesn't display avi, mpg, etc

    I'm trying to use a Ge-Force FX-5200 128 meg to display videos on a tv using TV out. Everything gets displayed on the TV monitor but actual video files don't show up (for example, I can see the media player window but its just black inside). Of cours

  • I can't uninstall or remove FExplorer aplication o...

    I can't uninstall or remove FExplorer aplication on my nokia E63. does it need a tool or something to remove it? please reply.