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!
Alex
As 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.
Similar Messages
-
Error 56 on iphone 6. problem is inside
my iphone 6 did not turn on after i drop it to the floor in my house. after that i got to the master and when he connected it to the itunes, itunes shows that the problem is inside. phone is not turning on. and we don't know what to do... in my country no any apple supporting centers. how can i switch on my phone?
how can i switch on my phone?
Well you dropped it and broke it, so you probably can't turn it on.
Contact Apple and arrange to get it repaired or replaced. -
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. -
Hi!
In my application I have a JTree component, wich has nodes and childs. When the application starts up I populate the JTree with some data retrieved from a database. But after that I need to change some data in the database wich is reloaded and this changes the text inside the nodes in the JTree. Then I call the repaint() method of the JTree update. The problem is when the updated string is bigger then the old string, part of the string is not visible i.e it shows "..." after the text.
Is there someone who knows this problem?
Thanks in advance.Hi dayanandabv ! Thanks for your reply ! I tried your suggestion, but it won't work! i tried validate() afler and before the repaint method.
Any other ideas?
I'm trying hard to fix this but with no results :( some help will be appreciated.
Thanks again. -
Problem using & inside string in a query
hi all, i have a problem with one of my query.
i try using an & inside a string in a query and sqlplus and toad prompt me to enter a value. it is reconizing it as input. this is my query
select department_name from dept where dept_name = 'S&R';
how can write this query without sqlplus/toad asking me to enter a value for :R
i tried to escape & by using 'S\&R' but nothing happen.In SQL*Plus you SET DEFINE OFF like this:
SQL> set define off
SQL> select 'S&R' from dual;
'S&
S&R(can't help you with Toad) -
JTree selection problem when using custom renderer and editor
Hello:
I created a JTree with custom renderer and editor.
The customization makes JCheckBox to be the component
responsible for editing and rendering.
The problem is that when I click on the node with the checkbox
the JTree selection model does not get updated.
Without customizations of the editor and renderer the MouseEvent would be fired and BasicTreeUI$MouseHandler.mousePressed() method would call
the selectPathForEvent() method which would be responsible for updating
the selection model. At the same time if I attach a mouse listener to the JTree (customized) I see the events when clicking on the nodes. It seems like the MouseEvent gets lost and somehow as a result of which the selection model does not get updated.
Am I missing something?
Thanks
AlexanderYou probably forgot to call super.getTreeCellRendererComponent(...) at the beginning of your getTreeCellRendererComponent(...) method in your custom renderer.
Or maybe in the getTreeCellEditorComponent(...) of the TreeCellEditor... -
JTree Repaint Problem .
I'm creating a dynamic JTree by querying th DB. The JTree has to reflect the changes if any.
But the problem is that although I'm getting all the correct nodes in the JTree, the tree display is not repainted if the window is maximized or focussed and the tree area is displayed grey. Other components like buttons etc are correctly visible.
If I click in the greyed area of the JTree then that particular node is visible and the rest nodes are hidden.
same problem comes when I have a JPopup for the nodes.. It leaves a greyed rectangle in place of the JPopup.
Any suggestions will be a great help.
- PraveenI tried the reload , revalidate and the repaint method of the Treemodel, but nothing changed... its all the same.I'd like to explain in full what am I doing.
I have some items in the DB which are shown in the JTree. When any Item is added to the DB I poll the DB
after an interval to check new entries or deleted entries, and this is to be updated to the JTree.
The additions and deletions are going on properly a/c to the DB the only problem being that , that if the window(JFrame) containing the JTree (JTree is contained in JScrollPane) is minimized or hidden, then only the JTree is greyed and not the other components such as the buttons.
Interestingly if I double click in the JTree area then the Jtree becomes visible properly. This happens after each update of the JTree.
Hope this description will give a better view.
Thanks for all your previous helpful hints. -
I have a problem trying to select a node of a JTree using JDK 1.3.1 and JDK 1.4 beta 3. I use a JTree with a DefaultTreeModel and DefaultMutableTreeNodes.
Before the tree became visible it has all the nodes loaded but not visible. Then I want to select a path of the tree using a node (DefaultMutableTreeNode) but I not able to do it.
The path isn't selected and isn't visible.
I use the following code:
jTree.setExpandsSelectedPaths(true)
jTree.setSelectionPath(new TreePath(node.getPath()));
//I've also tried with
jTree.expandPath(new TreePath(dmtn.getPath()));Thanks.Fair enough. I guess I need to do a bit more reading.
You have to create a new TreePath object because the
getPath() method of DefaultMutableTreeNode returns an
array of TreeNodes where as the setSelected method of
JTree requires a TreePath object.
Why are you creating a new path with the contents ofa
call to getPath?
wouldn't node.getPath() be what you want toexpend/set
visible/scroll to etc
try it without creating a new TreePath -
JTree scrollbar problem - can't scroll back to top when some nodes hidden
I have a problem which I cannot resolve: I have a JTree which has had 88 rows added to it, and which then has 15 or so rows set to be not visible; when I then scroll to the bottom of the pane I am unable to scroll all the way back to the top using either the scroll button at the top of the bar or the mouse scroll wheel although I can drag the knob to get to the top; using the button or wheel, the scrolling stops somewhat short of the top; via testing I've found that the AdjustmentEvent is not fired when it reaches that point. Anyone seen this before and/or know a way around it?
Thanks in advance,
MikeMikeAuerbach267 wrote:
It turns out that my problem was due to the fact that I am using my own TreeCellRenderer which makes invisible some nodes via user option but doesn't reload the tree; hence the confusion as to the scrollbar size. I now correctly reload after user option has changed rather than render nodes invisible and all is fine. Which reinforces Andrew's view in reply #1 that a 'vague waving about of hands' does not allow the forum members to help. -
I've got Java 1.4 dragging between tables and lists in my application. Every drag and drop is a move, so when I drop an item onto one list, it is removed from the source.
Everything works great until I try to drag and drop on the same list. Seems like Swing first does the importData, then the exportDone, but because everything is serialized through the JVM, there doesn't seem to be a way to tell the transfer handler that the source and the target are the same object. How exactly do I teach my TransferHandler class to not importData if the source and target are the same.
Right now I'm cheating and saving the source of the drag as a static variable in the application class, but that doesn't seem like it should be the right way to do things. Is the new DnD code just poorly implemented, or am I missing something?
Oh, and I've tried saving the source component in the transfer data, but I get some weird null pointer exception somewhere in the UI classes when I do that.
Here's my TransferHandler class:
import javax.swing.*;
import javax.swing.tree.TreePath;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.util.List;
import java.util.Vector;
import java.io.IOException;
* This handles the movement of CommentTextValues around the system. Combined
* with properly build CommonTextModel and TermModel table and tree models,
* this method makes the dragging and dropping of common text and terms in an
* application completely generic.
public class TermSelection extends TransferHandler implements Transferable {
// This looks a little weird, but it's because the TransferHandler is also the Transferable
private static final DataFlavor[] flavors = {
new DataFlavor(TermSelection.class, DataFlavor.javaJVMLocalObjectMimeType)
// The data to be moved
private List moving;
* All this handler does is move operations; copy may be supported later if
* the need arises.
public int getSourceActions(JComponent c) {
return MOVE;
* Indicate what we can import (TermSelection objects).
public boolean canImport(JComponent c, DataFlavor[] flavor) {
if (c instanceof JTree || c instanceof JTable || c instanceof JList) {
for (int idx = 0; idx < flavor.length; idx++) {
if (flavor[idx].equals(flavors[0])) {
return true;
return false;
* Create the transferable object to pass to the drop listener.
* @param component the component that we're dragging from
* @return a loaded (set <b>moving</b>) Transferable object
public Transferable createTransferable(JComponent component) {
if (component instanceof JTable) {
JTable table = (JTable) component;
if (table.getModel() instanceof CommonTextModel) {
CommonTextModel model = (CommonTextModel) table.getModel();
// Get the selected items and save them for transfer
int[] rows = table.getSelectedRows();
List terms = model.getCommonText();
moving = new Vector(rows.length);
for (int idx = 0; idx < rows.length; idx++) {
moving.add(terms.get(rows[idx]));
return this;
} else if (table.getModel() instanceof TermModel) {
TermModel model = (TermModel) table.getModel();
// Get the selected items and save them for transfer
int[] rows = table.getSelectedRows();
List terms = model.getTerms();
moving = new Vector(rows.length);
for (int idx = 0; idx < rows.length; idx++) {
moving.add(terms.get(rows[idx]));
return this;
} else if (component instanceof JTree) {
JTree tree = (JTree) component;
if (tree.getModel() instanceof TermModel) {
// TreePath path = tree.get
} else if (component instanceof JList) {
JList list = (JList) component;
if (list.getModel() instanceof TermModel) {
TermModel model = (TermModel) list.getModel();
// Get the selected items and save them for transfer
int[] rows = list.getSelectedIndices();
List terms = model.getTerms();
moving = new Vector(rows.length);
for (int idx = 0; idx < rows.length; idx++) {
moving.add(terms.get(rows[idx]));
return this;
return null;
* Import the data into components onto which they were dropped. Supports
* JTree and JTable components that have models implementing
* CommonTextModel and TermModel.
* @param c the componet we're dropping on
* @param t the data object (with the moved values)
* @return true, if the drop was successful
public boolean importData(JComponent c, Transferable t) {
List moved = getWrapped(t);
if (moved != null && t.isDataFlavorSupported(flavors[0])) {
// Drop it on a tree?
if (c instanceof JTree) {
// Drop it on a terms tree?
if (((JTree) c).getModel() instanceof TermModel) {
TermModel model = (TermModel) ((JTree) c).getModel();
model.addTerms(moved);
return true;
// Drop it on a common text tree?
// NOT YET IMPLEMENTED !!!
// Drop it on the stop table or unreferenced terms table?
} else if (c instanceof JTable) {
JTable table = (JTable) c;
if (table.getModel() instanceof CommonTextModel) {
CommonTextModel model = (CommonTextModel) table.getModel();
model.addCommonText(moved);
return true;
} else if (c instanceof JList) {
JList list = (JList) c;
if (list.getModel() instanceof TermModel) {
TermModel model = (TermModel) list.getModel();
model.addTerms(moved);
return true;
return false;
* All drags in Rosetta are "moves" as opposed to "copies." Remove the
* objects from their source.
protected void exportDone(JComponent source, Transferable data, int action) {
List moved = getWrapped(data);
if (moved != null) {
if (source instanceof JTable) {
JTable table = (JTable) source;
if (table.getModel() instanceof CommonTextModel) {
CommonTextModel model = (CommonTextModel) table.getModel();
model.removeText(moved);
} else if (source instanceof JList) {
JList list = (JList) source;
if (list.getModel() instanceof TermModel) {
TermModel model = (TermModel) list.getModel();
model.removeTerms(moved);
super.exportDone(source, data, action);
* Convert the transferable object to a wrapped object.
* @param data
* @return returns null if the transferable object is not a Wrapped
* object, or an exception was thrown
private static List getWrapped(Transferable data) {
try {
if (data.getTransferData(flavors[0]) instanceof List) {
return (List) data.getTransferData(flavors[0]);
} catch (UnsupportedFlavorException e) {
} catch (IOException e) {
return null;
public DataFlavor[] getTransferDataFlavors() {
return flavors;
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(flavors[0]);
* @param flavor ignored; we always return the list
* @return the list of CommonTextValue objects that we're dragging
* @throws UnsupportedFlavorException not thrown
* @throws IOException not thrown
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
return moving;
}You find an example here:
http://forum.java.sun.com/thread.jspa?threadID=646602 -
I created a JTree on top of a DefaultMutatableTreeNode by using the constructor JTree(TreeNode root)
I tried removing all leaf nodes of the model, using node.removeFromParent(). And unsurprisingly the UI is automatically updated.
After that, i reinsert new leaf nodes(they are new instances having new physical address) into the model, using parent.add(node). And unsurprisingly, the UI is automatically updated. The JTree looks powerful at the moment, i am quite satisfied with it.
However the nightmare comes, when i click on the leaf nodes on the UI and the getLastSelectedPathCompoent() mystically returned the already-removed leaf nodes but not the newly-inserted leaf nodes.
I tried debugging for a couple of hours, but failed! I think i am doing something really wrong :( Anyone help me out? Thanks a lot!problem solved:)
solved by calling the updateUI() for the removal operation..... -
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.
-
Hi ,
I am new to java swings, I am having problem with jtree casting.
I have the tree which I created in the similar way as DNDTree
The tree has 4 types such as model/subject/entity/attribues each
of different class. My problem is when I drag and drop .. later I have
to save the tree with all the properties into respective tables. Please
help me how do I accomplish.
ThanksHi, This is the error I m getting.
Excpetion is javax.swing.tree.DefaultMutableTreeNode cannot be cast to com.idecisions.cdi.hme_prac.MySubjectNodejava.lang.ClassCastException: javax.swing.tree.DefaultMutableTreeNode cannot be cast to com.idecisions.cdi.hme_prac.MySubjectNode
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source) -
I am having a problem printing a JPanel that includes a JLabel, a JPanel, and a JTree. If I only add the JLabel and JPanel to the JPanel to be printed, everything works fine. But as soon as I add my JTree (which is small, and should fit on one page), the pageIndex stops being incremented and I end up with the print method being infinitely called. Has anyone run into this problem before? Why is the pageIndex not being incremented?
Thanks for any help!
andrewwi1Ok, after a whole lot of trial and error I think I answered my own question.
It seems that adding the JTree to the Panel to be printed really caused the Print API to call the print method many many times on the same pageIndex. I had never seen it need to render the same page more than 4 or 5 times before now. I was running the code through debug (using VisualAge for Java), and was also causing the panel to be printed to the screen via JFrame. So after I'd get about 30 JFrames containing my print panel I'd assume something was wrong and kill the thread. Turns out it needs to render the same page 30+ times with a JTree (or at least with my JTree). After turning of the JFrame visibility (so I wouldn't see them pop up on my screen) and waiting for quite awhile, the page finally printed just fine.
Maybe you are looking for
-
Confused about wheather to use session or some other technology
i have two jsp pages one is index.jsp and other one is display.jsp,from index.jsp i am passing a string value and collecting it in display.jsp ,after collecting it i am making use of that value in a sql query to display the result from the data base,
-
Cnr 6.2 upgrade to 8.1
hello, I have to make a upgrade of a CNR 6.2 ( two servers in failover pair) to the version CNR 8.1 : The customer configuration is actually : Two servers in OS platform currently : Windows server 2003 Enterprise Edition SP2 2 servers ( failover p
-
HT2506 My PREVIEW keeps crashing when I try to print. Why?
When I open photos in my PREVIEW program, and then try to print... it keeps crashing and telling me "preview quit unexpectedly while using the EF172218 (FF) Plug-in." Process: Preview [4001] Path: /Applications/Preview.app/Contents
-
Fireworks 8 on OS X font problems and Solutions
Hi All I had a problem with my Fireworks 8 and being able to switch fonts. The list would scroll very slowly and sooner or later crash Fireworks. If I tried to open an PSD file with text in it I would crash not only my Fireworks program but the entir
-
I have spent the longest time trying to figure out how to make my edge animate site be able to resize without having any distortion. And this is where I need help!! It's driving me crazy because I cannot create a stable website! This is the site