📄 dirpanel.java
字号:
/* * Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved. * * Permission to use, copy, modify, and distribute this software * and its documentation for NON-COMMERCIAL purposes and without * fee is hereby granted provided that this copyright notice * appears in all copies. * * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING * THIS SOFTWARE OR ITS DERIVATIVES. * * "@(#)DirPanel.java 1.1 99/05/06 SMI" */package examples.browser;import javax.swing.*;import javax.swing.event.*;import javax.swing.border.*;import java.awt.*;import java.awt.event.*;import javax.swing.tree.*;import javax.naming.*;import javax.naming.directory.*;import java.util.Enumeration;import java.util.Hashtable;import java.net.URL;/** * This class is a panel for displaying a namespace. * It consists of a toolbar, a split pane and a status line at the bottom. * The left pane contains a tree showing the hierarchical structure * of the namespace. The right pane is a list displaying the contents * of the selected tree node and search results. * * Double clicking on a list entry brings up a window for viewing and * editing the attributes associated with the entry. * * @author Rosanna Lee */public class DirPanel extends JPanel implements ConfigListener { static final boolean debug = true; JTree tree; // Hierarchical view of the namespace JList list; // Contents of the selected tree node DirTreeModel treeModel; // Representation of data in tree JViewport treeViewPort; JLabel status = new JLabel("Ready"); Hashtable env; // Environment properties of provider String root; // Root of namespace to start browsing boolean initialized = false; // whether panel's data has been initialized Component cursorComp; // Component for setting cursor /** * Constructs a new instance of DirPanel. * More arguments to come: Environment properties */ public DirPanel(Component cursorComp, Hashtable env, String rootName) { super(new BorderLayout()); this.cursorComp = cursorComp; this.env = env; this.root = rootName; list = new JList(new DefaultListModel()); list.setCellRenderer(new DirListCellRenderer()); list.addMouseListener(new DoubleClickHandler());// -- Put tree and list into scrollers and SplitPane // Set up empty tree for now; see initialize() tree = new JTree(new Hashtable(7)); tree.setShowsRootHandles(true); tree.collapseRow(0); /* Put the tree in a scroller. */ JScrollPane leftSp = new JScrollPane(); leftSp.setPreferredSize(new Dimension(250, 300)); treeViewPort = leftSp.getViewport(); treeViewPort.setView(tree); /* Put list in a scroller */ JScrollPane rightSp = new JScrollPane(); rightSp.setPreferredSize(new Dimension(250, 300)); rightSp.getViewport().setView(list); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftSp, rightSp); splitPane.setPreferredSize(new Dimension(500, 300)); splitPane.setContinuousLayout(true); /* Put split pane into panel, and add status line on bottom */ add(constructToolBar(), BorderLayout.NORTH); add(splitPane, BorderLayout.CENTER); add(status, BorderLayout.SOUTH); }// --- set up tree void init() { if (initialized) return; DirTreeNode rootNode = null; waitCursor(); try { Context ctx = getInitialContext(); Object obj; if (root != null) { obj = ctx.lookup(root); rootNode = new DirTreeNode(new DirData(root, obj)); } else { rootNode = new DirTreeNode(new DirData("", ctx)); } } catch (NamingException e) { if (debug) e.printStackTrace(); setStatus(e); return; } finally { restoreCursor(); } initialized = true; /* Create the tree. */ tree = new JTree(rootNode); tree.setShowsRootHandles(true); tree.collapseRow(0); treeModel = new DirTreeModel(rootNode); tree.setModel(treeModel); /* Allow items to be editable (renamed) */ tree.setEditable(true); /* Enable tool tips for the tree, without this tool tips will not be picked up. */ ToolTipManager.sharedInstance().registerComponent(tree); /* Make the tree use an instance of DirTreeCellRenderer for drawing nodes. */ tree.setCellRenderer(new DirTreeCellRenderer()); /* Make tree ask for the height of each row. */ tree.setRowHeight(-1); /* Add listeners for selection and expansion of nodes */ tree.addTreeSelectionListener(new TreeSelectionHandler()); // tree.addTreeExpansionListener(new TreeExpansionHandler()); /* Update view port in split pane. */ treeViewPort.setView(tree); } /** * Called when root and/or environment properties have been modified. * Force reset of tree and list views. */ void reinitialize(String newRoot, Hashtable newEnv) { if (debug) System.err.println("Reinitializing"); this.root = newRoot; this.env = newEnv; // initialize tree gotten = false; initialized = false; init(); // initialize list DefaultListModel lm = (DefaultListModel)list.getModel(); lm.clear(); // Force frame to update invalidate(); validate(); }// -- Deal with Initial Context Context initialContext = null; boolean gotten = false; Context getInitialContext() throws NamingException { if (gotten) { return initialContext; } initialContext = new InitialDirContext(env); gotten = true; return initialContext; } Context getParentContext(DirTreeNode node) throws NamingException { DirTreeNode parent = (DirTreeNode)node.getParent(); Context parentCtx = null; if (parent != null) { parentCtx = (Context)((DirData)parent.getUserObject()).getObject(); } if (parentCtx == null) { // we're at the root, parent is the initial context parentCtx = getInitialContext(); } return parentCtx; }// -- Methods for dealing with status line void setStatus(String s, boolean beep) { if (beep) java.awt.Toolkit.getDefaultToolkit().beep(); if (debug) System.err.println("status: " + s); status.setText(s); } void setStatus(String s) { setStatus(s, true); } void setStatus(Exception e) { // %%% for DEMO only boolean beep = !(e instanceof NoInitialContextException); setStatus(e.getClass().getName(), beep); Browser.appendToConsole(e); } void resetStatus() { status.setText("Ready"); }// -- Methods for setting stop watch cursor Cursor savedCursor; void waitCursor() { //System.err.println("set wait cursor"); savedCursor = cursorComp.getCursor(); cursorComp.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } void restoreCursor() { //System.err.println("restoring cursor"); cursorComp.setCursor(savedCursor); } /** * Returns the TreeNode instance that is selected in the tree. * If nothing is selected, null is returned. */ DefaultMutableTreeNode getSelectedNode() { TreePath selPath = tree.getSelectionPath(); if(selPath != null) return (DefaultMutableTreeNode)selPath.getLastPathComponent(); return null; } /** * Ask user whether it is OK to proceed. */ boolean checkWithUser(String msg) { Object[] options = {"OK", "CANCEL"}; return (JOptionPane.showOptionDialog(this, msg, "Warning", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]) == 0); } /** * RemoveAction removes the selected node from the tree. * If the root is selcted or if nothing is selected, nothing is removed. */ void removeSelectedNode() { DirTreeNode target = (DirTreeNode)getSelectedNode(); if (target == (DirTreeNode)treeModel.getRoot()) { setStatus("Cannot remove root"); return; } if(target == null) { setStatus("Select a tree node first."); return; } try { Context parentCtx = getParentContext(target); String name = ((DirData)target.getUserObject()).getName(); if (!checkWithUser( "Click OK to remove '" + name + "'")) { return; } waitCursor();DirPanel.debugName("Remove", name); if (((DirData)target.getUserObject()).isContext()) { parentCtx.destroySubcontext(name); } else { parentCtx.unbind(name); } treeModel.removeNodeFromParent(target); resetStatus(); } catch (NamingException e) { if (debug) e.printStackTrace(); setStatus(e); } finally { restoreCursor(); } } /** * When tree node is selected, display its contents in list. */ class TreeSelectionHandler implements TreeSelectionListener { public void valueChanged(TreeSelectionEvent evt) { DirTreeNode target; DefaultListModel lm; // Only do something if node is selected // Ignore if unselected if (!evt.isAddedPath()) { return; } waitCursor(); try { target = (DirTreeNode)evt.getPath().getLastPathComponent(); lm = (DefaultListModel)list.getModel(); lm.clear(); if (target.loadChildren(false)) { for (Enumeration enum = target.children(); enum.hasMoreElements();) { lm.addElement(enum.nextElement()); } } else { /** * If object is not a context, then display its contents */ DirData data = (DirData)(target.getUserObject()); if (data.getObject() != null) { if (data.getObject() instanceof Component) { (new ShowComponentThread( (Component)data.getObject(), data.getName())).start(); } else if (!(data.getObject() instanceof Context)) { (new ShowComponentThread( data.getObject().toString(), data.getName())).start(); } } } // Refresh list area list.invalidate(); list.validate(); } finally { restoreCursor(); } } } class ShowComponentThread extends Thread { Object obj; String name; ShowComponentThread(Object obj, String name) { this.obj = obj; this.name = name; } public void run() { JOptionPane.showMessageDialog(null, obj, name, JOptionPane.PLAIN_MESSAGE); // The following shows a "Dismiss" button instead of "OK"/* String[] options = {"Dismiss"}; JOptionPane.showOptionDialog(null, component, name, JOptionPane.PLAIN_MESSAGE, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);*/ } } /** * When tree node is opened, load its contents. *//* class TreeExpansionHandler implements TreeExpansionListener, LoadChildrenListener { public void treeExpanded(TreeExpansionEvent evt) {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -