JTree Color

Hi, I'm new to JTree. I've a problem with JTree setBackground. It seems to changed the background color without changing the node's label's background color and I've used setForeground but it seems like no effect. Can anyone help? Thanks

Hi, I'm new to JTree. I've a problem with JTree
setBackground. It seems to changed the background
color without changing the node's label's background
color and I've used setForeground but it seems like no
effect. Can anyone help? ThanksThe problem you're seeing is because each node is rendered with a component different from the JTree background as a whole. you need to set the background for the rendering component as well as the background.
The easiest way to do this is to use the DefaultTreeCellRenderer in the javax.swing.tree package.
http://java.sun.com/j2se/1.3/docs/api/javax/swing/tree/DefaultTreeCellRenderer.html
sample code follows.
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellRenderer;
public class TestTree extends JFrame{
   public TestTree(){
      Container cp = getContentPane();
      JTree tree =  new JTree();
      DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
      renderer.setBackgroundNonSelectionColor(Color.blue);
      renderer.setBackgroundSelectionColor(Color.yellow);
      tree.setCellRenderer(renderer);
      tree.setBackground(Color.blue);
      cp.add(tree);
   public static void main(String args[]){
      TestTree tt = new TestTree();
      tt.pack();
      tt.show();
      tt.setDefaultCloseOperation(EXIT_ON_CLOSE);
}

Similar Messages

  • JTree - Color setting of linestyle

    Between the root and the node elements there are lines to show the connection between the element/levels. How can I change the color of these lines and/or how can I hide these lines?

    Example:
    private JTree tree;
    tree.putClientProperty("JTree.lineStyle", "None");

  • Sort JTree alphabetical

    Hello everyone! I am trying to sort a JTree alphabetical. For the moment i made only the roots (partitions) to sort. I use the JTree to view all the partitions and view all the files. I override the interface TreeNode for my needs...and i made a class for cell renderer...
    public class FileTreeNode implements TreeNode
         public File file;
         private File[] children;     
         private  TreeNode parent;     
         public boolean isFileSystemRoot;     
         public FileTreeNode(File file, boolean isFileSystemRoot, TreeNode parent)
              this.file = file;
              this.isFileSystemRoot = isFileSystemRoot;
              this.parent = parent;
              this.children = this.file.listFiles();
              if (this.children == null)
                   this.children = new File[0];
         public FileTreeNode(File[] children)
              this.file = null;
              this.parent = null;
              this.children = children;               
         @Override
         public Enumeration<?> children()
              final int elementCount = this.children.length;
              return new Enumeration<File>()
                   int count = 0;
                   public boolean hasMoreElements()
                        return this.count < elementCount;
                   public File nextElement()
                        if (this.count < elementCount)
                             return FileTreeNode.this.children[this.count++];
                        throw new NoSuchElementException("Vector Enumeration");
         @Override
         public boolean getAllowsChildren()
              return true;
         @Override
         public TreeNode getChildAt(int childIndex)
              return new FileTreeNode(this.children[childIndex],this.parent == null, this);
         @Override
         public int getChildCount()
              return this.children.length;
         @Override
         public int getIndex(TreeNode node)
              FileTreeNode ftn = (FileTreeNode) node;
              for (int i = 0; i < this.children.length; i++)
                   if (ftn.file.equals(this.children))
                        return i;                    
              return -1;
         @Override
         public TreeNode getParent()
              return this.parent;
         @Override
         public boolean isLeaf()
              return (this.getChildCount() == 0);
         public void sortRoots()
              List<File> list = Arrays.asList(this.children);
              Collections.sort(list);
              System.out.println("Partitions: " + list);
    and the other class....public class FileTreeCellRenderer extends DefaultTreeCellRenderer
         private static final long serialVersionUID = 1L;
         protected static FileSystemView fsv = FileSystemView.getFileSystemView();
         private Map<String, Icon> iconCache = new HashMap<String, Icon>();          
         private Map<File, String> rootNameCache = new HashMap<File, String>();     
         public Component getTreeCellRendererComponent(JTree tree, Object value,
                   boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus)
              FileTreeNode ftn = (FileTreeNode) value;
              File file = ftn.file;
              String filename = "";
              if (file != null)
                   if (ftn.isFileSystemRoot)
                        filename = this.rootNameCache.get(file);
                        if (filename == null)
                             filename = fsv.getSystemDisplayName(file);                         
                             this.rootNameCache.put(file, filename);
                   else
                        filename = file.getName();
              JLabel result = (JLabel) super.getTreeCellRendererComponent(tree,
                        filename, selected, expanded, leaf, row, hasFocus);
              if (file != null)
                   Icon icon = this.iconCache.get(filename);
                   if (icon == null)
                        icon = fsv.getSystemIcon(file);
                        this.iconCache.put(filename, icon);
                   result.setIcon(icon);
              return result;
    and i run the application...File[] roots = File.listRoots();
    FileTreeNode rootTreeNode = new FileTreeNode(roots);
    tree = new JTree(rootTreeNode);
    tree.setCellRenderer(new FileTreeCellRenderer());
    can anyone please help me to sort alphabetical all the files from all the nodes...any help will be appreciated.
    Thanks.
    Calin                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    might be easier if you were to add a small pictorial
    e.g. if you have a no-arg constructor JTree, you get this
    JTree
          colors
                   blue
                   violet
                   red
                   yellow
          sports
                   basketball
                   soccer
                   football
                   hockey
          food
                   hot dogs
                   pizza
                   ravioli
                   bananasnow put it how you would like it sorted

  • Where in the world is this coming from?

    I've recently been contracted to build an application for my employer. Great. The project is really straight forward and its going along nicely ... all except for this simple bit here.
    I decided to use a new "big & bad" IDE (Netbeans 5.5) seeing as how this was pretty GUI intensive. I don't like to have to sit down and calculate all of those dimensions and placements by hand. So ... am using the IDE.
    Pasted below is the initComponents() method of my program where my JTree (jTree1) is instantiated. It has an empty constructor - and nothing has been added to it ... so I'm curious as to how this is happening:
    The problem:
    I've reviewed the code over and over again. I can't find anywhere where a default dataset is being assigned to the JTree. Anywhere. However, when I go to view my form - I have the following information in the tree:
    JTree
    |
    Colors
    |- blue
    |- violet
    |- red
    |- yellow
    |
    Sports
    |- basketball
    |- soccer
    |- football
    |- hockey
    |
    Food
    |- hotdogs
    |- pizza
    |- ravioli
    |- bananas
    Where in the name of Satan's assshole is this coming from?
        private void initComponents() {
            btnSend = new javax.swing.JButton();
            btnClose = new javax.swing.JButton();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTree1 = new javax.swing.JTree();
            jLabel1 = new javax.swing.JLabel();
            btnDoAssignment = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Homework Utilities");
            btnSend.setText("Send Homework");
            btnClose.setText("Close");
            btnClose.setMaximumSize(new java.awt.Dimension(109, 23));
            btnClose.setMinimumSize(new java.awt.Dimension(109, 23));
            btnClose.setPreferredSize(new java.awt.Dimension(109, 23));
            btnClose.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btnCloseActionPerformed(evt);
            jTree1.setEditable(true);
            jScrollPane1.setViewportView(jTree1);
            jLabel1.setText("Select Homework Assignment:");
            btnDoAssignment.setText("Do Assignment");
            btnDoAssignment.setMaximumSize(new java.awt.Dimension(109, 23));
            btnDoAssignment.setMinimumSize(new java.awt.Dimension(109, 23));
            btnDoAssignment.setPreferredSize(new java.awt.Dimension(109, 23));
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(btnClose, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(btnSend)
                        .add(btnDoAssignment, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(22, 22, 22)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE)
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE))
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jLabel1)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                            .add(btnDoAssignment, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                            .add(btnSend)
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                            .add(btnClose, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap())
            pack();
        }Nowhere else in the rest of the entire application is jTree1 even referenced. So, how is this? How is that data in my tree? Best question: how in the funk do I get it out??

    Myeh - I'm not really in any rush. I work from home as a private contractor. I tell you - it is so much more ... relaxed? ... than when I was working for my previous employer. My current employer wants the product finished by June. Thats when they have a big push of students coming in and want the new software ready for them. So, I've got a while - and it definitely wont take me that long to complete. I just figured that there must be something to the fuss about IDEs and how they simplify things. And, tonight, I found that that is a load of horseshit.
    (Just so you know - there is a downside to working for yourself... you get weird requests from people like the following ...)
    I had a guy once ask me to write an application for his son who is obsessed with the television show Alias. He said he wanted a program that did exactly what this Alias program did on the show in a particular episode. When asked if I was familiar with it, I said no. So what does this goofball do? He goes and buys the show on DVD and brings it to me. We watch it - he takes me to the point in the show and says "That! Right there! That's what he wants!!"
    Astonished (and somewhat dumbfounded) I ask him, "You're aware of the fact that I am not going to be capable of writing an application that remotely logs into a secret NSA super-computer via satellite ...... right?" He then proceeded to tell me to make it look like it does. Just make up all sorts of stuff - just as long as it looks the same.
    The worst part .... that wasn't the only request of the type that I've received. (Granted, the others were by kids - usually 14 or 15 that thought that I'd do it for 10 or so bucks.) Because I obviously have time to waste on such things ...

  • Applet doubt

    I m taking this code from else where .but in o/p after login if u see on right side i get jtree-color-sports-food--like this menu.If i want my own menu how can i do this ,if any one have idea pls post me to [email protected] or post here
    java code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class LoginApplet2 extends JApplet {
    public void init() {
    add( new MainGui(), BorderLayout.CENTER );
    validate();
    public static void main(String[] args) {
    Runnable r = new Runnable() {
    public void run() {
    JFrame f = new JFrame("Log-In app.");
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    f.add( new MainGui(), BorderLayout.CENTER );
    f.pack();
    f.setLocationByPlatform(true);
    f.setVisible(true);
    SwingUtilities.invokeLater(r);
    class MainGui extends JPanel {
    JButton logIn;
    JLabel status;
    JPasswordField passwordField;
    JTextField username;
    JLabel logInLabel;
    JPanel mainPanel;
    JPanel usernamePasswordPanel;
    CardLayout cards;
    MainGui() {
    super.setLayout(new BorderLayout(3,3));
    status = new JLabel("Log-In to proceed");
    add(status, BorderLayout.NORTH);
    mainPanel = new JPanel();
    cards = new CardLayout();
    mainPanel.setLayout(cards);
    usernamePasswordPanel = new JPanel(new GridLayout(2,2,3,3));
    usernamePasswordPanel.add( new JLabel("Username:") );
    username = new JTextField(10);
    usernamePasswordPanel.add( username );
    usernamePasswordPanel.setBorder(new EmptyBorder(25,25,25,25));
    usernamePasswordPanel.add( new JLabel("Password:") );
    passwordField = new JPasswordField(10);
    usernamePasswordPanel.add( passwordField );
    logInLabel = new JLabel("Log In to use the app.");
    mainPanel.add(logInLabel,"login");
    JPanel mainApp = new JPanel(new BorderLayout(3,3));
    mainApp.add(new JScrollPane(new JTree()), BorderLayout.WEST);
    mainApp.add(new JTextArea(4,20), BorderLayout.CENTER);
    mainPanel.add(mainApp, "app");
    logIn = new JButton("Log In");
    logIn.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae) {
    if (logIn.getText().equals("Log In")) {
    JOptionPane.showMessageDialog(
    logIn,
    usernamePasswordPanel,
    "Log-In (Pswd hint: any 4+ letters or digits)",
    JOptionPane.QUESTION_MESSAGE);
    checkPassWord();
    } else {
    logOut();
    add(logIn, BorderLayout.SOUTH);
    add(mainPanel, BorderLayout.CENTER);
    setBorder(new EmptyBorder(4,4,4,4));
    public void checkPassWord() {
    // change this for server based authentication
    if (passwordField.getPassword().length>3) {
    cards.show(mainPanel, "app");
    logIn.setText("Log Out");
    status.setText("Logged in as " + username.getText());
    } else {
    status.setText("Log In failed!");
    public void logOut() {
    cards.show(mainPanel, "login");
    logIn.setText("Log In");
    status.setText("Logged out");
    passwordField.setText("");
    related html::
    <html>
    <head></head>
    <body>
    <applet code="LoginApplet2.class" width=300 height=300>
    </applet>
    </body>
    </html>

    >
    I m taking this code from else where . ..>Where? If it is available on the net, it is better to give the URL.
    And whenever pasting code, code snippets, HTML/XML or input/output, please use the code tags. The code tags help preserve the indentation and formatting of the text. To use the code tags, select the text and click the CODE button on the Plain Text tab of the message posting form.(1)
    >
    .. but in o/p after login if u see on right side i get jtree-color-sports-food--like this menu.>Please spell words fully(2). For the sake of saving typing a couple of letters, it makes people seem like buffoons.
    >
    ...If i want my own menu how can i do this ,if any one have idea pls post me to [email protected] or post here >
    - (2) Those words are 'please' and 'you'.
    - The word I should always be upper case. Always.
    - Please add 2 spaces and a single upper case letter at the start of every sentence. This helps the reader, and you would not want to make it harder for people to help you, would you?
    - "If i want my own menu how can i do this" is a question, and should be 'marked' as a question with a question mark -> "If I want my own menu how can I do this?".
    - And since it came up - 'doubt' seems to be an Indian(/English) word for 'question'. These are international forums, so that subject should be 'applet question'
    - It is not a good idea to invite people on public forums to tutor you privately. It is generally felt that public forums are also to help people 'searching' for the answer later, and if a thread goes to email, that opportunity is lost.
    - Posting an email address to a public forum will attract a torrent of spam.
    But the 'short answer' to your question is..
    >
    java code:
    mainApp.add(new JScrollPane(new JTree()), BorderLayout.WEST);>..Use one of the [JTree constructors|http://java.sun.com/javase/6/docs/api/javax/swing/JTree.html#constructor_summary] *(<- link)* that accepts an argument. For further details, see [How to Use Trees|http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html] *(<- link)* in the Java Tutorial.
    (1) And here is how that snippet looks when inside code tags
        mainApp.add(new JScrollPane(new JTree()), BorderLayout.WEST);
    ...

  • How to give some color to a Node in a JTree

    Hi there,
    I have built a JTree that is now ALMOST ready to be the way I want... but ONE thing is missing : I want to be able to put some color on the leaves of my tree, well on the String objects that are just right to their icons. I searched almost all day! Why is it so hard to find some function to accomplish this task when this task is a common one.
    Well please if anyone knows how to do that in a simple way please write back.
    Mr. Big

    It's actually quite easy.
    What you have to do is write a custom tree cell renderer which extends DefaultTreeCellRenderer. In that class, your getTreeCellRenderer() method should do something like the following:
    public Component getTreeCellRendererComponent(
        JTree tree, Object value, boolean selected,
        boolean expanded, boolean leaf, int row, boolean hasFocus )
            Component treeCellRenderer =
                  super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
            if (selected) {
                setForeground(Color.WHITE);
                setBackground(BACKGROUND_SELECTION_COLOR);
            } else {
                treeCellRenderer.setForeground(Color.RED);
            return treeCellRenderer;
    Then you'll need to make sure that you call myTree.setCellRenderer(new CustomTreeCellRenderer());
    cheers,
    Greg

  • How can I create an alt background color for items in a jlistbox or jtree

    What I'm looking to do is have a white background for say items 1,3,5, etc. and a light yellow background for items 2,4,6, etc. I was wondering how can I set an alternative background color on items in a JTree or a JList

    Use a cell renderer:
    import java.awt.*;
    import javax.swing.*;
    public class ListAlternating extends JFrame
         public ListAlternating()
              String[] items = {"one", "two", "three", "four", "five", "six", "seven"};
              JList list = new JList( items );
              list.setVisibleRowCount(5);
              list.setCellRenderer( new MyCellRenderer() );
              JScrollPane scrollPane = new JScrollPane( list );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              ListAlternating frame = new ListAlternating();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );
         class MyCellRenderer extends DefaultListCellRenderer
              public Component getListCellRendererComponent(
                   JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
                   super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                   if (!isSelected)
                        setBackground(index % 2 == 0 ? list.getBackground() : Color.LIGHT_GRAY);
                   return this;
    }

  • JTree custom renderer setting selection background color problem

    Hi,
    I have a JTree with a custom icon renderer that displays an icon. The JTree is part of a TreeTable component. Iam having a problem setting the selection background uniformly for the entire row. There is no problem when there is no row selected in the JTable.
    My present code looks like this:
    Iam overriding paint in my renderer which extends DefaultCellRenderer.
           super.paint(g);
            Color bColor = null;
            if(!m_selected) {
                 if(currRow % 2 == 0) {
                      bColor = Color.WHITE;
                 } else {
                                                    bColor = backColor;
            } else {
                 bColor = table.getSelectionBackground();                  bColor = getRowSelectionColor();
         if(bColor != null) {
                           g.setColor(bColor);
             if(!m_selected) {
                   g.setXORMode(new Color(0xFF, 0xFF, 0xFF));
             } else {
                 g.setXORMode(new Color(0x00, 0x00, 0x00));
                  I have a color I arrive at using some algorithm that I want using method getRowSelectionColor(). The other cells in the row have this color. But the cell containing the tree node shows different color. Iam not able to arrive at the right combination of the color to set and the xor color so my tree node also looks like the other cells in the row.
    It is not a problem really as the table still looks good. Its just that the tree node looks like it has been highlighted and this might cause a problem when a table cell is highlighed later on in the application ( two cells in the row would be highlighted causing confusion).
    Any help would be appreciated.
    Regards,
    vidyut

    Hi Camickr,
    Thanks for the reply. Iam sorry I didn't include the sources the first time around. There were too many of them. I have created a small, self-contained, compilable program that demonstrates the problem and including it herewith. Still there's quite many files but they are all needed Iam afraid. The only one you will have to concern yourself fior this problem is the file IconRenderer.java. The treenode background and the other cells background are not in sync when table row is not selected in this example though. But they are in my real program. I just need them to be in sync i.e have the same background color when the row is selected.
    Your help would be very much appreciated.
    These are the files that are included below:
    1. AbstractTreeTableModel.java
    2. Bookmarks.java
    3. BookmarksModel.java
    4. DynamicTreeTableModel.java
    5. IconRenderer.java
    6. IndicatorRenderer.java
    7. JTreeTable.java
    8. TreeTableExample3.java (contains main)
    9. TreeTableModel.java
    10. TreeTableModelAdapter.java
    The copyright and javadocs information has been stripped for clarity.
    cheers,
    vidyut
    // AbstractTreeTableModel.java BEGIN
    import javax.swing.tree.*;
    import javax.swing.event.*;
    public abstract class AbstractTreeTableModel implements TreeTableModel {
        protected Object root;    
        protected EventListenerList listenerList = new EventListenerList();
        public AbstractTreeTableModel(Object root) {
            this.root = root;
        // Default implementations for methods in the TreeModel interface.
        public Object getRoot() {
            return root;
        public boolean isLeaf(Object node) {
            return getChildCount(node) == 0;
        public void valueForPathChanged(TreePath path, Object newValue) {}
        // This is not called in the JTree's default mode:
        // use a naive implementation.
        public int getIndexOfChild(Object parent, Object child) {
            for (int i = 0; i < getChildCount(parent); i++) {
             if (getChild(parent, i).equals(child)) {
                 return i;
         return -1;
        public void addTreeModelListener(TreeModelListener l) {
            listenerList.add(TreeModelListener.class, l);
        public void removeTreeModelListener(TreeModelListener l) {
            listenerList.remove(TreeModelListener.class, l);
        protected void fireTreeNodesChanged(Object source, Object[] path,
                                            int[] childIndices,
                                            Object[] children) {
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            TreeModelEvent e = null;
            // Process the listeners last to first, notifying
            // those that are interested in this event
            for (int i = listeners.length-2; i>=0; i-=2) {
                if (listeners==TreeModelListener.class) {
    // Lazily create the event:
    if (e == null)
    e = new TreeModelEvent(source, path,
    childIndices, children);
    ((TreeModelListener)listeners[i+1]).treeNodesChanged(e);
    protected void fireTreeNodesInserted(Object source, Object[] path,
    int[] childIndices,
    Object[] children) {
    // Guaranteed to return a non-null array
    Object[] listeners = listenerList.getListenerList();
    TreeModelEvent e = null;
    // Process the listeners last to first, notifying
    // those that are interested in this event
    for (int i = listeners.length-2; i>=0; i-=2) {
    if (listeners[i]==TreeModelListener.class) {
    // Lazily create the event:
    if (e == null)
    e = new TreeModelEvent(source, path,
    childIndices, children);
    ((TreeModelListener)listeners[i+1]).treeNodesInserted(e);
    protected void fireTreeNodesRemoved(Object source, Object[] path,
    int[] childIndices,
    Object[] children) {
    // Guaranteed to return a non-null array
    Object[] listeners = listenerList.getListenerList();
    TreeModelEvent e = null;
    // Process the listeners last to first, notifying
    // those that are interested in this event
    for (int i = listeners.length-2; i>=0; i-=2) {
    if (listeners[i]==TreeModelListener.class) {
    // Lazily create the event:
    if (e == null)
    e = new TreeModelEvent(source, path,
    childIndices, children);
    ((TreeModelListener)listeners[i+1]).treeNodesRemoved(e);
    protected void fireTreeStructureChanged(Object source, Object[] path,
    int[] childIndices,
    Object[] children) {
    // Guaranteed to return a non-null array
    Object[] listeners = listenerList.getListenerList();
    TreeModelEvent e = null;
    // Process the listeners last to first, notifying
    // those that are interested in this event
    for (int i = listeners.length-2; i>=0; i-=2) {
    if (listeners[i]==TreeModelListener.class) {
    // Lazily create the event:
    if (e == null)
    e = new TreeModelEvent(source, path,
    childIndices, children);
    ((TreeModelListener)listeners[i+1]).treeStructureChanged(e);
    // Default impelmentations for methods in the TreeTableModel interface.
    public Class getColumnClass(int column) { return Object.class; }
    public boolean isCellEditable(Object node, int column) {
    return getColumnClass(column) == TreeTableModel.class;
    public void setValueAt(Object aValue, Object node, int column) {}
    // Left to be implemented in the subclass:
    * public Object getChild(Object parent, int index)
    * public int getChildCount(Object parent)
    * public int getColumnCount()
    * public String getColumnName(Object node, int column)
    * public Object getValueAt(Object node, int column)
    // AbstractTreeTableModel.java END
    // Bookmarks.java BEGIN
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import javax.swing.text.html.parser.*;
    public class Bookmarks {
    /** The root node the bookmarks are added to. */
    private BookmarkDirectory root;
    * Creates a new Bookmarks object, with the entries coming from
    * <code>path</code>.
    public Bookmarks(String path) {
         root = new BookmarkDirectory("Bookmarks");
         if (path != null) {
         parse(path);
    * Returns the root of the bookmarks.
    public BookmarkDirectory getRoot() {
         return root;
    protected void parse(String path) {
         try {
         BufferedReader reader = new BufferedReader(new FileReader
                                       (path));
         new ParserDelegator().parse(reader, new CallbackHandler(), true);
         catch (IOException ioe) {
         System.out.println("IOE: " + ioe);
         JOptionPane.showMessageDialog(null, "Load Bookmarks",
                             "Unable to load bookmarks",
                             JOptionPane.ERROR_MESSAGE);
    private static final short NO_ENTRY = 0;
    private static final short BOOKMARK_ENTRY = 2;
    private static final short DIRECTORY_ENTRY = 3;
    private class CallbackHandler extends HTMLEditorKit.ParserCallback {
         /** Parent node that new entries are added to. */
         private BookmarkDirectory parent;
         /** The most recently parsed tag. */
         private HTML.Tag tag;
         /** The last tag encountered. */
         private HTML.Tag lastTag;
         * The state, will be one of NO_ENTRY, DIRECTORY_ENTRY,
    * or BOOKMARK_ENTRY.
         private short state;
         * Date for the next BookmarkDirectory node.
         private Date parentDate;
         * The values from the attributes are placed in here. When the
         * text is encountered this is added to the node hierarchy and a
    * new instance is created.
         private BookmarkEntry lastBookmark;
         * Creates the CallbackHandler.
         public CallbackHandler() {
         parent = root;
         lastBookmark = new BookmarkEntry();
         // HTMLEditorKit.ParserCallback methods
         * Invoked when text in the html document is encountered. Based on
         * the current state, this will either: do nothing
    * (state == NO_ENTRY),
         * create a new BookmarkEntry (state == BOOKMARK_ENTRY) or
    * create a new
         * BookmarkDirectory (state == DIRECTORY_ENTRY). If state is
    * != NO_ENTRY, it is reset to NO_ENTRY after this is
    * invoked.
    public void handleText(char[] data, int pos) {
         switch (state) {
         case NO_ENTRY:
              break;
         case BOOKMARK_ENTRY:
              // URL.
              lastBookmark.setName(new String(data));
    parent.add(lastBookmark);
    lastBookmark = new BookmarkEntry();
              break;
         case DIRECTORY_ENTRY:
              // directory.
              BookmarkDirectory newParent = new
                   BookmarkDirectory(new String(data));
              newParent.setCreated(parentDate);
              parent.add(newParent);
              parent = newParent;
              break;
         default:
              break;
    state = NO_ENTRY;
         * Invoked when a start tag is encountered. Based on the tag
         * this may update the BookmarkEntry and state, or update the
         * parentDate.
         public void handleStartTag(HTML.Tag t, MutableAttributeSet a,
                        int pos) {
         lastTag = tag;
         tag = t;
         if (t == HTML.Tag.A && lastTag == HTML.Tag.DT) {
    long lDate;
              // URL
              URL url;
              try {
              url = new URL((String)a.getAttribute(HTML.Attribute.HREF));
              } catch (MalformedURLException murle) {
              url = null;
              lastBookmark.setLocation(url);
              // created
              Date date;
              try {
    lDate = Long.parseLong((String)a.getAttribute("add_date"));
    if (lDate != 0l) {
    date = new Date(1000l * lDate);
    else {
    date = null;
              } catch (Exception ex) {
              date = null;
              lastBookmark.setCreated(date);
              // last visited
              try {
    lDate = Long.parseLong((String)a.
    getAttribute("last_visit"));
    if (lDate != 0l) {
    date = new Date(1000l * lDate);
    else {
    date = null;
              } catch (Exception ex) {
              date = null;
              lastBookmark.setLastVisited(date);
              state = BOOKMARK_ENTRY;
         else if (t == HTML.Tag.H3 && lastTag == HTML.Tag.DT) {
              // new node.
              try {
              parentDate = new Date(1000l * Long.parseLong((String)a.
                                  getAttribute("add_date")));
              } catch (Exception ex) {
              parentDate = null;
              state = DIRECTORY_ENTRY;
         * Invoked when the end of a tag is encountered. If the tag is
         * a DL, this will set the node that parents are added to the current
         * nodes parent.
         public void handleEndTag(HTML.Tag t, int pos) {
         if (t == HTML.Tag.DL && parent != null) {
              parent = (BookmarkDirectory)parent.getParent();
    public static class BookmarkDirectory extends DefaultMutableTreeNode {
         /** Dates created. */
         private Date created;
         public BookmarkDirectory(String name) {
         super(name);
         public void setName(String name) {
         setUserObject(name);
         public String getName() {
         return (String)getUserObject();
         public void setCreated(Date date) {
         this.created = date;
         public Date getCreated() {
         return created;
    public static class BookmarkEntry extends DefaultMutableTreeNode {
         /** User description of the string. */
         private String name;
         /** The URL the bookmark represents. */
         private URL location;
         /** Dates the URL was last visited. */
         private Date lastVisited;
         /** Date the URL was created. */
         private Date created;
         public void setName(String name) {
         this.name = name;
         public String getName() {
         return name;
         public void setLocation(URL location) {
         this.location = location;
         public URL getLocation() {
         return location;
         public void setLastVisited(Date date) {
         lastVisited = date;
         public Date getLastVisited() {
         return lastVisited;
         public void setCreated(Date date) {
         this.created = date;
         public Date getCreated() {
         return created;
         public String toString() {
         return getName();
    // Bookmarks.java END
    // BookmarksModel.java BEGIN
    import java.util.Date;
    public class BookmarksModel extends DynamicTreeTableModel {
    * Names of the columns.
    private static final String[] columnNames =
    { "Name", "Location", "Last Visited", "Created" };
    * Method names used to access the data to display.
    private static final String[] methodNames =
    { "getName", "getLocation", "getLastVisited","getCreated" };
    * Method names used to set the data.
    private static final String[] setterMethodNames =
    { "setName", "setLocation", "setLastVisited","setCreated" };
    private static final Class[] classes =
    { TreeTableModel.class, String.class, Date.class, Date.class };
    public BookmarksModel(Bookmarks.BookmarkDirectory root) {
         super(root, columnNames, methodNames, setterMethodNames, classes);
    public boolean isCellEditable(Object node, int column) {
         switch (column) {
         case 0:
         // Allow editing of the name, as long as not the root.
         return (node != getRoot());
         case 1:
         // Allow editing of the location, as long as not a
         // directory
         return (node instanceof Bookmarks.BookmarkEntry);
         default:
         // Don't allow editing of the date fields.
         return false;
    // BookmarksModel.java END
    // DynamicTreeTableModel.java BEGIN
    import java.lang.reflect.*;
    import javax.swing.tree.*;
    public class DynamicTreeTableModel extends AbstractTreeTableModel {
    /** Names of the columns, used for the TableModel getColumnName method. */
    private String[] columnNames;
    private String[] methodNames;
    private String[] setterMethodNames;
    /** Column classes, used for the TableModel method getColumnClass. */
    private Class[] cTypes;
    public DynamicTreeTableModel(TreeNode root, String[] columnNames,
                        String[] getterMethodNames,
                        String[] setterMethodNames,
                        Class[] cTypes) {
         super(root);
         this.columnNames = columnNames;
         this.methodNames = getterMethodNames;
         this.setterMethodNames = setterMethodNames;
         this.cTypes = cTypes;
    public int getChildCount(Object node) {
         return ((TreeNode)node).getChildCount();
    public Object getChild(Object node, int i) {
         return ((TreeNode)node).getChildAt(i);
    public boolean isLeaf(Object node) {
         return ((TreeNode)node).isLeaf();
    public int getColumnCount() {
         return columnNames.length;
    public String getColumnName(int column) {
         if (cTypes == null || column < 0 || column >= cTypes.length) {
         return null;
         return columnNames[column];
    public Class getColumnClass(int column) {
         if (cTypes == null || column < 0 || column >= cTypes.length) {
         return null;
         return cTypes[column];
    public Object getValueAt(Object node, int column) {
         try {
         Method method = node.getClass().getMethod(methodNames[column],
                                  null);
         if (method != null) {
              return method.invoke(node, null);
         catch (Throwable th) {}
         return null;
    * Returns true if there is a setter method name for column
    * <code>column</code>. This is set in the constructor.
    public boolean isCellEditable(Object node, int column) {
    return (setterMethodNames != null &&
         setterMethodNames[column] != null);
    // Note: This looks up the methods each time! This is rather inefficient;
    // it should really be changed to cache matching
    // methods/constructors
    // based on <code>node</code>'s class, and code>aValue</code>'s
    //class.
    public void setValueAt(Object aValue, Object node, int column) {
         boolean found = false;
         try {
         // We have to search through all the methods since the
         // types may not match up.
         Method[] methods = node.getClass().getMethods();
         for (int counter = methods.length - 1; counter >= 0; counter--) {
              if (methods[counter].getName().equals
              (setterMethodNames[column]) && methods[counter].
              getParameterTypes() != null && methods[counter].
              getParameterTypes().length == 1) {
              // We found a matching method
              Class param = methods[counter].getParameterTypes()[0];
              if (!param.isInstance(aValue)) {
                   // Yes, we can use the value passed in directly,
                   // no coercision is necessary!
                   if (aValue instanceof String &&
                   ((String)aValue).length() == 0) {
                   // Assume an empty string is null, this is
                   // probably bogus for here.
                   aValue = null;
                   else {
                   // Have to attempt some sort of coercision.
                   // See if the expected parameter type has
                   // a constructor that takes a String.
                   Constructor cs = param.getConstructor
                   (new Class[] { String.class });
                   if (cs != null) {
                        aValue = cs.newInstance(new Object[]
                                       { aValue });
                   else {
                        aValue = null;
              // null either means it was an empty string, or there
              // was no translation. Could potentially deal with these
              // differently.
              methods[counter].invoke(node, new Object[] { aValue });
              found = true;
              break;
         } catch (Throwable th) {
         System.out.println("exception: " + th);
         if (found) {
         // The value changed, fire an event to notify listeners.
         TreeNode parent = ((TreeNode)node).getParent();
         fireTreeNodesChanged(this, getPathToRoot(parent),
                        new int[] { getIndexOfChild(parent, node) },
                        new Object[] { node });
    public TreeNode[] getPathToRoot(TreeNode aNode) {
    return getPathToRoot(aNode, 0);
    private TreeNode[] getPathToRoot(TreeNode aNode, int depth) {
    TreeNode[] retNodes;
         // This method recurses, traversing towards the root in order
         // size the array. On the way back, it fills in the nodes,
         // starting from the root and working back to the original node.
    /* Check for null, in case someone passed in a null node, or
    they passed in an element that isn't rooted at root. */
    if(aNode == null) {
    if(depth == 0)
    return null;
    else
    retNodes = new TreeNode[depth];
    else {
    depth++;
    if(aNode == root)
    retNodes = new TreeNode[depth];
    else
    retNodes = getPathToRoot(aNode.getParent(), depth);
    retNodes[retNodes.length - depth] = aNode;
    return retNodes;
    // DynamicTreeTableModel.java END
    // IconRenderer.java BEGIN
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.plaf.basic.BasicTreeUI;
    class IconRenderer extends DefaultTreeCellRenderer
    // Color backColor = new Color(0xD0, 0xCC, 0xFF);
    Color backColor = new Color(0xF0, 0xF0, 0xE0);
    String tipText = "";
    JTree tree;
    int currRow = 0;
    boolean m_selected;
    JTable table;
    public IconRenderer(JTree tree, JTable table) {
    this.table = table;
    // setBackground(backColor);
    setBackground(Color.GREEN);
    setForeground(Color.black);
         this.tree = tree;
    public Component getTreeCellRendererComponent(JTree tree, Object value,
    boolean selected,
    boolean expanded, boolean leaf,
    int row, boolean hasFocus) {
         Object node = null;
         super.getTreeCellRendererComponent(
    tree, value, selected,
    expanded, leaf, row,
    hasFocus);
         TreePath treePath = tree.getPathForRow(row);
    if(treePath != null)
              node = treePath.getLastPathComponent();
    currRow = row;
    m_selected = selected;
    DefaultMutableTreeNode itc = null;
    if (node instanceof DefaultMutableTreeNode) {
    itc = (DefaultMutableTreeNode)node;
         setClosedIcon(closedIcon);
    setOpenIcon(openIcon);
    return this;
    /* Override the default to send back different strings for folders and leaves. */
    public String getToolTipText() {
    return tipText;
    * Paints the value. The background is filled based on selected.
    public void paint(Graphics g) {
         super.paint(g);
         Color bColor = null;
         if(!m_selected) {
              System.out.println(" iconren not sel currRow " + currRow);
              if(currRow % 2 == 0) {
                   bColor = Color.WHITE;
              } else {
              bColor = backColor;
         } else {
              bColor = table.getSelectionBackground();
              System.out.println("in else selbg = " + bColor);           
              bColor = new Color(0xF0, 0xCC, 0x92);
              System.out.println(" bColor aft = " + bColor);           
         int imageOffset = -1;
         if(bColor != null) {
         imageOffset = getLabelStart();
         g.setColor(bColor);
         if(!m_selected) {
              System.out.println(" not sel setting white ");
              g.setXORMode(new Color(0xFF, 0xFF, 0xFF));
         } else {
    //          g.setXORMode(new Color(0xCC, 0xCC, 0x9F));
              g.setXORMode(new Color(0x00, 0x00, 0x00));
              System.out.println(" using color = " + g.getColor());           
         if(getComponentOrientation().isLeftToRight()) {
         g.fillRect(imageOffset, 0, getWidth() - 1 - imageOffset,
                   getHeight());
         } else {
         g.fillRect(0, 0, getWidth() - 1 - imageOffset,
                   getHeight());
    private int getLabelStart() {
         Icon currentI = getIcon();
         if(currentI != null && getText() != null) {
         return currentI.getIconWidth() + Math.max(0, getIconTextGap() - 1);
         return 0;
    // IconRenderer.java END
    // IndicatorRenderer.java BEGIN
    // import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import javax.swing.table.*;
    import javax.swing.table.*;
    import javax.swing.plaf.basic.*;
    import java.awt.event.*;
    import java.util.EventObject;
    import java.text.NumberFormat;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.StringTokenizer;
    import java.util.Arrays;
    class IndicatorRenderer extends DefaultTableCellRenderer {
    /** Makes sure the number of displayed in an internationalized
    * manner. */
    protected NumberFormat formatter;
    /** Row that is currently being painted. */
    protected int lastRow;
    protected int reloadRow;
    protected int reloadCounter;
    protected TreeTableModel treeTableModel;
    protected TreeTableModelAdapter treeTblAdapter;
    protected JTable table;
    Component renderer = null;
    Color backColor = new Color(0xF0, 0xF0, 0xE0);
    IndicatorRenderer(TreeTableModelAdapter treeTblAdapter, TreeTableModel treeTableModel) {
         setHorizontalAlignment(JLabel.RIGHT);
         setFont(new Font("serif", Font.BOLD, 12));
         this.treeTableModel = treeTableModel;
         this.treeTblAdapter = treeTblAdapter;
    * Invoked as part of DefaultTableCellRenderers implemention. Sets
    * the text of the label.
    public void setValue(Object value) {
    /* setText((value == null) ? "---" : formatter.format(value)); */
         setText((value == null) ? "---" : (String) value.toString());
    * Returns this.
    public Component getTableCellRendererComponent(JTable table,
    Object value, boolean isSelected, boolean hasFocus,
    int row, int column) {
         renderer = super.getTableCellRendererComponent(table, value, isSelected,
    hasFocus, row, column);
         lastRow = row;
         this.table = table;
              if(isSelected) {
                   doMask(hasFocus, isSelected);
              } else
              setBackground(table.getBackground());
    return renderer;
    * If the row being painted is also being reloaded this will draw
    * a little indicator.
    public void paint(Graphics g) {
         super.paint(g);
    private void doMask(boolean hasFocus, boolean selected) {
              maskBackground(hasFocus, selected);
    private void maskBackground(boolean hasFocus, boolean selected) {
              Color seed = null;
              seed = table.getSelectionBackground();
              Color color = seed;
              if (color != null) {
                   setBackground(
    new Color(0xF0, 0xCC, 0x92));
    // IndicatorRenderer.java END
    // JTreeTable.java BEGIN
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import java.util.EventObject;
    public class JTreeTable extends JTable {
    /** A subclass of JTree. */
    protected TreeTableCellRenderer tree;
    protected IndicatorRenderer indicatorRenderer = null;
    public JTreeTable(TreeTableModel treeTableModel) {
         super();
         // Creates the tree. It will be used as a renderer and editor.
         tree = new TreeTableCellRenderer(treeTableModel);
         TreeTableModelAdapter tdap = new TreeTableModelAdapter(treeTableModel, tree);
         // Installs a tableModel representing the visible rows in the tree.
         super.setModel(tdap);
         // Forces the JTable and JTree to share their row selection models.
         ListToTreeSelectionModelWrapper selectionWrapper = new
         ListToTreeSelectionModelWrapper();
         tree.setSelectionModel(selectionWrapper);
         setSelectionModel(selectionWrapper.getListSelectionModel());
         // Installs the tree editor renderer and editor.
         setDefaultRenderer(TreeTableModel.class, tree);
         setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor());
         indicatorRenderer = new IndicatorRenderer(tdap, treeTableModel);     
         // No grid.
         setShowGrid(false);
         // No intercell spacing
         setIntercellSpacing(new Dimension(0, 0));     
         // And update the height of the trees row to match that of
         // the table.
         //if (tree.getRowHeight() < 1) {
         // Metal looks better like this.
         setRowHeight(20);
    public TableCellRenderer getCellRenderer(int row, int col) {
              if(col == 0)
              return tree;
              else
              return indicatorRenderer;     
    public void updateUI() {
         super.updateUI();
         if(tree != null) {
         tree.updateUI();
         // Do this so that the editor is referencing the current renderer
         // from the tree. The renderer can potentially change each time
         // laf changes.
         setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor());
         // Use the tree's default foreground and background colors in the
         // table.
    LookAndFeel.installColorsAndFont(this, "Tree.background",
    "Tree.foreground", "Tree.font");
    public int getEditingRow() {
    return (getColumnClass(editingColumn) == TreeTableModel.class) ? -1 :
         editingRow;
    private int realEditingRow() {
         return editingRow;
    public void sizeColumnsToFit(int resizingColumn) {
         super.sizeColumnsToFit(resizingColumn);
         if (getEditingColumn() != -1 && getColumnClass(editingColumn) ==
         TreeTableModel.class) {
         Rectangle cellRect = getCellRect(realEditingRow(),
                             getEditingColumn(), false);
    Component component = getEditorComponent();
         component.setBounds(cellRect);
    component.validate();
    public void setRowHeight(int rowHeight) {
    super.setRowHeight(rowHeight);
         if (tree != null && tree.getRowHeight() != rowHeight) {
    tree.setRowHeight(getRowHeight());
    public JTree getTree() {
         return tree;
    public boolean editCellAt(int row, int column, EventObject e){
         boolean retValue = super.editCellAt(row, column, e);
         if (retValue && getColumnClass(column) == TreeTableModel.class) {
         repaint(getCellRect(row, column, false));
         return retValue;
    public class TreeTableCellRenderer extends JTree implements
         TableCellRenderer {
         /** Last table/tree row asked to renderer. */
         protected int visibleRow;
         /** Border to draw around the tree, if this is non-null, it will
         * be painted. */
         protected Border highlightBorder;
         public TreeTableCellRenderer(Tr

  • Rendering alternate colors in JTree

    I have a JTree within a scrollpane.
    What I would like to do is have every alternate line on the JTree rendered with one of 2 colors, i.e. line 1 is blue, line 2 is yellow, line 3 is blue etc.
    The tricky bit is that I want this color to fill the width of the scrollpane - changing the background of the JLabel color in the renderer will only update from the tree node to the right of the scrollpane (it leaves the area to the left of the node blank).
    Am I making any sense?

    Try this
    regards
    Stas
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.tree.*;
    public class Test {
    JScrollPane scroll;
    JTree tree;
    public Test() throws Exception {
    JFrame frame=new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    DefaultMutableTreeNode root=new DefaultMutableTreeNode("root");
    DefaultMutableTreeNode node1=new DefaultMutableTreeNode("node1");
    DefaultMutableTreeNode node2=new DefaultMutableTreeNode("node2");
    root.add(node1);
    root.add(node2);
    DefaultMutableTreeNode subnode2=new DefaultMutableTreeNode("node2_1");
    node2.add(subnode2);
    subnode2=new DefaultMutableTreeNode("node2_2");
    node2.add(subnode2);
    subnode2=new DefaultMutableTreeNode("node2_3");
    node2.add(subnode2);
    tree=new JTree(root);
    tree.setCellRenderer(new MyRenderer());
    frame.getContentPane().add(tree);
    frame.setBounds(100,100,200,200);
    frame.show();
    public static void main(String[] args) throws Exception {
    new Test();
    class MyRenderer extends DefaultTreeCellRenderer {
    public MyRenderer() {
    super();
    setOpaque(true);
    public Component getTreeCellRendererComponent(JTree tree, Object value,
    boolean sel,
    boolean expanded,
    boolean leaf, int row,
    boolean hasFocus) {
    JLabel l=(JLabel)super.getTreeCellRendererComponent(tree, value,
    sel,
    expanded,
    leaf, row,
    hasFocus);
    l.setPreferredSize(new Dimension(5000,20));
    if (row % 2==0) {
    l.setBackground(Color.CYAN);
    else {
    l.setBackground(Color.YELLOW);
    return l;

  • Changing colors in JTree

    How to change the color of the lines between specified nodes in JTree ?
    I would like to change colour of the line only between 2 specified nodes. Is this possibly ?

    looks like you would have to write your own UI, overriding
    drawDashedHorizontalLine()
    drawDashedVerticalLine()

  • JTree Node Color, to distinguish between different activities

    Hi,
    Situation:          Dynamic JTree (Tree is constructed from as a result of Database). User has the option to either Enable / Disable node and can repeat the activities but restricted only one activity per node, the node is to be highlighted; to restrict the user from further activities.
    Problem:          Am a newbie to swing, after searching the forum for the same, i found few good solutions which are specific to color change of specific selected node, in a temporary context.
         But we need the node color change within a same level; to distinguish either the node is either enabled / disabled.
    Your help is appreciated,

    durino13 wrote:
    1. Is the approach above a good approach, how to load children 'lazilly'?Sounds pretty reasonable to me.
    2. I also use custom renderer to display different icons for every "tree" level. When I initially expand the 4th level, everything works fine !!! Then I collapse the 4th level and expand it again and here my problem starts: my 4th level icon is set to 'root level icon' instead of '4th level' icon. This does not happen, if computerNode.removeAllChildren(); method is removed from listening above
    Any idea, what am i doing wrong?Ummmm... Load the model the first time (only) the node is expanded... Putz!
    And I suggest you listen deeply to Mr Jacobs... He really does know what he's talking about ;-)
    ... and not this time, but in future: Swing questions are best asked in [THE Swing Forum|http://forums.sun.com/forum.jspa?forumID=57].
    Cheers. Keith.

  • Setting the color of a particular node in JTree

    Hi all!
    I'm new to Java and facing a problem with JTrees.
    I'm using the following snippet to create a JTree :
    DeafultMutableTreeNode root = new DefaultMutableTeeNode("Letters");
    DeafultMutableTreeNode parent1 = new DefaultMutableTeeNode("uppercase");
    DeafultMutableTreeNode parent2 = new DefaultMutableTeeNode("lowercase");
    DeafultMutableTreeNode child1 = new DefaultMutableTeeNode("A");
    DeafultMutableTreeNode child2 = new DefaultMutableTeeNode("B");
    DeafultMutableTreeNode child3 = new DefaultMutableTeeNode("C");
    DeafultMutableTreeNode child4 = new DefaultMutableTeeNode("a");
    DeafultMutableTreeNode child5 = new DefaultMutableTeeNode("b");
    DeafultMutableTreeNode child6 = new DefaultMutableTeeNode("c");
    root.add(parent1);
    root.add(parent2);
    parent1.add(child1);
    parent1.add(child2);
    parent1.add(child3);
    parent2.add(child4);
    parent2.add(child5);
    parent2.add(child6);
    JTree tree = new JTree(root);
    JScrollPane pane = new JScrollPane(tree);
    TreePath path = tree.getNextMatch("lowercase", 0, javax.swing.text.Position.Bias.Forward);
    tree.setSelectionPath(path);
    tree.expandPath(path);
    In the above JTree, the node labeled "lowercase" gets selected and expanded as soon as the program is run.
    What i want to know is that, is there any way in which i can set only the "lowercase" node's background to a different color (say, YELLOW) and have it so, no matter if the node is expanded or collapsed or other nodes are expanded or collapsed.
    ps: Sample snippet would really b helpful.

    You need to write your own renderer for this.
    Read the tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#display

  • Setting the color of a node in JTree

    Hi all!
    I'm new to Java and facing a problem with JTrees.
    I'm using the following snippet to create a JTree :
    DeafultMutableTreeNode root = new DefaultMutableTeeNode("Letters");
    DeafultMutableTreeNode parent1 = new DefaultMutableTeeNode("uppercase");
    DeafultMutableTreeNode parent2 = new DefaultMutableTeeNode("lowercase");
    DeafultMutableTreeNode child1 = new DefaultMutableTeeNode("A");
    DeafultMutableTreeNode child2 = new DefaultMutableTeeNode("B");
    DeafultMutableTreeNode child3 = new DefaultMutableTeeNode("C");
    DeafultMutableTreeNode child4 = new DefaultMutableTeeNode("a");
    DeafultMutableTreeNode child5 = new DefaultMutableTeeNode("b");
    DeafultMutableTreeNode child6 = new DefaultMutableTeeNode("c");
    root.add(parent1);
    root.add(parent2);
    parent1.add(child1);
    parent1.add(child2);
    parent1.add(child3);
    parent2.add(child4);
    parent2.add(child5);
    parent2.add(child6);
    JTree tree = new JTree(root);
    JScrollPane pane = new JScrollPane(tree);
    TreePath path = tree.getNextMatch("lowercase", 0, javax.swing.text.Position.Bias.Forward);
    tree.setSelectionPath(path);
    tree.expandPath(path);
    In the above JTree, the node labeled "lowercase" gets selected and expanded as soon as the program is run.
    What i want to know is that, is there any way in which i can set only the "lowercase" node's background to a different color (say, YELLOW) and have it so, no matter if the node is expanded or collapsed or other nodes are expanded or collapsed.
    ps: Sample snippet would really b helpful.

    You need to write your own renderer for this.
    Read the tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#display

  • Setting jtree objects' color

    Hi all
    I have a small (?) problem changing the background color of a jtree object.
    I change the background color to black with setBackground method but the objects in it remains white. I want them to be in black background color, too. and I couldn't find a solution. How can I do that?
    thanks

    I have a small (?) problem changing the background
    color of a jtree object.Do you mean the instance of JTree, or one of its nodes?
    Just a few guesses - the Swing experts are in the Swing forum:
    - maybe the tree background is transparent and you actually see the background of the pane it's on. Did you set the JTree to be opaque?
    - did you think about custom renderers?

  • Dynamically changing the color of nodes in a JTree

    I have created a JTree and want to dynamically change the color of some of the TreeNodes as my program runs. The JTree is displayed in a JPanel. There is an algorithm built into which identifies the nodes whose color I need to change. No user actions is performed (everythign is internal to the program).
    It seems that in the TreeCellRender only kicks in when the tree is first displayed. How do I get it to re-render the tree when the TreeModel changes? It seems that the Listeners are only looking for external user interactions.
    Any help would be greatly appreciated.
    Thanks!

    I think I was a bit too vague in my question. Let me try again...
    I have changed an attribute in a node in a JTree. This attribute is changed after the tree was initially rendered, but while the program is still running. I want to tell the TreeCellRenderer to look again at this node since that attribute that was changed will effect how the node should be renderered. I tried using the nodeChanged() method, but it did not work (the colot of the node did not change). Any advise how I can do this?
    Thanks!

Maybe you are looking for

  • To see values of same column in a single row

    Hi, I have a requirement. I've to show all the column values in a row (as a comma separated) through a single query (No custom functions can't be used). For example EMP table has these records (no fix no. of records). empno ename 123 BILL 234 SCOTT 2

  • Can't connect to internet on my old g4 flat screen, network + airport ok

    I installed an airport card on the g4 (dome) and connected to our wireless network, which gets a signal, (though the status is "not available"). I can't connect to internet (server not recognized), and every time I check the internet assistant app, t

  • Can Firefox provide an option to keep the refresh button next to the forward/back buttons?

    When I first installed FF4 the refresh button was buried on the righthand side of the URL window. There were a number of complaints about that location. Then the button got moved next to the forward/back buttons. This made me quite happy. Today, I fi

  • How do I install / update a specific kernel module?

    Hi I'm trying to update an existing kernel module. I can download it and it comes with a pretty easy to use Makefile based on http://www.kernel.org/doc/Documentation - odules.txt. The Makefile installs the newly created module into /lib/modules/$kern

  • Trouble with charAt and nested for loops

    Hi, I have a programming assignment in which my goal is to write a program that reads a social security number written as contiguous digits (eg, 509435456; obtained via JOptionPane); uses charAt to obtain each character; and then prints each digit on