请教:如何在一个TreeView中实现某些树结点有CheckBox,某些树结点没有CheckBox?(哪些结点有CheckBox是完全确定的)谢谢!

解决方案 »

  1.   

    看了一下, 估计比较麻烦。 我先说说我的想法。1. 继承org.elcipse.swt.widgets.Tree, 写一个Tree的子类。 重写createItem()方法, 返回步骤2中定义的TreeItem子类。
    2. 继承org.eclipse.swt.widgets.TreeItem, 写一个TreeItem的子类。在TreeItem类中决定是否显示Checkbox.
    3.继承CheckboxTreeViewer, 在构造方法中创建步骤1中定义的Tree子类。没有仔细想, 权当作参考吧。
      

  2.   

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import com.incors.plaf.alloy.*;//组件的下载网址http://www.incors.com/lookandfeel/
    /*将alloy.jar放在c:\j2sdk1.4.0\jre\lib\ext\目录下.
     */
    public class TreeDemo3
    {
        public TreeDemo3()
        {
            JFrame f = new JFrame("TreeDemo");
            Container contentPane = f.getContentPane();
            
            
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("资源管理器");
            DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("我的公文包");
            DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("我的电脑");
            DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("收藏夹");
            DefaultMutableTreeNode node4 = new DefaultMutableTreeNode("Readme");
            
            DefaultTreeModel treeModel = new DefaultTreeModel(root);        /*DefaultTreeModel类所提供的insertNodeInto()方法加入节点到父节点的数量.
             *利用DefaultMutableTreeNode类所提供的getChildCount()方法取得目前子节点的数量.
             */
            treeModel.insertNodeInto(node1, root, root.getChildCount());
            treeModel.insertNodeInto(node2, root, root.getChildCount());
            treeModel.insertNodeInto(node3, root, root.getChildCount());
            treeModel.insertNodeInto(node4, root, root.getChildCount());
            
            DefaultMutableTreeNode leafnode = new 
                    DefaultMutableTreeNode("公司文件");        //DefaultTreeModel类所提供的insertNodeInto()方法加入节点到父节点的数量.
            treeModel.insertNodeInto(leafnode, node1, node1.getChildCount());
            leafnode = new DefaultMutableTreeNode("个人信件");
            treeModel.insertNodeInto(leafnode, node1, node1.getChildCount());
            leafnode = new DefaultMutableTreeNode("私人文件");
            treeModel.insertNodeInto(leafnode, node1, node1.getChildCount());
            
            leafnode = new DefaultMutableTreeNode("本机磁盘(C:)");
            treeModel.insertNodeInto(leafnode, node2, node2.getChildCount());
            leafnode = new DefaultMutableTreeNode("本机磁盘(D:)");
            treeModel.insertNodeInto(leafnode, node2, node2.getChildCount());
            leafnode = new DefaultMutableTreeNode("本机磁盘(E:)");
            treeModel.insertNodeInto(leafnode, node2, node2.getChildCount());
            
            DefaultMutableTreeNode node31 = new DefaultMutableTreeNode("网站列表");
            treeModel.insertNodeInto(node31, node3, node3.getChildCount());
            leafnode = new DefaultMutableTreeNode("奇摩站");
            treeModel.insertNodeInto(leafnode, node3, node3.getChildCount());
            leafnode = new DefaultMutableTreeNode("职棒消息");
            treeModel.insertNodeInto(leafnode, node3, node3.getChildCount());
            leafnode = new DefaultMutableTreeNode("网络书店");
            treeModel.insertNodeInto(leafnode, node3, node3.getChildCount());
            try {
               LookAndFeel alloyLnF = new AlloyLookAndFeel();    
               UIManager.setLookAndFeel(alloyLnF);
            } catch (UnsupportedLookAndFeelException ex) {
            // You may handle the exception here
            }
             // this line needs to be implemented in order to make JWS work properly
              UIManager.getLookAndFeelDefaults().put("ClassLoader", getClass().getClassLoader());
            
            //以TreeModel建立JTree。
            JTree tree = new JTree(treeModel);
            /*改变JTree的外观**/
              tree.putClientProperty("JTree.lineStyle","Horizontal");
            /*改变JTree的外观**/
            JScrollPane scrollPane = new JScrollPane();
            scrollPane.setViewportView(tree);
            
            contentPane.add(scrollPane);
            f.pack();
            f.setVisible(true);
            
            f.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });    }    public static void main(String args[]) {
        
            new TreeDemo3();
        }
    }
      

  3.   

    以上的代码实现了在tree node上显示节点的功能,继承它,然后把节点改为checkbox显示。
    希望对楼主有帮助
      

  4.   

    congliu兄,谢谢!我们用的是SWT而不是SWING。汗。:)mr_yanfei(晏斐) 兄,谢谢,正在考虑如何实现,痛苦。
      

  5.   

    import org.eclipse.jface.viewers.*;
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.events.*;
    import org.eclipse.swt.layout.*;
    import org.eclipse.swt.widgets.*;/**
     * This class demonstrates the CheckboxTreeViewer
     */
    public class CheckFileTree extends FileTree {
      /**
       * Configures the shell
       * 
       * @param shell the shell
       */
      protected void configureShell(Shell shell) {
        super.configureShell(shell);
        shell.setText("Check File Tree");
      }  /**
       * Creates the main window's contents
       * 
       * @param parent the main window
       * @return Control
       */
      protected Control createContents(Composite parent) {
        Composite composite = new Composite(parent, SWT.NONE);
        composite.setLayout(new GridLayout(1, false));    // Add a checkbox to toggle whether the labels preserve case
        Button preserveCase = new Button(composite, SWT.CHECK);
        preserveCase.setText("&Preserve case");    // Create the tree viewer to display the file tree
        final CheckboxTreeViewer tv = new CheckboxTreeViewer(composite);
        tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));
        tv.setContentProvider(new FileTreeContentProvider());
        tv.setLabelProvider(new FileTreeLabelProvider());
        tv.setInput("root"); // pass a non-null that will be ignored    // When user checks the checkbox, toggle the preserve case attribute
        // of the label provider
        preserveCase.addSelectionListener(new SelectionAdapter() {
          public void widgetSelected(SelectionEvent event) {
            boolean preserveCase = ((Button) event.widget).getSelection();
            FileTreeLabelProvider ftlp = (FileTreeLabelProvider) tv
                .getLabelProvider();
            ftlp.setPreserveCase(preserveCase);
          }
        });    // When user checks a checkbox in the tree, check all its children
        tv.addCheckStateListener(new ICheckStateListener() {
          public void checkStateChanged(CheckStateChangedEvent event) {
            // If the item is checked . . .
            if (event.getChecked()) {
              // . . . check all its children
              tv.setSubtreeChecked(event.getElement(), true);
            }
          }
        });
        return composite;
      }  /**
       * The application entry point
       * 
       * @param args the command line arguments
       */
      public static void main(String[] args) {
        new CheckFileTree().run();
      }
    }
      

  6.   

    import org.eclipse.jface.viewers.TreeViewer;
    import org.eclipse.jface.window.ApplicationWindow;
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.events.*;
    import org.eclipse.swt.layout.*;
    import org.eclipse.swt.widgets.*;/**
     * This class demonstrates TreeViewer. It shows the drives, directories, and files
     * on the system.
     */
    public class FileTree extends ApplicationWindow {
      /**
       * FileTree constructor
       */
      public FileTree() {
        super(null);
      }  /**
       * Runs the application
       */
      public void run() {
        // Don't return from open() until window closes
        setBlockOnOpen(true);    // Open the main window
        open();    // Dispose the display
        Display.getCurrent().dispose();
      }  /**
       * Configures the shell
       * 
       * @param shell the shell
       */
      protected void configureShell(Shell shell) {
        super.configureShell(shell);    // Set the title bar text and the size
        shell.setText("File Tree");
        shell.setSize(400, 400);
      }  /**
       * Creates the main window's contents
       * 
       * @param parent the main window
       * @return Control
       */
      protected Control createContents(Composite parent) {
        Composite composite = new Composite(parent, SWT.NONE);
        composite.setLayout(new GridLayout(1, false));    // Add a checkbox to toggle whether the labels preserve case
        Button preserveCase = new Button(composite, SWT.CHECK);
        preserveCase.setText("&Preserve case");    // Create the tree viewer to display the file tree
        final TreeViewer tv = new TreeViewer(composite);
        tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));
        tv.setContentProvider(new FileTreeContentProvider());
        tv.setLabelProvider(new FileTreeLabelProvider());
        tv.setInput("root"); // pass a non-null that will be ignored    // When user checks the checkbox, toggle the preserve case attribute
        // of the label provider
        preserveCase.addSelectionListener(new SelectionAdapter() {
          public void widgetSelected(SelectionEvent event) {
            boolean preserveCase = ((Button) event.widget).getSelection();
            FileTreeLabelProvider ftlp = (FileTreeLabelProvider) tv
                .getLabelProvider();
            ftlp.setPreserveCase(preserveCase);
          }
        });
        return composite;
      }  /**
       * The application entry point
       * 
       * @param args the command line arguments
       */
      public static void main(String[] args) {
        new FileTree().run();
      }
    }
      

  7.   

    import java.io.*;import org.eclipse.jface.viewers.ITreeContentProvider;
    import org.eclipse.jface.viewers.Viewer;/**
     * This class provides the content for the tree in FileTree
     */
    public class FileTreeContentProvider implements ITreeContentProvider {
      /**
       * Gets the children of the specified object
       * 
       * @param arg0 the parent object
       * @return Object[]
       */
      public Object[] getChildren(Object arg0) {
        // Return the files and subdirectories in this directory
        return ((File) arg0).listFiles();
      }  /**
       * Gets the parent of the specified object
       * 
       * @param arg0 the object
       * @return Object
       */
      public Object getParent(Object arg0) {
        // Return this file's parent file
        return ((File) arg0).getParentFile();
      }  /**
       * Returns whether the passed object has children
       * 
       * @param arg0 the parent object
       * @return boolean
       */
      public boolean hasChildren(Object arg0) {
        // Get the children
        Object[] obj = getChildren(arg0);    // Return whether the parent has children
        return obj == null ? false : obj.length > 0;
      }  /**
       * Gets the root element(s) of the tree
       * 
       * @param arg0 the input data
       * @return Object[]
       */
      public Object[] getElements(Object arg0) {
        // These are the root elements of the tree
        // We don't care what arg0 is, because we just want all
        // the root nodes in the file system
        return File.listRoots();
      }  /**
       * Disposes any created resources
       */
      public void dispose() {
      // Nothing to dispose
      }  /**
       * Called when the input changes
       * 
       * @param arg0 the viewer
       * @param arg1 the old input
       * @param arg2 the new input
       */
      public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
      // Nothing to change
      }
    }
      

  8.   

    java_augur(听着音乐) 兄,
    这是标准的用法,没有定制显示或不显示CheckBox啊。呵呵。
      

  9.   

    final CheckboxTreeViewer tv = new CheckboxTreeViewer(composite);
    final TreeViewer tv = new TreeViewer(composite);
    一个是有,一个是没有。
    一共四个文件,一次只能贴三个,
    今天补全,你可能用不到,可能别人用得着。
    仔细理解一下,可能就会找到答案。
      

  10.   

    import java.io.*;
    import java.util.*;import org.eclipse.jface.viewers.ILabelProvider;
    import org.eclipse.jface.viewers.ILabelProviderListener;
    import org.eclipse.jface.viewers.LabelProviderChangedEvent;
    import org.eclipse.swt.graphics.Image;/**
     * This class provides the labels for the file tree
     */
    public class FileTreeLabelProvider implements ILabelProvider {
      // The listeners
      private List listeners;  // Images for tree nodes
      private Image file;
      private Image dir;  // Label provider state: preserve case of file names/directories
      boolean preserveCase;  /**
       * Constructs a FileTreeLabelProvider
       */
      public FileTreeLabelProvider() {
        // Create the list to hold the listeners
        listeners = new ArrayList();    // Create the images
        try {
          file = new Image(null, new FileInputStream("images/file.gif"));
          dir = new Image(null, new FileInputStream("images/directory.gif"));
        } catch (FileNotFoundException e) {
          // Swallow it; we'll do without images
        }
      }  /**
       * Sets the preserve case attribute
       * 
       * @param preserveCase the preserve case attribute
       */
      public void setPreserveCase(boolean preserveCase) {
        this.preserveCase = preserveCase;    // Since this attribute affects how the labels are computed,
        // notify all the listeners of the change.
        LabelProviderChangedEvent event = new LabelProviderChangedEvent(this);
        for (int i = 0, n = listeners.size(); i < n; i++) {
          ILabelProviderListener ilpl = (ILabelProviderListener) listeners.get(i);
          ilpl.labelProviderChanged(event);
        }
      }  /**
       * Gets the image to display for a node in the tree
       * 
       * @param arg0 the node
       * @return Image
       */
      public Image getImage(Object arg0) {
        // If the node represents a directory, return the directory image.
        // Otherwise, return the file image.
        return ((File) arg0).isDirectory() ? dir : file;
      }  /**
       * Gets the text to display for a node in the tree
       * 
       * @param arg0 the node
       * @return String
       */
      public String getText(Object arg0) {
        // Get the name of the file
        String text = ((File) arg0).getName();    // If name is blank, get the path
        if (text.length() == 0) {
          text = ((File) arg0).getPath();
        }    // Check the case settings before returning the text
        return preserveCase ? text : text.toUpperCase();
      }  /**
       * Adds a listener to this label provider
       * 
       * @param arg0 the listener
       */
      public void addListener(ILabelProviderListener arg0) {
        listeners.add(arg0);
      }  /**
       * Called when this LabelProvider is being disposed
       */
      public void dispose() {
        // Dispose the images
        if (dir != null) dir.dispose();
        if (file != null) file.dispose();
      }  /**
       * Returns whether changes to the specified property on the specified element
       * would affect the label for the element
       * 
       * @param arg0 the element
       * @param arg1 the property
       * @return boolean
       */
      public boolean isLabelProperty(Object arg0, String arg1) {
        return false;
      }  /**
       * Removes the listener
       * 
       * @param arg0 the listener to remove
       */
      public void removeListener(ILabelProviderListener arg0) {
        listeners.remove(arg0);
      }
    }
      

  11.   

    java_augur(听着音乐) 兄,
    这是The Definitive Guide to SWT and JFace一书的源码吧。我看了。问题是,我需要定制一个TREE,可以让它显示或不显示ITEM的复选框。呵呵。