JTree 失去焦点可编辑

import java.awt.*;
import java.awt.event.*;
import java.util.EventObject;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;

public class ELS
{
	public static void main(String args[])
	{
		JFrame frame = new JFrame("Editable Tree");
		JTree tree = new JTree();
		tree.setEditable(true);

		DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree
				.getCellRenderer();
		TreeCellEditor editor = new LeafCellEditor(tree, renderer,
				new LeafEditor());
		tree.setCellEditor(editor);

		// This allows the edit to be saved if editing is interrupted
		// by a change in selection, focus, etc -> see method detail.
		tree.setInvokesStopCellEditing(true);

		JScrollPane scrollPane = new JScrollPane(tree);
		frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
		frame.setSize(300, 350);
		frame.setVisible(true);
	}
}

class LeafCellEditor extends DefaultTreeCellEditor
{
	public LeafCellEditor(JTree tree, DefaultTreeCellRenderer renderer)
	{
		super(tree, renderer);
	}

	public LeafCellEditor(JTree tree, DefaultTreeCellRenderer renderer,
			TreeCellEditor editor)
	{
		super(tree, renderer, editor);
	}
}

class LeafEditor extends AbstractCellEditor implements TreeCellEditor,
		ActionListener
{
	JTextField textField;

	public LeafEditor()
	{
		textField = new JTextField();
		textField.addActionListener(this);
	}

	public Component getTreeCellEditorComponent(JTree tree, Object value,
			boolean isSelected, boolean expanded, boolean leaf, int row)
	{
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
		textField.setText(node.toString());
		return textField;
	}

	public boolean isCellEditable(EventObject event)
	{
		// System.out.println("event = " + event);
		// Get initial setting
		boolean returnValue = super.isCellEditable(event);
		if (event instanceof MouseEvent)
		{
			// If still possible, check if current tree node is a leaf
			if (returnValue)
			{
				JTree tree = (JTree) event.getSource();
				Object node = tree.getLastSelectedPathComponent();
				if ((node != null) && (node instanceof TreeNode))
				{
					TreeNode treeNode = (TreeNode) node;
					returnValue = treeNode.isLeaf();
				}
			}
		}
		return returnValue;
	}

	public Object getCellEditorValue()
	{
		return textField.getText();
	}

	/** Press enter key to save the edited value. */
	public void actionPerformed(ActionEvent e)
	{
		super.stopCellEditing();
	}
}

你可能感兴趣的:(JTree)