Tweaking LAF icons for JTree
What I want to do, at the moment, is to indicate some JTree nodes as disabled, but this could be a more general question. I realise I can substitute a custome renderer to replace the icons representing tree nodes with an image of my own. But I want the replacements to be consistent in appearance with the standard images used in the Windows LAF, ideally I'd like a coresponding stuff for the metal LAF too.
So:
1) Where are the standard bitmaps squirelled away so I can grab and modify them.
2) Is there a proper way of switching images on the basis of the chosen LAF.
1) I don't know where they are, but you can get them with (e.g.):
Icon openIcon = (Icon)UIManager.get("Tree.openIcon");2) You can check the currently installed LAF and then decide which icons you use:
if (UIManager.getLookAndFeel() instanceof javax.swing.plaf.metal.MetalLookAndFeel) {
UIManager.put("Tree.openIcon", new ImageIcon(getClass().getResource("resources/images/open.png")));
UIManager.put("Tree.closedIcon", new ImageIcon(getClass().getResource("resources/images/closed.png")));
UIManager.put("Tree.collapsedIcon", new ImageIcon(getClass().getResource("resources/images/collapsed.png")));
UIManager.put("Tree.expandedIcon", new ImageIcon(getClass().getResource("resources/images/expanded.png")));
UIManager.put("Tree.leafIcon", new ImageIcon(getClass().getResource("resources/images/leaf.png")));
}After setting such properties you should call
SwingUtilities.updateComponentTreeUI(<component>);to update the whole component tree starting with <component>. So, <component> often is the applet or the main frame of an application where your ui modifications take place..
Sources:
i) LAF-Demos in <java-install-dir>/demo/jfc/Metalworks
ii) Code example to list LAF-properties in a table (search for "ListProperties"): http://forum.javacore.de/viewtopic.php?p=5682&sid=301abe27a4d5fb3099b130c55a6a52e7
Similar Messages
-
Unable to display blinking icon for JTree
I am unable to see blinking icon for JTree node. If I use any other image which is not blinking, then I am able to see icon.
If blinking image is used, it shows blank image.
Please refer to following code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
public class TreeApplet extends JApplet {
JTree tree;
DefaultMutableTreeNode root;
DefaultMutableTreeNode node1;
DefaultMutableTreeNode node2;
DefaultMutableTreeNode node3;
DefaultMutableTreeNode node4;
private ImageIcon errorIcon = null;
private URL resource = null;
private static final long serialVersionUID = 1L;
public void init() {
errorIcon = loadIcon("images/errorBlink.gif");
root = new DefaultMutableTreeNode(new ProcessInfo("root", "error"));
node1 = new DefaultMutableTreeNode(new ProcessInfo("Node1", "info"));
node2 = new DefaultMutableTreeNode(new ProcessInfo("Node2", "warn"));
node3 = new DefaultMutableTreeNode(new ProcessInfo("Node3", "debug"));
node4 = new DefaultMutableTreeNode(new ProcessInfo("Node4", "error"));
node1.add(node2);
node3.add(node4);
root.add(node1);
root.add(node3);
setLayout(new BorderLayout());
tree = new JTree(root);
tree.setCellRenderer(new TreeRenderer());
add(new JScrollPane((JTree) tree), "Center");
private class TreeRenderer extends DefaultTreeCellRenderer {
private static final long serialVersionUID = 1L;
public TreeRenderer() {
this.setBackgroundSelectionColor(Color.lightGray);
this.setBorderSelectionColor(Color.BLACK);
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf,
int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
setIcon(getStatus(value));
return this;
private ImageIcon getStatus(Object value) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
ProcessInfo nodeInfo = (ProcessInfo) node.getUserObject();
String status = nodeInfo.getStatus();
if ( status != null ) {
if ( status.equalsIgnoreCase("error") ) {
return errorIcon;
return null;
private ImageIcon loadIcon(String name) {
ImageIcon icon = null;
resource = this.getClass().getResource(name);
if ( resource != null ) {
icon = new ImageIcon(resource);
return icon;
}1. Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
2. A renderer is just a "rubber stamp" used to paint on the table/tree/list/whatever. You can't display animation in an ImageIcon by setting it to a renderer. Since the JLabel subclass used as the renderer isn't a part of any visible component hierarchy, the icon won't be refreshed with new frames.
db -
How to Use different icons for JTree in the same level
Hi guys, i come cross a problem with JTree. The module need a JTree which need to represent items in the same level using different icons. For example:
[Icon for Root]Root
|
|_____________[Icon for Table] TABLES
|
|_____________[Icon for Index] INDEXS
|
|_____________[Icon for Views] VIEWS
As i know, the default behavior for JTree is using the same icon for all leaves and
the same icon for all node that has children. How can i achieve that?
Thansk a lot!subclass DefaultTreeCellRenderer. if you overwrite the method below, then you can set the icon to whatever you want....!
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel,
boolean expanded,
boolean leaf, int row,
boolean hasFocus) {
String stringValue = tree.convertValueToText(value, sel,
expanded, leaf, row, hasFocus);
this.tree = tree;
this.hasFocus = hasFocus;
setText(stringValue);
if(sel)
setForeground(getTextSelectionColor());
else
setForeground(getTextNonSelectionColor());
// There needs to be a way to specify disabled icons.
if (!tree.isEnabled()) {
setEnabled(false);
if (leaf) {
setDisabledIcon(getLeafIcon());
} else if (expanded) {
setDisabledIcon(getOpenIcon());
} else {
setDisabledIcon(getClosedIcon());
else {
setEnabled(true);
if (leaf) {
setIcon(getLeafIcon());
} else if (expanded) {
setIcon(getOpenIcon());
} else {
setIcon(getClosedIcon());
setComponentOrientation(tree.getComponentOrientation());
selected = sel;
return this;
} -
How do I remove expand / collapse icon for JTree empty folders
Hi
I am using a JTree as a file system browser. I use DefaultMutableTreeNode nodes.
I have a problem with empty folders.
Empty folders show the expand / collapse icon, leading the user to believe there are sub-directories. When the user double-clicks the folder, the expand / collapse icon goes away. This is a "haha-gotcha" glitch that I really don't want my users to have to continually deal with.
So, how might I get my JTree to not show the expand / collapse icon for empty folders?
Thanks
WayneMaybe I can use the FileSystemView isTraversable(File f) method in my TreeCellRenderer class to check if anything is in the directory.
But I still need to know how to disable the expand / collapse icon for such a node. -
Using animation as icon for JTree node
Hi,
I am using a custom tree cell renderer. I have a label in the renderer, the label have gif Image Icon, but the problem is it is not getting animated. But when I use a JLabel with gif icon some where else it is working fine, but it is not working for tree node.
package com.gopi.utilities.gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeCellRenderer;
import com.gopi.remfilebrowser.gui.GUIUtil;
import com.gopi.remfilebrowser.util.FileBrowserConstants;
public class CustomTreeCellRenderer implements TreeCellRenderer
private JPanel panel;
private JLabel label;
private TreeCellRenderer defaultRenderer;
public CustomTreeCellRenderer()
super();
panel = GUIUtil.createGridBagPanel();
label = new JLabel();
label.setHorizontalAlignment(JLabel.LEFT);
System.out.println("New");
GridBagConstraints gc = new GridBagConstraints();
GUIUtil.fillComponent(panel,label);
defaultRenderer = new DefaultTreeCellRenderer();
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel,
boolean expanded,
boolean leaf, int row,
boolean hasFocus)
if(value instanceof NewAbstractTreeNode)
NewAbstractTreeNode node = (NewAbstractTreeNode) value;
System.out.println("dr");
label.setText(value.toString());
label.setIcon(ImageLoader.getInstance().getIcon(node.getIconKey()));
if(hasFocus && sel)
panel.setBackground(FileBrowserConstants.TREE_NODE_SELECTED_COLOR);
else if(sel)
panel.setBackground(FileBrowserConstants.TREE_NODE_UNSELECTED_COLOR);
else
panel.setBackground(Color.white);
return panel;
return defaultRenderer.getTreeCellRendererComponent(tree,value,sel,expanded,leaf,row,hasFocus);
}JLabels using ImageIcons are designed to display the icon as is, including animation and all.
A CellRenderer only paints the Icon once, when the cell is painted. Much ike a rubber stamp of the JComponent. Hence, its not designed to do the animation and all.
If you really want it, you can probably use MediaTracker and a Timer to do your animation scheduling. Might not be very pretty code though
ICE -
hi,
I have a JTree. For this JTree i have a DefaultJTreeCellRenderer.
i have done like this
JTree tree = new JTree();
DefaultJTreeCellRenderer renderer = new DefaultJTreeCellRenderer();
renderer.setOpenIcon(....);
renderer.serCloseIcon(...);
tree.setCellRenderer(renderer);but this is not working.
how to change the icons of the node when i click
thank youpublic class Test extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton buttonCreate;
private JTree tree;
private DefaultMutableTreeNode defaultMutableTreeNode;
private DefaultTreeModel defaultTreeModel;
private int i;
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
layoutComponents();
setSize(400, 400);
setLocationRelativeTo(null);
setVisible(true);
private void layoutComponents() {
defaultMutableTreeNode = new DefaultMutableTreeNode("Root");
defaultTreeModel = new DefaultTreeModel(defaultMutableTreeNode);
tree = new JTree(defaultTreeModel);
tree.setRootVisible(false);
buttonCreate = new JButton("Create");
getContentPane().setLayout(new BorderLayout());
getContentPane().add(tree, BorderLayout.CENTER);
getContentPane().add(buttonCreate, BorderLayout.SOUTH);
DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
ImageIcon icon_close = new ImageIcon("./images/project_closed.gif");
ImageIcon icon_open = new ImageIcon("./images/project_opened.gif");
renderer.setOpenIcon(icon_open);
renderer.setClosedIcon(icon_close);
tree.setCellRenderer(renderer);
buttonCreate.addActionListener(this);
public static void main(String[] args) {
new Test();
public void actionPerformed(ActionEvent e) {
addElementToParent("Child" + i++);
private DefaultMutableTreeNode addElementToParent(Object theChild) {
return addElementToParent(defaultMutableTreeNode, theChild, true);
private DefaultMutableTreeNode addElementToParent(DefaultMutableTreeNode theParent, Object theChild, boolean shouldBeVisible) {
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(theChild);
if (theParent == null) {
theParent = defaultMutableTreeNode;
defaultTreeModel.insertNodeInto(childNode, theParent, theParent.getChildCount());
TreePath childTreePath = new TreePath(childNode.getPath());
// Make sure the user can see the lovely new node.
if (shouldBeVisible) {
tree.scrollPathToVisible(childTreePath);
tree.requestFocusInWindow();
return childNode;
}this is the code which i was trying to execute.
here i want to explain you is
when i click the node the icon should change to open_icon
when i click the other node the previous node icon should change to close_icon
how is this possible
null -
How to display different icon, for different node of jtree
Hi All,
How to display different icon, for different node of jtreeyou haven't responded to my last post here: [http://forums.sun.com/thread.jspa?threadID=5323190&messageID=10382676#10382676|http://forums.sun.com/thread.jspa?threadID=5323190&messageID=10382676#10382676]
-
Defining different icons for TreeNode by extending DefaultTreeCellRenderer
Hello all,
I'm using a JTree to display project, folder and files. I'd like to have different icons for open project, close project, open folder, close folders, and files
but i got for the root which is a project object a folder icon and for folder when it is not expanded i got project icon and the when i expand it i got a folder icon, can someone help me please
Here is my code :
public class MyTreeCellRenderer extends DefaultTreeCellRenderer {
private Icon openIcon = null;
private Icon closeIcon = null;
private Icon leafIcon = null;
private Icon projectOpenIcon = new ImageIcon("icons/book_open.png");
private Icon projectCloseIcon = new ImageIcon("icons/book_blue.png");
private Icon folderOpenIcon = new ImageIcon("icons/folder.png");
private Icon folderCloseIcon = new ImageIcon("icons/folder_closed.png");
private Icon fileIcon = new ImageIcon("icons/document.png");
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row,
hasFocus);
LogescoTreeNode node =
(LogescoTreeNode)value;
Object obj = node.getUserObject();
System.out.println(obj.getClass().toString());
if(openIcon == null) {
openIcon = this.getOpenIcon();
if(openIcon != null) {
if(obj instanceof LProject) {
openIcon = projectOpenIcon;
this.setOpenIcon(openIcon);
openIcon = null;
} else if(obj instanceof LFolder) {
openIcon = folderOpenIcon;
this.setOpenIcon(openIcon);
openIcon = null;
if(closeIcon == null) {
closeIcon = this.getClosedIcon();
if(closeIcon != null) {
if(obj instanceof LProject) {
closeIcon = projectCloseIcon;
this.setClosedIcon(closeIcon);
closeIcon = null;
} else if(obj instanceof LFolder) {
closeIcon = folderCloseIcon;
this.setClosedIcon(closeIcon);
closeIcon = null;
this.setLeafIcon(fileIcon);
return this;
}Thank you.Hi all,
I changed my code a bit knowing that the renderer is global to the tree so my (openIcon == null) is called only once for the first node.
Here is my new code :
public class MyTreeCellRenderer extends DefaultTreeCellRenderer {
private Icon projectOpenIcon = new ImageIcon("icons/book_open.png");
private Icon projectCloseIcon = new ImageIcon("icons/book_blue.png");
private Icon folderOpenIcon = new ImageIcon("icons/folder.png");
private Icon folderCloseIcon = new ImageIcon("icons/folder_closed.png");
private Icon fileIcon = new ImageIcon("icons/document.png");
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, selected,
expanded, leaf, row, hasFocus);
LogescoTreeNode node =
(LogescoTreeNode)value;
Object obj = node.getUserObject();
System.out.println(obj.getClass().toString());
if(obj instanceof LProject) {
this.setIcon(expanded ? projectOpenIcon : projectCloseIcon);
} else if(obj instanceof LFolder) {
this.setIcon(expanded ? folderOpenIcon : folderCloseIcon);
} else {
this.setIcon(fileIcon);
return this;
} -
Hi,
Can anyone tell me how to change the icon for a particular node in a JTree?
I know how to change all the leafs for example by using the DefaultTreeCellRenderer.setLeafIcon()method. But do you know how to set just one node to a particular icon?
Cheers,
JimMyTreeCellRenderer extends DefaulTreeCellRenderer{
public Component getTreeCellRendererComponent(
JTree tree,
Object value,
boolean sel,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
super.getTreeCellRendererComponent(
tree, value, sel,
expanded, leaf, row,
hasFocus);
//Do your condition on your value
if( value ....){
setIcon(myIcon);
return this;
} -
i want to remove blue lever shown with each branch node
in jtree please help i searched but couldn't find a solution
thanxhi i downloadeed this code from sun java tutorial
successfully changed all icons except that blue lever at extreme left of each branch node
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.event.TreeSelectionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.tree.TreeSelectionModel;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.ImageIcon;
import java.net.URL;
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
public class TreeIconDemo extends JFrame {
private JEditorPane htmlPane;
private static boolean DEBUG = false;
private URL helpURL;
public TreeIconDemo() {
super("TreeIconDemo");
//Create the nodes.
DefaultMutableTreeNode top = new DefaultMutableTreeNode("The Java Series");
createNodes(top);
//Create a tree that allows one selection at a time.
final JTree tree = new JTree(top);
tree.getSelectionModel().setSelectionMode
(TreeSelectionModel.SINGLE_TREE_SELECTION);
* Set the icon for leaf nodes.
* Note: In the Swing 1.0.x release, we used
* swing.plaf.basic.BasicTreeCellRenderer.
DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
renderer.setLeafIcon(new ImageIcon("yoshi.gif"));
renderer.setClosedIcon(new ImageIcon("yoshi.gif"));
renderer.setOpenIcon(new ImageIcon("yoshi.gif"));
tree.setCellRenderer(renderer);
//Listen for when the selection changes.
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)
tree.getLastSelectedPathComponent();
if (node == null) return;
Object nodeInfo = node.getUserObject();
if (node.isLeaf()) {
BookInfo book = (BookInfo)nodeInfo;
displayURL(book.bookURL);
if (DEBUG) {
System.out.print(book.bookURL + ": \n ");
} else {
displayURL(helpURL);
if (DEBUG) {
System.out.println(nodeInfo.toString());
//Create the scroll pane and add the tree to it.
JScrollPane treeView = new JScrollPane(tree);
//Create the HTML viewing pane.
htmlPane = new JEditorPane();
htmlPane.setEditable(false);
initHelp();
JScrollPane htmlView = new JScrollPane(htmlPane);
//Add the scroll panes to a split pane.
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
splitPane.setTopComponent(treeView);
splitPane.setBottomComponent(htmlView);
Dimension minimumSize = new Dimension(100, 50);
htmlView.setMinimumSize(minimumSize);
treeView.setMinimumSize(minimumSize);
splitPane.setDividerLocation(100); //XXX: ignored in some releases
//of Swing. bug 4101306
//workaround for bug 4101306:
//treeView.setPreferredSize(new Dimension(100, 100));
splitPane.setPreferredSize(new Dimension(500, 300));
//Add the split pane to this frame.
getContentPane().add(splitPane, BorderLayout.CENTER);
private class BookInfo {
public String bookName;
public URL bookURL;
public String prefix = "file:"
+ System.getProperty("user.dir")
+ System.getProperty("file.separator");
public BookInfo(String book, String filename) {
bookName = book;
try {
bookURL = new URL(prefix + filename);
} catch (java.net.MalformedURLException exc) {
System.err.println("Attempted to create a BookInfo "
+ "with a bad URL: " + bookURL);
bookURL = null;
public String toString() {
return bookName;
private void initHelp() {
String s = null;
try {
s = "file:"
+ System.getProperty("user.dir")
+ System.getProperty("file.separator")
+ "TreeDemoHelp.html";
if (DEBUG) {
System.out.println("Help URL is " + s);
helpURL = new URL(s);
displayURL(helpURL);
} catch (Exception e) {
System.err.println("Couldn't create help URL: " + s);
private void displayURL(URL url) {
try {
htmlPane.setPage(url);
} catch (IOException e) {
System.err.println("Attempted to read a bad URL: " + url);
private void createNodes(DefaultMutableTreeNode top) {
DefaultMutableTreeNode category = null;
DefaultMutableTreeNode book = null;
category = new DefaultMutableTreeNode("Books for Java Programmers");
top.add(category);
//original Tutorial
book = new DefaultMutableTreeNode(new BookInfo
("The Java Tutorial: Object-Oriented Programming for the Internet",
"tutorial.html"));
category.add(book);
//Tutorial Continued
book = new DefaultMutableTreeNode(new BookInfo
("The Java Tutorial Continued: The Rest of the JDK",
"tutorialcont.html"));
category.add(book);
//JFC Swing Tutorial
book = new DefaultMutableTreeNode(new BookInfo
("The JFC Swing Tutorial: A Guide to Constructing GUIs",
"swingtutorial.html"));
category.add(book);
//Arnold/Gosling
book = new DefaultMutableTreeNode(new BookInfo
("The Java Programming Language", "arnold.html"));
category.add(book);
//FAQ
book = new DefaultMutableTreeNode(new BookInfo(
"The Java FAQ", "faq.html"));
category.add(book);
//Chan/Lee
book = new DefaultMutableTreeNode(new BookInfo
("The Java Class Libraries: An Annotated Reference",
"chanlee.html"));
category.add(book);
//Threads
book = new DefaultMutableTreeNode(new BookInfo
("Concurrent Programming in Java: Design Principles and Patterns",
"thread.html"));
category.add(book);
category = new DefaultMutableTreeNode("Books for Java Implementers");
top.add(category);
//VM
book = new DefaultMutableTreeNode(new BookInfo
("The Java Virtual Machine Specification",
"vm.html"));
category.add(book);
//Language Spec
book = new DefaultMutableTreeNode(new BookInfo
("The Java Language Specification",
"jls.html"));
category.add(book);
public static void main(String[] args) {
JFrame frame = new TreeIconDemo();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
frame.pack();
frame.setVisible(true); -
Possibility to have your own icons in JTree depending on what node
Can you specify your own icons in a JTree? With this I mean more than your own directory/leaf icons. For example, if you have a family tree, you might want different icons for sons and daugthers etc.
I did like you said, and it works, almost.
I use the following code to find out what type my nodes in the tree are. I can just look at my NodeInfo object to get that. But when I click at different nodes in the tree, other nodes than the clicked one changes icons.
DefaultMutableTreeNode node =
(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
NodeInfo selectedNode = (NodeInfo)node.getUserObject();Edit: Also tried this code but that gave me:
Exception in thread "main" java.lang.ClassCastException: java.lang.String
at gui.MyTreeCellRenderer.getTreeCellRendererComponent(MyTreeCellRenderer.java:26)
DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
NodeInfo selectedNode = (NodeInfo)node.getUserObject();Message was edited by:
sandsater -
Hi...
In my JTree, I have two class (that extend DefaultMutableTreeNode) that can be leaf. I want to set different Icons for each one of the class. How do I do that? Below, the code I tryed, it does not work (the icons change, but sometimes they are associated with the wrong class).
public class VRTreeCellRenderer extends DefaultTreeCellRenderer {
public Component getTreeCellRendererComponent (JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, selected, expanded,
leaf, row, hasFocus);
if (value.getClass() == DefaultPort.class) {
this.setLeafIcon(new ImageIcon (MainApp.gifIconPath + "door.gif"));
} else if (value.getClass() == Stream.class) {
this.setLeafIcon(new ImageIcon (MainApp.gifIconPath +
"corrente.gif"));
return this;
}Gack!!!
Don't go loading and creating images inside this method, it's done on the paint loop and you'll slow it down. Load your images up front and store them as field in the object.
Don't use "foo.getClass() == Bar.class" to compare classes, use "foo instanceof Bar" - otherwise you can fall over if multiple class loaders are used.
Don't throw away the value returned by the superclass method, use it. You discard it and then return "this" - which in actual fact works fine as you know, but semantically it's wrong and if the implementation of the default renderer changes then your code breaks.
Also, by the time you set the icon it's too late. The superclass has already configured the component for the cell in question; you are in fact configuring it for the next time it passes through. So, move those methods above your call to the superclass method. -
Individual leaf icons in JTree
is it possible to for different leaves in the same tree to have different icons?
I tried this code:
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Actors");
File dir = new File("images\\actors\\");
int i = 0;
DefaultMutableTreeNode actorChild;
String[] fileArray = dir.list();
while (i < dir.listFiles().length){
ImageIcon icon = new ImageIcon(getClass().getResource("images\\actors\\" + fileArray));
DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
renderer.setLeafIcon(icon);
actorChild = new DefaultMutableTreeNode(fileArray[i]);
root.add(actorChild);
i++;
actorTree.setCellRenderer(renderer);
DefaultTreeModel t = new DefaultTreeModel(root);
actorTree.setModel(t);
However as you can see it merely sets all leaf icons to the last value from the last iteration of the loop.
any info appreciated :)This is my latest attempt, but it still doesnt work, it just makes the icon for the last item in the jtree.
I cant figure out what im doing wrong here, any ideas?
class CustomIconRenderer extends JLabel implements TreeCellRenderer {
String[] fileArray;
CustomIconRenderer(String[] fileArray){
this.fileArray = fileArray;
public Component getTreeCellRendererComponent(JTree tree,
Object value, boolean sel, boolean expanded, boolean leaf,
int row, boolean hasFocus) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
Object obj = node.getUserObject();
String nodeName = obj.toString();
setText(nodeName); // set the text
int i = 0;
while (i < fileArray.length){
if (nodeName.endsWith(fileArray)){
Icon icon = new ImageIcon(getClass().getResource("images\\actors\\"+ nodeName));
setIcon(icon);
else{
setIcon(null);
i++;
return this; -
I want to change different icon for different leaf node
Hi,
i am reading file system(win 2000)and showing in a tree.i want to
show different icon for different file extension.
Pl suggest me with sample code,how should i do?
ThanxHi...
To do this, u need to write ur own TreeCellRenderer.
ex :
class FileSystemTreeCellRenderer extends JLabel implements TreeCellRenderer
File file= null;
public FileSystemTreeCellRenderer(File f)
this.file = f;
public Component getTreeCellRendererComponent
JTree tree,
Object value,
boolean selected,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus
if(file.isDirectory())
setIcon("your image");
setText("file/dir name");
else
setIcon("your other image");
setText("file/dir name");
return this;
Hope it suits ur need .. (also, using the file extensions, u can set different icons following the above strategy...)
Regards,
Ramanujam -
I have just updated to iOS7, no icon for browser, was using Safari, how do I get it back and can I reverse the upgrade and go back to iOS6? Thanks to you from the UnTechie
The icon for Safari has probably moved to make room for new apps. Scroll the Home screen to look for it.
You cannot reverse the upgrade.
Maybe you are looking for
-
Bind multiple fields to one node in data view
I have a need to have an interactive form where data from a single data source is displayed in multiple fields on the form. In addition these fields are open for input. I have bound the multiple fields on the form to one node in the data view. The
-
For no apparent reason, the printing from the iPad to the HP wireless printer was no more possible, while it was still possible from the iPhone 5. Any idea why?
-
Forte for Java CE won't run files created with J2SDK
I'm very new to Java. When I try to run packages, classes written with Java 2 SDK, I get the following error: java.lang.NoClassDefFoundError: TextComponentPrintWriter (wrong name: utilities/TextComponentPrintWriter) I have mounted the root directory
-
Sending smartform output as PDF attachment, Error opening PDF attachment
Hi Experts, I am using the code form the following link to send a smartform output as PDF attachment. I can able to see the message, but can not open PDF document. https://www.sdn.sap.com/irj/sdn/wiki?path=/display/snippets/convertSmartformtoPDFforma
-
Hi, I have create the vendor Currency as USD and enter the GRN. And the GRN quantity has been issued to production. Now part of quantity is avaiable in stock. Now i need to change the Vendor Currecnty to INR. Please let me know how can do this cha