下面列出了怎么用javax.swing.JTree的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public boolean canPerformAction(JTree targetTree, Object draggedNode, int action, Point location) {
TreePath pathTarget = targetTree.getPathForLocation(location.x, location.y);
if (pathTarget == null) {
targetTree.setSelectionPath(null);
return false;
}
targetTree.setSelectionPath(pathTarget);
if (action == DnDConstants.ACTION_COPY) {
return false;
} else if (action == DnDConstants.ACTION_MOVE) {
Object targetNode = pathTarget.getLastPathComponent();
return canMove(draggedNode, targetNode);
} else {
return false;
}
}
private boolean setCellSelection(Properties[] properties) {
JTree tree = (JTree) component;
if (properties.length == 0) {
tree.setSelectionRows(new int[0]);
return true;
}
List<TreePath> paths = new ArrayList<TreePath>();
for (Properties propertie : properties) {
TreePath path = getPath(tree, propertie.getProperty("Path"));
if (path != null) {
paths.add(path);
}
}
if (paths.size() != properties.length) {
return false;
}
tree.setSelectionPaths(paths.toArray(new TreePath[paths.size()]));
return true;
}
private static List<TypeMemberTreeNode> getSelectedNodesSorted(final JTree tree) {
final List<TypeMemberTreeNode> nodes = Lists.newArrayList();
for (final TreePath path : tree.getSelectionPaths()) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
if (node instanceof TypeMemberTreeNode) {
nodes.add((TypeMemberTreeNode) node);
} else {
return Lists.newArrayList();
}
}
Collections.sort(nodes, new Comparator<TypeMemberTreeNode>() {
@Override
public int compare(final TypeMemberTreeNode node0, final TypeMemberTreeNode node1) {
return node0.getTypeMember().compareTo(node1.getTypeMember());
}
});
return nodes;
}
/**
* This method is called by Swing to return an object to be drawn.
*/
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean isLeaf, int row, boolean isFocused) {
String string = tree.convertValueToText(value, isSelected, expanded, isLeaf, row, isFocused);
this.isFocused = isFocused;
this.isSelected = isSelected;
setText(string);
setForeground(UIManager.getColor(isSelected ? "Tree.selectionForeground" : "Tree.textForeground"));
preferredHeight = 0; // By default, don't override width/height
if (do_isDouble(value)) {
Dimension d = super.getPreferredSize();
preferredWidth = d.width + 3;
preferredHeight = d.height * 2;
}
return this;
}
@Override
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);
RobotComponent comp = (RobotComponent) value;
if (comp.isValid()) {
setForeground(Color.black);
} else {
setForeground(Color.red);
}
if (comp.supportsChildren() && leaf) {
setIcon(getOpenIcon());
}
return this;
}
@Test
public void testEscapeOpenSecondProgram() throws Exception {
restoreProgram(diffTestP2);
loadProgram(diffTestP1);
launchDiffByAction();
Window win = waitForWindow("Select Other Program");
assertNotNull(win);
waitForSwing();
Component comp = getComponentOfType(win, JComboBox.class);
assertNotNull(comp);
JTree tree = findComponent(win, JTree.class);
TreeTestUtils.selectTreeNodeByText(tree, "DiffTestPgm2");
triggerActionKey(comp, 0, KeyEvent.VK_ESCAPE);
waitForSwing();
assertNull(fp2.getTopLevelAncestor());
win = getWindow("Select Other Program");
assertNull(win);
closeProgram();
assertNull(cb.getCurrentLocation());
}
@Override
public boolean isEnableForComponent(Component invoker) {
if (invoker.getName() != null && invoker.getName().equals(ScriptsListPanel.TREE)) {
try {
JTree tree = (JTree) invoker;
ScriptNode node = (ScriptNode) tree.getLastSelectedPathComponent();
if (node == null
|| !node.isTemplate()
|| node.getUserObject() == null
|| !(node.getUserObject() instanceof ScriptWrapper)) {
return false;
}
if (((ScriptWrapper) node.getUserObject()).getEngine() == null) {
return false;
}
return extension.getScriptsPanel().getSelectedScript() != null;
} catch (Exception e) {
}
}
return false;
}
private String getTextForNode(JTree tree, int row) {
TreePath treePath = tree.getPathForRow(row);
if (treePath == null) {
return row + "";
}
StringBuilder sb = new StringBuilder();
int start = tree.isRootVisible() ? 0 : 1;
Object[] objs = treePath.getPath();
for (int i = start; i < objs.length; i++) {
String pathString;
if (objs[i].toString() == null) {
pathString = "";
} else {
pathString = escapeSpecialCharacters(getTextForNodeObject(tree, objs[i]));
}
sb.append("/" + pathString);
}
return sb.toString();
}
/**
* Returns the rendered cell for the supplied value.
*
* @param jtrHierarchy
* The JTree
* @param value
* The value to assign to the cell
* @param isSelected
* True if cell is selected
* @param isExpanded
* True if cell is expanded
* @param leaf
* True if cell is a lesaf
* @param row
* The row of the cell to render
* @param hasFocus
* If true, render cell appropriately
* @return The renderered cell
*/
@Override
public Component getTreeCellRendererComponent(JTree jtrHierarchy, Object value, boolean isSelected,
boolean isExpanded, boolean leaf, int row, boolean hasFocus) {
JLabel cell = (JLabel) super.getTreeCellRendererComponent(jtrHierarchy, value, isSelected, isExpanded, leaf,
row, hasFocus);
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) value;
Object userObject = treeNode.getUserObject();
if (userObject instanceof X509Certificate) {
X509Certificate cert = (X509Certificate) userObject;
cell.setText(X509CertUtil.getShortName(cert));
ImageIcon icon = new ImageIcon(getClass().getResource(
"images/certificate_node.png"));
cell.setIcon(icon);
cell.setToolTipText(X500NameUtils.x500PrincipalToX500Name(cert.getSubjectX500Principal()).toString());
}
return cell;
}
@SwingThread
void expandToFirstLeaf(int max) {
Debug.println("expand to first leaf");
if (leavesShown()) {
return;
}
JTree jTree = getTree();
int i = 0;
while (true) {
int rows = jTree.getRowCount();
if (i >= rows || rows >= max) {
break;
}
TreePath treePath = jTree.getPathForRow(i);
Object lastPathComponent = treePath.getLastPathComponent();
if (lastPathComponent instanceof BugLeafNode) {
return;
}
jTree.expandRow(i++);
}
}
/**
* 返回的是一个<code>JPanel</code>对象,该对象中包含一个<code>JCheckBox</code>对象 和一个
* <code>JLabel</code>对象。并且根据每个结点是否被选中来决定<code>JCheckBox</code> 是否被选中。
*/
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
String stringValue = tree.convertValueToText(value, selected, expanded, leaf, row, hasFocus);
setEnabled(tree.isEnabled());
if (value instanceof CheckBoxTreeNode) {
check.setSelected(((CheckBoxTreeNode)value).isSelected());
}
label.setFont(tree.getFont());
label.setText(stringValue);
label.setSelected(selected);
label.setFocus(hasFocus);
if (leaf)
label.setIcon(UIManager.getIcon("Tree.leafIcon"));
else if (expanded)
label.setIcon(UIManager.getIcon("Tree.openIcon"));
else
label.setIcon(UIManager.getIcon("Tree.closedIcon"));
return this;
}
@Override
public Component getTreeCellRendererComponent(final JTree tree,
final Object value,
final boolean sel,
final boolean expanded,
final boolean leaf,
final int row,
final boolean hasFocus) {
final boolean selected = m_lastSelectionNode != null &&
((DefaultMutableTreeNode) value).getUserObject() == m_lastSelectionNode.getUserObject();
super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, selected);
setForeground(DEFAULT_FOREGROUND_COLOR);
if (value instanceof CTagTreeNode) {
renderTagTreeNode((CTagTreeNode) value);
} else if (value instanceof CTaggedGraphNodeNode) {
renderTaggedGraphNodeNode((CTaggedGraphNodeNode) value);
} else if (value instanceof CTaggedGraphNodesContainerNode) {
renderTaggedGraphNodesContainerNode((CTaggedGraphNodesContainerNode) value);
}
return this;
}
public void singleNodeSelected() throws Throwable, InvocationTargetException {
final JTree tree = (JTree) ComponentUtils.findComponent(JTree.class, frame);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
siw(new Runnable() {
@Override
public void run() {
tree.expandRow(0);
tree.setSelectionRow(0);
}
});
final LoggingRecorder lr = new LoggingRecorder();
siw(new Runnable() {
@Override
public void run() {
Rectangle rowBounds = tree.getRowBounds(0);
RTree rTree = new RTree(tree, null, rowBounds.getLocation(), lr);
rTree.mouseButton1Pressed(null);
}
});
Call call = lr.getCall();
AssertJUnit.assertEquals("click", call.getFunction());
AssertJUnit.assertEquals("/Root Node", call.getCellinfo());
}
/**
* Loads a project inside a thread.
*
* @param parent Parent window used for dialogs.
* @param project Project to load.
* @param projectTree Project tree to expand on project loading. This argument can be null.
*/
private static void loadProjectThreaded(final Window parent, final INaviProject project,
final JTree projectTree) {
Preconditions.checkNotNull(parent, "IE00005: Parent argument can not be null");
Preconditions.checkNotNull(project, "IE01284: Project argument can not be null");
if (project.isLoading()) {
return;
}
new Thread() {
@Override
public void run() {
loadProjectInternal(parent, project, projectTree);
}
}.start();
}
/**
* Invokes the <code>getPathBounds</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Rectangle getPathBounds(JTree a, TreePath b) {
Rectangle returnValue =
((TreeUI) (uis.elementAt(0))).getPathBounds(a,b);
for (int i = 1; i < uis.size(); i++) {
((TreeUI) (uis.elementAt(i))).getPathBounds(a,b);
}
return returnValue;
}
public CModuleInitializeAction(final JTree projectTree, final INaviModule[] modules) {
super(generateMenuEntryName(modules));
m_projectTree =
Preconditions.checkNotNull(projectTree, "IE01901: Project tree argument can not be null");
m_modules =
Preconditions.checkNotNull(modules, "IE01902: Module argument can't be null").clone();
putValue(ACCELERATOR_KEY, HotKeys.INITIALIZE_MODULE_ACCELERATOR_KEY.getKeyStroke());
putValue(MNEMONIC_KEY, (int) "HK_MENU_INITIALIZE_MODULE".charAt(0));
}
/**
* Maps {@code JTree.setInvokesStopCellEditing(boolean)} through queue
*/
public void setInvokesStopCellEditing(final boolean b) {
runMapping(new MapVoidAction("setInvokesStopCellEditing") {
@Override
public void map() {
((JTree) getSource()).setInvokesStopCellEditing(b);
}
});
}
/**
* Invokes the <code>stopEditing</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean stopEditing(JTree a) {
boolean returnValue =
((TreeUI) (uis.elementAt(0))).stopEditing(a);
for (int i = 1; i < uis.size(); i++) {
((TreeUI) (uis.elementAt(i))).stopEditing(a);
}
return returnValue;
}
/**
* Invokes the <code>getPathBounds</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Rectangle getPathBounds(JTree a, TreePath b) {
Rectangle returnValue =
((TreeUI) (uis.elementAt(0))).getPathBounds(a,b);
for (int i = 1; i < uis.size(); i++) {
((TreeUI) (uis.elementAt(i))).getPathBounds(a,b);
}
return returnValue;
}
@Override
public void mousePressed(MouseEvent e) {
JTree objectTree = treeView.getTree();
TreePath selPath = objectTree.getPathForLocation(e.getX(), e.getY());
if (selPath == null) {
if (e.getButton() == MouseEvent.BUTTON3) {
showPopupMenu(e.getX(), e.getY());
}
}
else {
UserObject userObject = getUserObject(selPath);
if (e.getButton() == MouseEvent.BUTTON3) {
evaluateRightClick(e, userObject, treeView.getSelectedItems());
}
else if (e.getButton() == MouseEvent.BUTTON1) {
//This Method tells the OpenTCSView what elements are currently selected
((AbstractUserObject) userObject).selectMultipleObjects();
if (e.getClickCount() == 2) {
userObject.doubleClicked();
}
}
}
}
public Component getTreeCellRendererComponentPersistent(JTree tree, Object value, boolean sel, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
LockContentionTreeCellRenderer renderer = new LockContentionTreeCellRenderer();
// renderer.setLeafIcon(leafIcon);
// renderer.setClosedIcon(closedIcon);
// renderer.setOpenIcon(openIcon);
return renderer.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
}
/**
* Invokes the <code>isEditing</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean isEditing(JTree a) {
boolean returnValue =
((TreeUI) (uis.elementAt(0))).isEditing(a);
for (int i = 1; i < uis.size(); i++) {
((TreeUI) (uis.elementAt(i))).isEditing(a);
}
return returnValue;
}
@Override
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);
Layer layer = (Layer) value;
if (ProductSceneView.BASE_IMAGE_LAYER_ID.equals(layer.getId())) {
label.setText(String.format("<html><b>%s</b></html>", layer.getName()));
}
return label;
}
/**
* Creates a new component object.
*
* @param projectTree Project tree that is updated when certain events happen.
* @param database Database where the module is stored.
* @param addressSpace Address space the module belongs to (this argument can be null in case of a
* global module).
* @param module Module that provides the information displayed in the component.
* @param container Container that represents the context in which the module is displayed.
*/
public CModuleNodeComponent(final JTree projectTree, final IDatabase database,
final INaviAddressSpace addressSpace, final INaviModule module,
final IViewContainer container) {
super(new BorderLayout());
Preconditions.checkNotNull(database, "IE01977: Database argument can't be null");
this.module = Preconditions.checkNotNull(module, "IE01978: Module argument can't be null");
// Note: the order of creating tabs must not be changed since, e.g., focusSectionAddress relies
// upon a fixed index.
tabbedPane.addTab("Overview", OVERVIEW_ICON, overviewPanel =
new CModuleOverviewPanel(projectTree, database, addressSpace, module, container));
tabbedPane.addTab("Functions" + String.format(" (%d)", module.getFunctionCount()),
FUNCTIONS_ICON, functionsPanel =
new CNativeFunctionViewsNodeComponent(projectTree, database, module, container));
tabbedPane.addTab("Views" + String.format(" (%d)", module.getCustomViewCount()), VIEWS_ICON,
viewsPanel = new CModuleViewsContainerComponent(projectTree, container));
tabbedPane.addTab("Debug Traces", TRACES_ICON,
tracesPanel = new CTracesNodeComponent(projectTree, container));
tabbedPane.addTab(
"Sections and Types", DATA_ICON, dataPanel = new CDataNodeComponent(module, container));
tabbedPane.setEnabledAt(1, module.isLoaded());
tabbedPane.setEnabledAt(2, module.isLoaded());
tabbedPane.setEnabledAt(3, module.isLoaded());
tabbedPane.setEnabledAt(4, module.isLoaded());
module.addListener(internalModuleListener);
add(tabbedPane);
lookup.put(module, this);
}
private void expandAllNodes(JTree tree, int startingIndex, int rowCount){
for(int i=startingIndex;i<rowCount;++i){
tree.expandRow(i);
}
if(tree.getRowCount()!=rowCount){
expandAllNodes(tree, rowCount, tree.getRowCount());
}
}
public static void restoreState(final JTreeTable ttable, List paths, TreePath selected) {
if (paths != null) {
JTree tree = ttable.getTree();
HeapWalkerNode root = (HeapWalkerNode)tree.getModel().getRoot();
for (Object path : paths) ensurePathComputed(root, (TreePath)path, new HashSet());
ttable.setup(paths, selected);
}
}
@Override
public Icon getIcon(JTree tree, Object value, boolean selected,
boolean expanded, boolean leaf, int row, boolean isRollover,
boolean isPressed) {
return decoration.getIcon(tree, value, selected, expanded, leaf, row,
isRollover, isPressed);
}
@Override
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);
try {
DefaultMutableTreeNode node = ((DefaultMutableTreeNode) value);
if (node.getUserObject() instanceof String) {
setIcon(server);
} else if (node.getUserObject() instanceof UserProfile) {
if (((UserProfile) node.getUserObject()).isUVAccount()) {
setIcon(uvProfile);
} else {
setIcon(mainProfile);
}
}
} catch (Exception ignored) {
}
return this;
}
/**
* Invokes the <code>isEditing</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean isEditing(JTree a) {
boolean returnValue =
((TreeUI) (uis.elementAt(0))).isEditing(a);
for (int i = 1; i < uis.size(); i++) {
((TreeUI) (uis.elementAt(i))).isEditing(a);
}
return returnValue;
}
public DynamicTree() {
super(new GridLayout(1, 0));
rootNode = new DefaultMutableTreeNode("Root Node");
treeModel = new DefaultTreeModel(rootNode);
treeModel.addTreeModelListener(new MyTreeModelListener());
tree = new JTree(treeModel);
tree.setEditable(true);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setShowsRootHandles(true);
JScrollPane scrollPane = new JScrollPane(tree);
add(scrollPane);
}