JTree DnD Problem - public void drop(DropTargetDropEvent e)
This method won't executed, can someone give me some ideas what the problem could be.
After the following (simplified) method is called nothing happens.
public void dragOver(DropTargetDragEvent e)
e.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE );
How usually the void drop(DropTargetDropEvent e) method gets executetd ?
thanks for answers...
Ensure that you have initialised a DropTarget
and implemented the DropTargetListener
Similar Messages
-
Public void drop(DropTargetDropEvent e)
This method won't executed, can someone give me some ideas what the problem could be or when normaly this method gets called ?
After the following (simplified) method is called nothing happens.
public void dragOver(DropTargetDragEvent e)
e.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE );
How usually the void drop(DropTargetDropEvent e) method gets executetd ?
thanks for answers...Ensure that you have initialised a DropTarget
and implemented the DropTargetListener -
JTree DnD, disable clipboard
We have a JTree which contains custom nodes. We have enabled inter-tree Drag and Drop on the tree (Java 6 only. For java 5, we disable it), which works wonderfully, although in the example that you see below, it's only partially enabled. These nodes contain references to data (in the example, this data is represented via the Death class).
The problem, though, is that the clipboard appears to be enabled on this tree. In our case, it does not make sense to allow the clipboard, and in fact hinders the usefulness of our tree, because the shortcut keys (in particular, Shift-Delete) throw exceptions about the data not being serializable. We have plans to map Shift-Delete to something else, and would like to disable the clipboard, so that any other shortcuts also do not interfere with the tree's functioning.
So basically our question is "How do we disable the clipboard on our JTree?"
The code below is an example that demonstrates the problem. Our project is very large, so of course I'm not going to include the full thing, but this should be enough to give you an idea of the general layout of our tree, as well as the problem. When you run it, you will see a very basic tree with a node selected. You then press Shift-Delete and you will get a NotSerializableException because it's trying to serialize the node to the clipboard.
Notice, I have only tested this on Windows. It is most likely OS dependent and Look and Feel dependent due to the shortcut keys.
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.TransferHandler;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
public class ResNode extends DefaultMutableTreeNode implements Transferable
private static final long serialVersionUID = 1L;
private static final DataFlavor NODE_FLAVOR = new DataFlavor(ResNode.class,"Node");
private static final DataFlavor[] flavors = { NODE_FLAVOR };
public Death death; //used in another module
public ResNode(String name)
super(name);
death = new Death();
//Truncated for the purposes of this example
public class Death
public DataFlavor[] getTransferDataFlavors()
return flavors;
public boolean isDataFlavorSupported(DataFlavor flavor)
return flavor == NODE_FLAVOR;
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException
if (flavor != NODE_FLAVOR) throw new UnsupportedFlavorException(flavor);
return this;
public static void main(String[] args)
ResNode root = new ResNode("Root");
ResNode node = new ResNode("Node");
root.add(node);
JTree tree = new JTree(root);
tree.setSelectionPath(new TreePath(node.getPath()));
tree.setTransferHandler(new TransferHandler()
private static final long serialVersionUID = 1L;
protected Transferable createTransferable(JComponent c)
return (ResNode) ((JTree) c).getLastSelectedPathComponent();
public int getSourceActions(JComponent c)
return MOVE;
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(tree);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}We have a JTree which contains custom nodes. We have enabled inter-tree Drag and Drop on the tree (Java 6 only. For java 5, we disable it), which works wonderfully, although in the example that you see below, it's only partially enabled. These nodes contain references to data (in the example, this data is represented via the Death class).
The problem, though, is that the clipboard appears to be enabled on this tree. In our case, it does not make sense to allow the clipboard, and in fact hinders the usefulness of our tree, because the shortcut keys (in particular, Shift-Delete) throw exceptions about the data not being serializable. We have plans to map Shift-Delete to something else, and would like to disable the clipboard, so that any other shortcuts also do not interfere with the tree's functioning.
So basically our question is "How do we disable the clipboard on our JTree?"
The code below is an example that demonstrates the problem. Our project is very large, so of course I'm not going to include the full thing, but this should be enough to give you an idea of the general layout of our tree, as well as the problem. When you run it, you will see a very basic tree with a node selected. You then press Shift-Delete and you will get a NotSerializableException because it's trying to serialize the node to the clipboard.
Notice, I have only tested this on Windows. It is most likely OS dependent and Look and Feel dependent due to the shortcut keys.
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.TransferHandler;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
public class ResNode extends DefaultMutableTreeNode implements Transferable
private static final long serialVersionUID = 1L;
private static final DataFlavor NODE_FLAVOR = new DataFlavor(ResNode.class,"Node");
private static final DataFlavor[] flavors = { NODE_FLAVOR };
public Death death; //used in another module
public ResNode(String name)
super(name);
death = new Death();
//Truncated for the purposes of this example
public class Death
public DataFlavor[] getTransferDataFlavors()
return flavors;
public boolean isDataFlavorSupported(DataFlavor flavor)
return flavor == NODE_FLAVOR;
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException
if (flavor != NODE_FLAVOR) throw new UnsupportedFlavorException(flavor);
return this;
public static void main(String[] args)
ResNode root = new ResNode("Root");
ResNode node = new ResNode("Node");
root.add(node);
JTree tree = new JTree(root);
tree.setSelectionPath(new TreePath(node.getPath()));
tree.setTransferHandler(new TransferHandler()
private static final long serialVersionUID = 1L;
protected Transferable createTransferable(JComponent c)
return (ResNode) ((JTree) c).getLastSelectedPathComponent();
public int getSourceActions(JComponent c)
return MOVE;
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(tree);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} -
JTree TransferHandler problems (SSCE inside)
Hi JAvaers.
Appreciate the help as always, hopefully one of you will pinpoint the demon. I'd have thought that I could build these gizmos eyes closed by now -- except for this one! I'm examining code against those that work, and I can't play the find-the-mistakes game successfully at all. Here's an SSCE that reproduces the problem:
Expected Behavior:
When I drag a node onto another node, it is simply deleted from its original parent.
Actual Behavior:
No deletion takes place.
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.io.*;
* Dragging and dropping chocolate milk onto default category should remove
* the node from its parent, but it doesn't. *puzzle*
public class Test extends JFrame{
private static final long serialVersionUID = 1L;
private static Category root;
static{
root = new Category( "root category" );
Category milk = new Category( "milk" );
Category cmilk = new Category( "chocolate milk" );
Category choco = new Category( "choco" );
milk.add( cmilk );
root.add( milk );
root.add( choco );
public static void main( String args[]) throws Exception {
JFrame f = new JFrame();
f.setSize( 400, 400 );
f.getContentPane().add( new JScrollPane( new TestTree() ) );
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
f.setVisible( true );
* Our tree
private static final class TestTree extends JTree {
private static final long serialVersionUID = 1L;
private DefaultTreeModel model;
private TreePath selectedPath;
private Category originalTransferable;
public TestTree(){
model = new DefaultTreeModel( root );
setModel( model );
setDragEnabled( true );
setTransferHandler( new TreeNodeTransferHandler() );
setDropMode( DropMode.ON_OR_INSERT );
addTreeSelectionListener( new TreeSelectionListener() {
public void valueChanged( TreeSelectionEvent e ){
TreePath path = e.getNewLeadSelectionPath();
if( path != null ){
selectedPath = path;
private class TreeNodeTransferHandler extends TransferHandler {
private static final long serialVersionUID = 1L;
public boolean importData( TransferSupport info ) {
if( !canImport(info) )
return false;
try{
// fetch the drop location
JTree.DropLocation dl = (JTree.DropLocation)info.getDropLocation();
TreePath path = dl.getPath();
Category dragged = (Category)info.getTransferable().getTransferData( Category.categoryFlavor );
Category target = (Category)path.getLastPathComponent();
System.out.println(
" --> Original transferable hashcode : " +
originalTransferable.hashCode() +
"\n --> Actual transferable hashcode : " +
((Category)info.getTransferable().getTransferData( Category.categoryFlavor )).hashCode()
System.out.println( "droppped " + dragged + " onto " + target );
// doesn't work
((Category)dragged.getParent()).removeSubcategory( dragged, model );
// -- or --
// works
//((Category)originalTransferable.getParent()).removeSubcategory( originalTransferable, model );
return true;
catch( Exception x ){
x.printStackTrace();
return false;
public int getSourceActions( JComponent c ){
return TransferHandler.MOVE;
@Override
protected Transferable createTransferable( JComponent c ){
if( c.equals( TestTree.this ) ){
if( selectedPath != null && !((Category)selectedPath.getLastPathComponent()).isRoot() ){
originalTransferable = (Category)selectedPath.getLastPathComponent();
return originalTransferable;
return null;
public boolean canImport( TransferSupport info ){
if( !info.isDrop() )
return false;
if( !info.isDataFlavorSupported( Category.categoryFlavor ) )
return false;
JTree.DropLocation dl = (JTree.DropLocation)info.getDropLocation();
if( dl == null || dl.getPath() == null )
return false;
Object transferdata = null;
try{
transferdata = info.getTransferable().getTransferData( Category.categoryFlavor );
catch( Exception e ){
e.printStackTrace();
// can't drop a null node, nor can a node be dropped onto itself
return dl.getPath().getLastPathComponent() != null &&
dl.getPath().getLastPathComponent() != transferdata;
* Dummy node object
private static final class Category extends DefaultMutableTreeNode implements Transferable{
private static final long serialVersionUID = 1L;
public static final DataFlavor categoryFlavor = new DataFlavor( Category.class, "Category" );
public static final DataFlavor[] transferDataFlavors = new DataFlavor[]{ categoryFlavor };
private String title;
public Category( String t ){
title = t;
@Override
public String toString() {
return title;
@Override
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if( flavor.equals( categoryFlavor ) )
return this;
return null;
@Override
public DataFlavor[] getTransferDataFlavors() {
return transferDataFlavors;
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals( categoryFlavor );
* Remove a child category from this category
* @param n
public void removeSubcategory( final Category n, final DefaultTreeModel model ){
int[] childIndex = new int[1];
Object[] removedArray = new Object[1];
childIndex[0] = getIndex( n );
removedArray[0] = n;
remove( n );
model.nodesWereRemoved( this, childIndex, removedArray );
}Thanks again!
AlexAs other detail, if we resort to using the user objects inside of the Trasferables to transmit the categories themselves, it appears that the object integrity is maintained.
so either:
1 - Transferables are not guaranteed to be persistent in memory space
2 - There's a bug here that is causing some kind of improper cloning of the transferables themselves, that is otherwise preserving their user objects.
I'd call #2 a gotcha. I'll try bugging this at Sun to see if they'll fix it. -
Please help me ..
i have write a code ..which is when the user clicks the button...
a jtree table will come and the values inside the jtree will be filled by the contents of the selected items in the form...
but my problem is jtree only is comming
i created the object class ... but ...
the initialisation is not happening...
plz check the code below .. this is my class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class Reservation extends JFrame implements ItemListener,ActionListener{
JComboBox fromCity = null;
JComboBox toCity = null;
JComboBox dDay = null;
JComboBox dMonth = null;
JComboBox dYear = null;
JComboBox rDay = null;
JComboBox rMonth = null;
JComboBox rYear = null;
JComboBox adult = null;
JComboBox Cabin = null;
JFrame table;
public Reservation()
setSize(600,400);
JPanel p = new JPanel();
//getContentPane().setLayout(new BorderLayout());
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
p.setLayout(gbl);
String []cities = {"New York","Chicago","Miami","Pittsburgh","Memphis","New Orleans"};
String [] days={"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","27","28","29","30","31"};
String [] months = {"January","Feburary","March","April","May","June","July","August","September","October","November","December"};
String [] year = {"2006","2007"};
String [] adt = {"1","2","3","4"};
String [] cab = {"Buisness","Economy"};
fromCity = new JComboBox(cities);
fromCity.setSelectedIndex(0);
toCity = new JComboBox(cities);
toCity.setSelectedIndex(0);
dDay = new JComboBox(days);
dMonth = new JComboBox(months);
dYear = new JComboBox(year);
rDay = new JComboBox(days);
rMonth = new JComboBox(months);
rYear = new JComboBox(year);
adult = new JComboBox(adt);
Cabin = new JComboBox(cab);
JLabel frmCity = new JLabel("From");
frmCity.setLabelFor(fromCity);
JLabel tCity = new JLabel("To");
tCity.setLabelFor(tCity);
JLabel dDate = new JLabel("Departure Date");
dDate.setLabelFor(dDate);
JLabel rDate = new JLabel("Return Date");
rDate.setLabelFor(rDate);
JLabel Psg = new JLabel("Pasengers");
Psg.setLabelFor(Psg);
JLabel Adults = new JLabel("Adults");
Adults.setLabelFor(Adults);
JLabel cabin = new JLabel("Cabin");
cabin.setLabelFor(cabin);
JLabel search = new JLabel("Search By");
search.setLabelFor(search);
JRadioButton ROneWay = new JRadioButton("One Way");
JRadioButton RRoundTrip = new JRadioButton("Round Trip");
JButton searchbutton = new JButton("Date");
ButtonGroup group = new ButtonGroup();
group.add(ROneWay);
group.add(RRoundTrip);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(0,30,0,0);
p.add(frmCity,gbc);
gbc.gridx =1;
gbc.gridy = 0;
gbc.insets = new Insets(0,30,0,0);
p.add(fromCity,gbc);
gbc.gridx =0;
gbc.gridy = 1;
gbc.insets = new Insets(0,30,0,0);
p.add(tCity,gbc);
gbc.gridx =1;
gbc.gridy = 1;
gbc.insets = new Insets(10,30,0,0);
p.add(toCity,gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.insets = new Insets(10,50,0,0);
p.add(ROneWay,gbc);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.insets = new Insets(10,30,0,0);
p.add(RRoundTrip,gbc);
gbc.gridx = 1;
gbc.gridy = 3;
gbc.insets = new Insets(0,0,0,0);
p.add(dDate,gbc);
gbc.gridx = 0;
gbc.gridy = 4;
p.add(dDay,gbc);
gbc.gridx = 1;
gbc.gridy = 4;
p.add(dMonth,gbc);
gbc.gridx = 2;
gbc.gridy = 4;
p.add(dYear,gbc);
gbc.gridx = 1;
gbc.gridy = 5;
gbc.insets = new Insets(0,0,0,0);
p.add(rDate,gbc);
gbc.gridx = 0;
gbc.gridy = 6;
p.add(rDay,gbc);
gbc.gridx = 1;
gbc.gridy = 6;
p.add(rMonth,gbc);
gbc.gridx = 2;
gbc.gridy = 6;
p.add(rYear,gbc);
gbc.gridx = 1;
gbc.gridy = 7;
p.add(Psg,gbc);
gbc.gridx = 0;
gbc.gridy = 8;
p.add(Adults,gbc);
gbc.gridx = 1;
gbc.gridy = 8;
p.add(adult,gbc);
gbc.gridx = 0;
gbc.gridy = 9;
p.add(cabin,gbc);
gbc.gridx = 1;
gbc.gridy = 9;
gbc.insets = new Insets(10,0,0,0);
p.add(Cabin,gbc);
gbc.gridx = 0;
gbc.gridy = 10;
p.add(search,gbc);
gbc.gridx = 1;
gbc.gridy = 10;
gbc.insets = new Insets(10,0,0,0);
p.add(searchbutton,gbc);
getContentPane().add(p);
fromCity.addItemListener(this);
toCity.addItemListener(this);
dDay.addItemListener( this);
dMonth.addItemListener( this);
dYear.addItemListener(this);
adult.addItemListener(this);
Cabin.addItemListener(this);
searchbutton.addActionListener(this);
//Jtable form
table = new JFrame();
Container container;
container = table.getContentPane();
JPanel jpanel = new JPanel(new GridLayout(2,1));
container.setLayout(new GridLayout(2,1));
JLabel l1 = new JLabel("Departure Journey");
l1.setLabelFor(l1);
container.add(l1);
final String[] colHeads = {"","Flightno","Date","Departure Time","Arrival Time","Flight","Duration","Fare"};
final Object[ ][ ] data = new Object[10][10];
JTable table = new JTable(data,colHeads);
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(table,v,h);
container.add(jsp,BorderLayout.CENTER);
String ffcity,ttcity,dday,dmon,dyear,adt,cab;
public void itemStateChanged(ItemEvent e)
ffcity = (String)fromCity.getSelectedItem();
ttcity = (String)toCity.getSelectedItem();
dday = (String)dDay.getSelectedItem();
dmon = (String)dMonth.getSelectedItem();
dyear = (String)dYear.getSelectedItem();
adt = (String)adult.getSelectedItem();
cab = (String)Cabin.getSelectedItem();
public void actionPerformed(ActionEvent ae)
if(ae.getActionCommand() == "Date")
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:ds","sa", "");
PreparedStatement stmt = con.prepareStatement("select ifno,vdtime,vatime,vdate1,vdate2,vdate3,efare from airways where fcity = ? and tcity = ? and vdate1 = ? and vdate2 = ? and vdate3 = ?");
stmt.setString(1,ffcity);
stmt.setString(2,ttcity);
stmt.setString(3,dday);
stmt.setString(4,dmon);
stmt.setString(5,dyear);
ResultSet d = stmt.executeQuery();
/* int count=0;
while(d.next())
{count++;
int i = 0;*/
while(d.next())
/*for(int j =1;j<=7;j++)
data[i][j] = rs.getString(j);
System.out.println(" " + data[i][j]);
}i++;*/
System.out.println(d.getInt(1));
System.out.println(d.getDouble(2));
catch(Exception ex)
System.out.println("Error occurred");
System.out.println("Error:"+ex);
table.setVisible(true);
table.setSize(300,200);
private static void createAndShowGUI()
JFrame.setDefaultLookAndFeelDecorated(true);
Reservation r=new Reservation();
JFrame frame = new JFrame("Reservation Form");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//r.pack();
r.setVisible(true);
public static void main(String[] args)
SwingUtilities.invokeLater(new Runnable(){
public void run()
createAndShowGUI();
in this object creation is not happening
when i run this code ...
only jtree is comming..
how can i make it the values of seceted items to come in table
i commented the parts that having error..
when u uncomment it u will get the problem of this codeplease anyone
-
Hello --
I've searched this subject ad nauseum on these forums and the rest of the web, and I'm still coming up blank.
Basically, I have a file structure JTree. To do a "refresh" view, I basically kill the original object, and rebuild it again -- while first storing the last TreePath the user was on.
Since this tree is built dynamically, placeholders are used to tell if the parent node has any children. From there, it looks up its children.
During the refresh, I fire the tree.expandPath(path), and in my expansion listener, it should take care of the rest.
Well, it seems like all the steps are going correctly, due to the debug output I'm getting, but I can't get the tree to scroll to the path. Here's the reload part:
public void refreshTree(TreePath path){
TP tp = null;
Object [] obj = path.getPath();
for (int i = 2; i <= obj.length; i++){
tp = new TP(obj, i);
tree.expandPath(tp.getTP());
//I've tried these in the for loop to no avail
// tree.setSelectionPath(tp.getTP());
// tree.scrollPathToVisible(tp.getTP());
//this should be the last and final TreePath object
tree.expandPath(tp.getTP());
//tree.getSelectionModel().setSelectionPath(tp.getTP());
tree.setSelectionPath(tp.getTP());
tree.scrollPathToVisible(tp.getTP());
//this class exists so I can build the treepath one
//leaf at a time
class TP extends TreePath{
public TP(Object[] obj, int length){
super(obj, length);
public TreePath getTP(){
return this;
}I've tried rebuild and all, and it seems like everything is doing what it's supposed to except drawing it right. Here's the code for the expansion:
class selectionListener implements TreeExpansionListener{
public void treeExpanded(TreeExpansionEvent evt){
DefaultMutableTreeNode node = getTreeNode(evt.getPath());
TreeNode firstBorn = node.getFirstChild();
if (firstBorn.toString().equals(PLACEHOLDER)){
System.out.println("made it"); //debug
populateTree(evt.getPath()); //this gets the new stuff
public void treeCollapsed(TreeExpansionEvent evt){}
}So, again, it seems like everything is firing the way it should, it's just not redrawing the tree to the current path.
I'm on Java 1.4[02], Windows 2K, and JTree is set to SINGLE selection mode. If you need any additional information, please let me know.
Thank you very much for your time.
-SteveIt seems that the tree is firing a node change itself, because I have code executing in the
public void treeExpanded(TreeExpansionEvent evt)
function.
I also put a bit of debug code in... I have
System.out.println("Is collapsed? " + tree.isCollapsed(tp.getTP()));
Inside my for loop... the output is false everytime.
So it seems that everything exists, it's just not repainting the gui for some reason or other. I'm not spinning off seperate threads to do anything, so I'd assume it's not a thread problem.
Any ideas? This is really getting frustrating, for something I thought would be so simple. -
I have listed below a shor example.
What I need is a method to do each cell to be as wide as the tree is (see the red border line), even if I resize the window. And ofcourse, the tree should keep a minimum width so every cell is fully shown.
I'll be waiting for your answers. Thanks.
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
public class TreeExample extends JFrame {
public TreeExample() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
getContentPane().add(new JScrollPane(new SomeTree()));
pack();
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TreeExample().setVisible(true);
class SomeTree extends JTree {
public SomeTree() {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
String str = "***";
for (int i = 0; i < 10; i++) {
root.add(new DefaultMutableTreeNode(str));
str += "***";
setModel(new DefaultTreeModel(root));
setCellRenderer(new SomeCellRenderer());
setBorder(BorderFactory.createLineBorder(Color.RED));
class SomeCellRenderer extends JLabel implements TreeCellRenderer {
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded,
boolean leaf, int row,
boolean hasFocus) {
setOpaque(true);
setText(value.toString());
setBackground(Color.LIGHT_GRAY);
return this;
}The only problem i can figure is maybe the layout. Flowlayout is squeezing the size of the buttons so that they can appear in the little area that they do get. If you use borderlayout instead of the flowlayout, it may solve your problem. If that also doesn't work then set the minimum sizes of the labels.
-
JTree accessibility problem?
I've got an application which uses a JTree to display the data and cannot get a screen reader to speak any of the nodes as I navigate to them with the mouse or by the keyboard. I've used javaferret and indeed, it shows that no accessible name or description is getting set as I navigate around. Is this a problem with the JTree itself or a problem with the access bridge? Is there any way for me to diagnose this problem?
I'm using the default cell renderer. I've verified that I can reproduce the problem with simple examples from the tutorials. Here's a bit of code that I'm currently using to reproduce. It turns out that JAWS always reads the node you left rather than the node you were entered....apparently the active descendent isn't being updated properly...
import javax.accessibility.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.tree.*;
* Tree View!
* @author Jeff Dinkins
public class TreeTest extends JPanel implements PropertyChangeListener
public static void main(String[] args)
TreeTest p = new TreeTest();
JFrame f = new JFrame("Test JTree Accessibilty");
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(BorderLayout.NORTH, p);
f.pack();
f.setVisible(true);
public TreeTest() {
setLayout(new BorderLayout());
DefaultMutableTreeNode top = new DefaultMutableTreeNode("Music");
DefaultMutableTreeNode catagory;
DefaultMutableTreeNode composer;
DefaultMutableTreeNode style;
DefaultMutableTreeNode album;
// Classical
catagory = new DefaultMutableTreeNode("Classical");
top.add(catagory);
// Beethoven
catagory.add(composer = new DefaultMutableTreeNode("Beethoven"));
// Brahms
catagory.add(composer = new DefaultMutableTreeNode("Brahms"));
// Mozart
catagory.add(composer = new DefaultMutableTreeNode("Mozart"));
catagory.add(composer = new DefaultMutableTreeNode("Schubert"));
// Jazz
top.add(catagory = new DefaultMutableTreeNode("Jazz"));
// Ayler
catagory.add(composer = new DefaultMutableTreeNode("Albert Ayler"));
// Chet Baker
catagory.add(composer = new DefaultMutableTreeNode("Chet Baker"));
// Coltran
catagory.add(composer = new DefaultMutableTreeNode("John Coltrane"));
// Miles
catagory.add(composer = new DefaultMutableTreeNode("Miles Davis"));
// Rock
top.add(catagory = new DefaultMutableTreeNode("Rock"));
// The Beatles
catagory.add(composer = new DefaultMutableTreeNode("The Beatles"));
// Crowded House
catagory.add(composer = new DefaultMutableTreeNode("Crowded House"));
// Harvin Garvel
catagory.add(composer = new DefaultMutableTreeNode("Harvin Garvel"));
// The Steve Miller Band
catagory.add(composer = new DefaultMutableTreeNode("Steve Miller Band"));
JTree tree = new JTree(top);
add(new JScrollPane(tree), BorderLayout.CENTER);
tree.getAccessibleContext().addPropertyChangeListener(this);
public void propertyChange(PropertyChangeEvent e)
String name = e.getPropertyName();
if (AccessibleContext.ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY.equals(name))
System.out.println("active descendant changed");
AccessibleContext oldAC = (AccessibleContext)e.getOldValue();
String old = (oldAC == null) ? null : oldAC.getAccessibleName();
System.out.println("old descendant is " + old);
AccessibleContext ac = (AccessibleContext)e.getNewValue();
System.out.println("new descendant is " + ac.getAccessibleName()); -
JTree corruption problem when expanding paths (sometimes)
Sometimes when adding nodes or expanding paths in my JTree I get a really weird corruption. Here's screenshots of the problem:
http://linuxhelp.homeunix.com/screen1.png
http://linuxhelp.homeunix.com/screen2.png
How can I stop this from happening?
AdamHi!
I also had this problem but it works fine using SwingUtilities.invokeLater
/Malin
private class ExpandListener implements TreeWillExpandListener {
TreePath path = null;
public void treeWillCollapse(TreeExpansionEvent e) {
public void treeWillExpand(TreeExpansionEvent e) {
path = e.getPath();
collapseAll();
if (path != null) {
// If we don't scroll later it doesn't work correctly in some cases
SwingUtilities.invokeLater(new Runnable() {
public void run() {
scrollPathToVisible(path);
* Collapses the tree.
public void collapseAll() {
for (int i = root.getChildCount(); i > 0; i--) {
collapseRow(i); -
I use a JTree for displaying a custom TreeModel based on a DOM document. I have a problem with refreshing the tree: the tree refreshes itself correctly when it has focus, and does nothing when it has not (at least it seems to be related to focus), even though TreeModelEvents are fired. I know the problem originates from the custom TreeModel (others work fine), but I can't find what's wrong. I compared it to the DefaultTreeModel source and found nothing interesting.
In addition to that, the tree is displayed without its vertical connecting lines (but someone told me its a symptom of bad refreshing).
Anyone has an idea? Thanks in advance.
SimonI faced the same problem. Try adding a TreeModelListener and updateUI in it . . .
yourTreeModel.addTreeModelListener(new TreeModelListener() {
public void treeNodesChanged(TreeModelEvent e) {}
public void treeNodesInserted(TreeModelEvent e) {
yourTree.updateUI();
public void treeNodesRemoved(TreeModelEvent e) {
yourTree.updateUI();
public void treeStructureChanged(TreeModelEvent e) {}
}); -
JCheckBox as nodes in JTree having problems with custom renderer and editor
Ok, let me give some background. I have an XML document that I am parsing and reading in as a JTree. Works fine.
Next, I have overwritten the DefaultTreeCellEditor to return a JCheckBox and in this implementation of the getTreeCellEditorComponent(), I actually tell the node that he is selected. Works great.
Next, I have overwritten the DefaultTreeCellRenderer to return a JCheckBox and in the implementation of the getTreeCellEditorComponenet, I actually check to see if the Node is selected in the tree based upon the isSelected state of the actual Tree Node set in the tree cell editor, and if so, I set the JCheckBox to selected(true).Works Great.
Now, here is the issue. If a node in the tree is selected that contains children, then I want all of the children of that node to also be selected. However, when I select a node with children only the selected node is changed, and then a few moments later, the system repaints the entire tree and ALL nodes int the tree are set to a selected state. Strange? Yes. Any ideas?? WONDERFUL!! :)
Here is the TreeCellEditor code:
public Component getTreeCellEditorComponent(JTree tree,
Object value,
boolean isSelected,
boolean expanded,
boolean leaf,
int row)
elementCheckBox_ = new JCheckBox();
Component result = null;
System.out.println("isSelected? Editor = " + isSelected);
TreePath newPath = tree.getPathForRow(row);
System.out.println("value = " + value.getClass().toString());
if(value instanceof IMarketTreeNodeElement)
if(isSelected)
if(((IMarketTreeNodeElement)value).isSelected())
((IMarketTreeNodeElement)value).setSelected(false);
else
((IMarketTreeNodeElement)value).setSelected(true);
elementCheckBox_.setSelected(isSelected);
return elementCheckBox_;
Here is the TreeCellRenderer code:
public Component getTreeCellRendererComponent(JTree tree,
Object value,
boolean selected,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus)
Color colSelBorderCol = UIManager.getColor
("Tree.selectionBorderColor");
selBorder_ = BorderFactory.createLineBorder(colSelBorderCol, 1);
normBorder_ = BorderFactory.createEmptyBorder(1,1,1,1);
elementCheckBox_.setText(value.toString());
if(selected)
elementCheckBox_.setSelected(selected);
elementCheckBox_.setForeground(Color.YELLOW);
elementCheckBox_.setBackground(Color.RED);
else
elementCheckBox_.setForeground(tree.getForeground());
elementCheckBox_.setBackground(tree.getBackground());
if (hasFocus)
elementCheckBox_.setBorder(selBorder_);
else
elementCheckBox_.setBorder(normBorder_);
return elementCheckBox_;
Here is the Node Code setting all child nodes to selected:
public void setSelected(boolean selected)
isSelected_ = selected;
if(isSelected_)
if((this.getTagName() == "MARKET") ||
(this.getTagName() == "TIER") &&
(this.getChildCount() != 0))
selectChildren(true);
else
if((this.getTagName() == "MARKET") ||
(this.getTagName() == "TIER") &&
(this.getChildCount() != 0))
selectChildren(false);
public boolean isSelected()
return isSelected_;
public void selectChildren(boolean selected)
int children = getChildCount();
for(int i = 0; i < children; i++)
IMarketTreeNodeElement elem = (IMarketTreeNodeElement)
this.getChildNodes().item(i);
isSelected_ = selected;
Thanks for any help! :-)I tried to run your sample code and it won't compile. The header files:
#include
#include
#include
#include
#include
do not exist on my install of MeasurementStudio. I am a bit suspicous that I don't have the latest and greatest (loading the dialong resouce gave version warnings). Here is one of my header file headers:
//==============================================================================
// Title : NiAxes3d.h
// Copyright : National Instruments 1999. All Rights Reserved.
// Purpose : Defines the CNiAxes3D class.
//==============================================================================
I
looked on your updates site and don't really see an update that applies to ComponentWorks or MeasurementStudio. My version per the MAX program for 3DControls is 3.5.549.
Do I need a newer version? What do I have to do to get the updated version? What does it cost?
Chuck -
JTree sorting problem, how to sort
here is my code:
DefaultMutableTreeNode root=new DefaultMutableTreeNode("root");
DefaultMutableTreeNode childone=new DefaultMutableTreeNode("id");
DefaultMutableTreeNode person1=new DefaultMutableTreeNode("david");
DefaultMutableTreeNode p11=new DefaultMutableTreeNode("java programming");
DefaultMutableTreeNode p12=new DefaultMutableTreeNode("maths");
DefaultMutableTreeNode p13=new DefaultMutableTreeNode("c programming");
person1.add(p11);
person1.add(p12);
person1.add(p13);
childone.add(person1);
DefaultMutableTreeNode person3=new DefaultMutableTreeNode("ann");
DefaultMutableTreeNode p31=new DefaultMutableTreeNode("georgian");
DefaultMutableTreeNode p32=new DefaultMutableTreeNode("english");
DefaultMutableTreeNode p33=new DefaultMutableTreeNode("russian");
person3.add(p31);
person3.add(p32);
person3.add(p33);
childone.add(person3);
DefaultMutableTreeNode person2=new DefaultMutableTreeNode("merab");
DefaultMutableTreeNode p21=new DefaultMutableTreeNode("veterinar");
DefaultMutableTreeNode p22=new DefaultMutableTreeNode("building");
person2.add(p21);
person2.add(p22);
childone.add(person2);
DefaultMutableTreeNode person4=new DefaultMutableTreeNode("maia");
DefaultMutableTreeNode p41=new DefaultMutableTreeNode("medicine");
DefaultMutableTreeNode p42=new DefaultMutableTreeNode("pediatri");
DefaultMutableTreeNode p43=new DefaultMutableTreeNode("aaaa");
p41.add(p42);
p41.add(p43);
person4.add(p41);
childone.add(person4);
DefaultMutableTreeNode childtwo=new DefaultMutableTreeNode("fullname");
DefaultMutableTreeNode c1=new DefaultMutableTreeNode("merab");
DefaultMutableTreeNode c2=new DefaultMutableTreeNode("maia");
DefaultMutableTreeNode c3=new DefaultMutableTreeNode("ann");
DefaultMutableTreeNode c4=new DefaultMutableTreeNode("david");
childtwo.add(c1);
childtwo.add(c2);
childtwo.add(c3);
childtwo.add(c4);
DefaultMutableTreeNode childthree=new DefaultMutableTreeNode("email");
DefaultMutableTreeNode d1=new DefaultMutableTreeNode("[email protected]");
DefaultMutableTreeNode d2=new DefaultMutableTreeNode("[email protected]");
DefaultMutableTreeNode d3=new DefaultMutableTreeNode("[email protected]");
childthree.add(d1);
childthree.add(d2);
childthree.add(d3);
root.add(childthree);
root.add(childone);
root.add(childthree);
jTree1 = new JTree(root);
jScrollPane1.setViewportView(jTree1);
// DefaultTreeModel ddd=(DefaultTreeModel)jTree1.getModel();
Comparator<DefaultMutableTreeNode> comp=new Comparator<DefaultMutableTreeNode>() {
public int compare(DefaultMutableTreeNode o1,DefaultMutableTreeNode o2) {
return o1.toString().compareTo(o2.toString());
ArrayList<DefaultMutableTreeNode> arr=Collections.list(root.children());
Collections.sort(arr,comp);
root.removeAllChildren();
for(int i=0;i<arr.size();i++)
root.add(arr.get(i));now i want to sort all nodes and leafs that contains this tree , how should i do that? can anyone correct this code so that it sorts all data in this jtree?We may extend DefaultMutableTreeNode to implement Comparable
and override insert so that the relevant nodes are sorted after each insert:
* TreeSort.java
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
public class TreeSort extends JFrame {
private JTree jTree1;
private JScrollPane jScrollPane1;
public TreeSort() {
super("TreeSort");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(400,300);
setLocationRelativeTo(null);
MyNode root = new MyNode("root");
MyNode childone = new MyNode("id");
MyNode person1 = new MyNode("david");
MyNode p11 = new MyNode("java programming");
MyNode p12 = new MyNode("maths");
MyNode p13 = new MyNode("c programming");
person1.add(p11);
person1.add(p12);
person1.add(p13);
childone.add(person1);
MyNode person3 = new MyNode("ann");
MyNode p31 = new MyNode("georgian");
MyNode p32 = new MyNode("english");
MyNode p33 = new MyNode("russian");
person3.add(p31);
person3.add(p32);
person3.add(p33);
childone.add(person3);
MyNode person2 = new MyNode("merab");
MyNode p21 = new MyNode("veterinar");
MyNode p22 = new MyNode("building");
person2.add(p21);
person2.add(p22);
childone.add(person2);
MyNode person4 = new MyNode("maia");
MyNode p41 = new MyNode("medicine");
MyNode p42 = new MyNode("pediatri");
MyNode p43 = new MyNode("aaaa");
p41.add(p42);
p41.add(p43);
person4.add(p41);
childone.add(person4);
MyNode childtwo = new MyNode("fullname");
MyNode c1 = new MyNode("merab");
MyNode c2 = new MyNode("maia");
MyNode c3 = new MyNode("ann");
MyNode c4 = new MyNode("david");
childtwo.add(c1);
childtwo.add(c2);
childtwo.add(c3);
childtwo.add(c4);
MyNode childthree = new MyNode("email");
MyNode d1 = new MyNode("[email protected]");
MyNode d2 = new MyNode("[email protected]");
MyNode d3 = new MyNode("[email protected]");
childthree.add(d1);
childthree.add(d2);
childthree.add(d3);
root.add(childtwo);
root.add(childone);
root.add(childthree);
jTree1 = new JTree(root);
jScrollPane1 = new JScrollPane();
jScrollPane1.setViewportView(jTree1);
add(jScrollPane1);
public static void main(final String[] args) {
Runnable gui = new Runnable() {
public void run() {
new TreeSort().setVisible(true);
//GUI must start on EventDispatchThread:
SwingUtilities.invokeLater(gui);
class MyNode extends DefaultMutableTreeNode implements Comparable {
public MyNode(String name) {
super(name);
@Override
public void insert(final MutableTreeNode newChild, final int childIndex) {
super.insert(newChild, childIndex);
Collections.sort(this.children);
public int compareTo(final Object o) {
return this.toString().compareToIgnoreCase(o.toString());
}Edited by: Andre_Uhres on Nov 22, 2008 3:47 PM
There seems to be a small bug in your original code: childthree is added twice and childtwo isn't added at all. -
JTree refresh probleme help me please
a can't reload my JTree from my server
my Jtree code:
user.add("Zeus@mxf");
user.add("Neptune@toto");
user.add("Ulysse@mars");
root =new DefaultMutableTreeNode("users");
for(int i=1; i<user.size(); i++)
userNode = new DefaultMutableTreeNode
(user.elementAt(i) );
root.add(userNode);
renderer.setOpenIcon(OpenIcon);
renderer.setClosedIcon(ClosedIcon);
renderer.setLeafIcon(PrinterIcon);
tree=new JTree(root);
tree.setCellRenderer(renderer);
and if a have receive the write data i do my refresh methode:
refresh()
userNode = new DefaultMutableTreeNode(user.elementAt(0) );
root.add(userNode);
((DefaultTreeModel)tree.getModel()).reload();
tree.treeDidChange();
tree.setCellRenderer(renderer);
tree.setLargeModel(true);
tree.repaint();
tree.revalidate();
why it dose not work ?????Sorry I have not ready examples, try to implement a method this way:
String newUser = user.elementAt(0);
public void addNode(String newUser){
DefaultMutableTreeNode userNode = new DefaultMutableTreeNode(newUser);
root.add(userNode);
tree.getModel().nodeChanged((TreeNode)tree.getModel().getRoot());
tree.treeDidChange(); -
Let's say a tree has 3 children, and each children has a hierarchy of subtrees. Is there any way to just expand one children and its subtrees??
root
|_A
|_SUBTREE
|_B
|_SUBTREE
|_C
|_SUBTREE
If I do the following, it will expand the whole big tree.
JTree tree;
//etc...
1) /** Expand the tree */
for (int i=0; i<tree.getRowCount(); i++)
tree.expandRow(i);
If I do this, it own expands the first 6 children (including the subtrees of each children)
2) /** Expand the tree */
for (int i=0; i<6; i++)
tree.expandRow(i);
any ideas?? please help!!I think u mistook my point. Let's say a JTree has 3 children as follows:
and each child has its own tree hierarchy.
root
|_SUBTREE1
|_SUBTREE2
|_SUBTREE3
All I want is when the user click a particular tree node, the whole subtree will expand.
I tried the following, but it only expands the child of the tree node I selected.
public void treeExpanded(TreeExpansionEvent evt)
{ System.out.println("treeExpanded...");
TreePath path = evt.getPath();
int pathCount = path.getPathCount();
System.out.println(pathCount);
for (int i=0; i<pathCount; i++)
tree.expandPath(path);
Any ideas??? -
I have the following JTree:
[root] project
[node1] car
[node2 = child of node1] car_Info
[children of node2] color, length, engine, price, etc...(about 80 items)
I use polymorphism to implement this:
public interface NodeInfo {
public void select();
public class car implements NodeInfo {
// rest of car class
public void select() {
// car specific implementation
public class car_Info implements NodeInfo {
// rest of car_info
public void select() {
// car_info specific implementation
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
if (node == null) {
return;
NodeInfo nodeInfo = (NodeInfo) node.getUserObject();
nodeInfo.select(); // dynamic call to the actual runtime subtype of the NodeInfo object
How do i implement the leafs for my tree? (that is, color, length, etc....) And how can i put that into my valueChanged method?I have the following JTree:
[root] project
[node1] car
[node2 = child of node1] car_Info
[children of node2] color, length, engine, price,
etc...(about 80 items)
I use polymorphism to implement this:
public interface NodeInfo {
public void select();
public class car implements NodeInfo {
// rest of car class
public void select() {
// car specific implementation
public class car_Info implements NodeInfo {
// rest of car_info
public void select() {
// car_info specific implementation
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node =
e = (DefaultMutableTreeNode)
tree.getLastSelectedPathComponent();
if (node == null) {
return;
NodeInfo nodeInfo = (NodeInfo)
fo) node.getUserObject();
nodeInfo.select(); // dynamic call to the actual
ual runtime subtype of the NodeInfo object
How do i implement the leafs for my tree? (that is,
color, length, etc....) And how can i put that into
my valueChanged method?the valueChanged method exists only to allow the model to notify the view that it has changed, so that the view may change accordingly
I don't understand what you mean with your last sentence
Maybe you are looking for
-
Neo 4 Platinum - always problems! :((
Sorry for my bad english. After working a while on this mobo, I am unable to working in a stable way and the problems are very big to me and now I have only problems. Well, in order let me explain what happend: I have a Maxtor 80 GB SATAI connected o
-
MDM Custom Iview and Standard Iview Portal Eventing
Hi I'm trying to develop a custom iview which updates a Standard MDM Result Set iview: I found this documentation: http://help.sap.com/saphelp_mdm550/helpdata/en/45/c87cfd43e56f75e10000000a1553f6/frameset.htm https://www.sdn.sap.com/irj/scn/go/portal
-
Junit : How can I get the method name (say testMyAddress) that failed
My code is below TestSuite masterSuite = new TestSuite(testClass); TestResult result = new TestResult(); masterSuite.run(result); Enumeration errors = result.errors(); while (errors.hasMoreE
-
I have Adobe CC and I want to download Illustrator CS6?
I Use Adobe CC and i want to install and also want to download and use Illustrator CS6. I need help..
-
we had implemented bi apps at three sites. in addition to the prebuilt we have built customized schema at one of the customer site. now the other customer site is interested to have the exact thing in their application and they want this as a package