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

Similar Messages

  • 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

  • Jsplitpane and jpanel

    Hi
    I am new to Java Swing and therefore ADF Swing.   Therefore, this may sound like a basic question.
    I have created a swing empty form.  Is it possible to have a parent-child relationship between jsplitpane and containers?
    For e.g.  the design is - the left site on jsplitpane will house a jtree component, and right side of jsplitpane will have a jtabbedPane container.
    how do I achieve above.. please advise.
    Thanks,
    Darsh

    For me is not very clear your question. Do you want such as a jpanel in the top the your layout? Like a header?
    The location of each component in your page layout will depend on the type of Layout Managers you will use.
    What are you using?

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

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

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

  • JTextArea as ListCellRenderer in JPanel with JSplitPane and text wrapping

    Hi.
    I have problem with JTextArea text wrapping. The JTextArea is used as ListCellRenderer in JList and it has set:
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);I can dynamically add new Notes, modify and remove notes on JList. The capacity of the Text is various so the size of cells is various.
    The JList is in JScrollPane configured like this:
    JList notesList = new JList();
    JScrollPane scrollPane = new JScrollPane(
                        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
    scrollPane.setViewportView(notesList);This scrollPane is put on the left component in the JSplitPane.
    When I put one note with any capacity I want, word wrapping works great even if I move the splitter. The size of cells in JList changes as I want. When JList has more width the cells have less height, when JList has less width the cells height grows because of text wrapping.
    Problem
    Sometimes and I don't know when and why the cells size is fixed.
    I put new note to the list, JList lays the cell, calculate the size and disply it. It is good but when I move splitter the size of the cell is the same. It seems that during moving the splitter the JTextArea doesn't calculate their size.
    I would like in every cell in JList to see whole text wrapped. When I make more width by slider I would like to see whole text with less number of rows. When I make less width with the slider I want to see whole text wrapped and more higher cells.
    Can someone help me where to looking for ideas.

    Hi.
    I have problem with JTextArea text wrapping. The JTextArea is used as ListCellRenderer in JList and it has set:
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);I can dynamically add new Notes, modify and remove notes on JList. The capacity of the Text is various so the size of cells is various.
    The JList is in JScrollPane configured like this:
    JList notesList = new JList();
    JScrollPane scrollPane = new JScrollPane(
                        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
    scrollPane.setViewportView(notesList);This scrollPane is put on the left component in the JSplitPane.
    When I put one note with any capacity I want, word wrapping works great even if I move the splitter. The size of cells in JList changes as I want. When JList has more width the cells have less height, when JList has less width the cells height grows because of text wrapping.
    Problem
    Sometimes and I don't know when and why the cells size is fixed.
    I put new note to the list, JList lays the cell, calculate the size and disply it. It is good but when I move splitter the size of the cell is the same. It seems that during moving the splitter the JTextArea doesn't calculate their size.
    I would like in every cell in JList to see whole text wrapped. When I make more width by slider I would like to see whole text with less number of rows. When I make less width with the slider I want to see whole text wrapped and more higher cells.
    Can someone help me where to looking for ideas.

  • 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

  • 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

  • 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

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

  • JSplitPane and divider size.

    I have a JSplitPane with a panel on the left, a panel on the right and a panel in the middle as the divider. When the user clicks on the divider and drags and drops it to a new location, this divider appears as a black area the size of the middle divider panel. This is using one touch layout....my middle divider panel is about 120 pixels wide and when the user is dragging and dropping this divider, I want it to appear as a thin black line (about 4 pixels wide).
    I have not been able to reset the divider size on a mouse pressed event in my divider panel...I thought this might do it, but it does not. any ideas?

    http://www.physci.org/codes/sscce.jsp

Maybe you are looking for

  • Crystal Report RAS and eclipse jar licensing

    Hello, I am currently evaluating crystal reports 2013 for report designing for one of our customers. I have created a poc with xml from file system as a datasource and then setting our web service xml response as datasource at runtime to populate the

  • Two iPods - One computer

    How do I get two different iTunes accounts with only one computer. There is my mentally challenged son's iPod and then I have one too. Obviously I don't want the same songs on my iPod that he has on his. How do I open two different iTunes accounts or

  • Error Handling and Freeing-up Memory

    I'm trying to write my java programs as responsibly as possible. When an exception is caught and sent to my catch block, in order to properly free up memory do I need to set all objects (created prior to the error occurance in the try block) to null

  • Validation for initial budget upload in FMBB

    Hi, I have one requirement where client want a validation or rule, when they upload the budget for one group of commitment item and fund center then user should not be allowed again using the same document type initial budget upload to upload the bud

  • How to hide Total value in RFX response webdynpro component

    HI experts,        We are working on SRM 7.0 and there is a requirement to hide the Total Value that appers on RFX Response Header for a particular Role.The webdynpro component is FPM_IDR_COMPONENT and View is IDR_VIEW..I have searched the SDN and fo