How to make JTree transparent?

import javax.swing.*;

import javax.swing.tree.*;

import java.awt.*;

publicclass TreeTestFrameextends JFrame

{

public TreeTestFrame()

{

DefaultMutableTreeNode root=new DefaultMutableTreeNode("root");

DefaultMutableTreeNode nodeA=new DefaultMutableTreeNode("A");

DefaultMutableTreeNode nodeB=new DefaultMutableTreeNode("B");

root.add(nodeA);

root.add(nodeB);

DefaultTreeModel model=new DefaultTreeModel(root);

JTree tree=new JTree(model);

tree.setOpaque(false);

tree.setCellRenderer(new TestTreeCellRenderer());

getContentPane().add(tree);

}

publicstaticvoid main(String[] args)

{

Window w=new TreeTestFrame();

w.pack();

w.setVisible(true);

}

}

class TestTreeCellRendererextends DefaultTreeCellRenderer

{

public Component getTreeCellRendererComponent(JTree tree, Object value,boolean sel,boolean expanded,boolean leaf,int row,boolean hasFocus)

{

JLabel label=(JLabel)super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);

label.setForeground(Color.GREEN);

label.setBackground(Color.RED);

setOpaque(false);

return label;

}

}

The tree nodes are not transparent. The foreground has become green, but the background is still white after invoking label.setBackground(Color.RED). It seems JTree has constant white background.

Anyone can help? Thanks in advance.

Ling

[2841 byte] By [theGreatUncertaintya] at [2007-11-27 2:44:05]
# 1

is this what you mean?

import java.awt.*;

import javax.swing.*;

import javax.swing.tree.*;

class Testing

{

public void buildGUI()

{

JPanel p = new JPanel(new GridLayout(1,1));

p.setBackground(Color.YELLOW);

JTree tree = new JTree();

JScrollPane sp = new JScrollPane(tree);

tree.setOpaque(false);

sp.setOpaque(false);

sp.getViewport().setOpaque(false);

tree.setCellRenderer(new DefaultTreeCellRenderer(){

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

this.setBackgroundSelectionColor(null);

this.setBorderSelectionColor(null);

this.setBackgroundNonSelectionColor(new Color(0,0,0,0));

return this;

}

});

JFrame f = new JFrame();

p.add(sp);

f.getContentPane().add(p);

f.setSize(200,200);

f.setLocationRelativeTo(null);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

}

public static void main(String[] args)

{

SwingUtilities.invokeLater(new Runnable(){

public void run(){

new Testing().buildGUI();

}

});

}

}

Michael_Dunna at 2007-7-12 3:10:22 > top of Java-index,Desktop,Core GUI APIs...
# 2
Thank you, Michael. This is exactly what I want.
theGreatUncertaintya at 2007-7-12 3:10:22 > top of Java-index,Desktop,Core GUI APIs...