⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 notepad_tree.java

📁 java 编写的代码
💻 JAVA
字号:
package com.edu.sccp.snail.notepad.view;

import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.util.Enumeration;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;
public class Notepad_Tree extends JTree  implements TreeExpansionListener, TreeSelectionListener, MouseListener{

	private static final long serialVersionUID = 1L;
	DefaultTreeModel treeModel;
	FileSystemView fileView;
	FileRoot root;
	File right_Click_file = null;
	Notepad_Main parent_frame = null;
	JPopupMenu pm = null; // 弹出菜单
	JMenuItem newfile = null, openfile = null, copy = null, paste = null, cut = null, per = null,
			refresh = null, find = null, change = null; // 右键功能菜单
	public Notepad_Tree(Notepad_Main parent){
		this.parent_frame = parent;  //
	    Font myFont = new Font("宋体", 11, 12);
		fileView = FileSystemView.getFileSystemView();
		root = new FileRoot(fileView.getRoots()[0]);
		root.Child();
		pm = getJPopuMenu();   //右键菜单的初始化
		treeModel = new DefaultTreeModel(root);
		this.setModel(treeModel);
		this.addTreeExpansionListener(this);//树扩展或折叠某一节点时获得通知的侦听器
		this.addTreeSelectionListener(this);//对 TreeSelection 事件的侦听器。
		this.setCellRenderer(new SetInco());
	    this.setFont(myFont);
	    this.setRootVisible(true);
	    this.setRowHeight(18);
	    this.addMouseListener(this);
	}
	
	/**
	 * 得到一个右键菜单
	 * @author 小豆包
	 * @time 08/1/8
	 */
	
	/**
	 * 得到右键菜单
	 * @return PopupMenu
	 * @author 小豆包
	 * @time 08/1/4
	 */
	public JPopupMenu getJPopuMenu() {
		JPopupMenu pm1 = new JPopupMenu();
		pm1.add(newfile = new JMenuItem("新建"));
		pm1.add(openfile = new JMenuItem("打开"));
		pm1.addSeparator();
		pm1.add(refresh = new JMenuItem("刷新"));
		pm1.addSeparator();
		pm1.add(cut = new JMenuItem("剪切"));
		pm1.add(copy = new JMenuItem("复制"));
		pm1.add(paste = new JMenuItem("粘贴"));
		pm1.addSeparator();
		pm1.add(find = new JMenuItem("查找"));
		pm1.add(change = new JMenuItem("替换"));
		pm1.addSeparator();
		pm1.add(per = new JMenuItem("属性"));
		newfile.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_MASK));
		openfile.setAccelerator(KeyStroke.getKeyStroke('O', InputEvent.CTRL_MASK));
		copy.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_MASK));
		paste.setAccelerator(KeyStroke.getKeyStroke('V', InputEvent.CTRL_MASK));
		cut.setAccelerator(KeyStroke.getKeyStroke('X', InputEvent.CTRL_MASK));
		find.setAccelerator(KeyStroke.getKeyStroke('F', InputEvent.SHIFT_MASK));
		change.setAccelerator(KeyStroke
				.getKeyStroke('C', InputEvent.SHIFT_MASK));
		refresh.setAccelerator(KeyStroke.getKeyStroke('R',
				InputEvent.SHIFT_MASK));
		per.setAccelerator(KeyStroke.getKeyStroke('P', InputEvent.ALT_MASK));
		
		newfile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				/**
				 * 处理事件
				 */
				new Notepad_TreeNewFile(parent_frame,right_Click_file);
				
				
			}
		});
		
		
		openfile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				/**
				 * 处理事件
				 */
		    new Notepad_TreeOpenFile(parent_frame,right_Click_file);
				
				
			}
		});
		
		copy.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				/**
				 * 处理事件
				 */
				
			}
		});
		paste.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				/**
				 * 处理代码
				 */
			}
		});
		cut.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				/**
				 * 处理代码
				 */
			}
		});
		return pm1;
	}
	
	
	
	/**
	 * TreeCellRenderer
	 * 定义针对显示树节点的对象的要求
	 */
	class SetInco extends JPanel implements TreeCellRenderer{
	
		private static final long serialVersionUID = 1L;
		JLabel label = new JLabel();
		public SetInco(){
		      this.setLayout(null);
		      this.add(label);
		      label.setBackground(UIManager.getColor("Tree.textBackground"));
		      this.setBackground(UIManager.getColor("Tree.textBackground"));
		}
		//Dimension 类封装单个对象中组件的宽度和高度(精确到整数)。	
		public Dimension getPreferredSize(){
		      Dimension labelDimension = label.getPreferredSize();
		      return new Dimension(labelDimension.width,
		                            labelDimension.height);
		}	
		//是一个具有图形表示能力的对象,可在屏幕上显示,并可与用户进行交互
		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());
		      label.setFont(tree.getFont());
//		      checkBox.setSelected( ( (FileRoot) value).Selection());
		      //设置图标为系统的文件类型图标
		      FileSystemView fileSystemView = FileSystemView.getFileSystemView();
		      label.setIcon(fileSystemView.getSystemIcon( ( (FileRoot) value).getFile()));
		      label.setText(stringValue);
		      return this;
		}
	    public void doLayout() {
	        Dimension labelDimension = label.getPreferredSize();
	        int labelY = 0;
	        label.setLocation(0,labelY);
	        label.setBounds(0, labelY, labelDimension.width,
	                        labelDimension.height);
	    }
	}
	// 每当树中的一个项被折叠时调用
	public void treeCollapsed(TreeExpansionEvent arg0) {

		
	}
	//每当树中的一个项被扩展时调用
	public void treeExpanded(TreeExpansionEvent e) {
		this.setCursor(new Cursor(Cursor.WAIT_CURSOR));//Cursor 是一个封装鼠标光标的位图表示形式的类
		TreePath path = e.getPath(); //表示节点的路径
		FileRoot fileroot = (FileRoot)path.getLastPathComponent();//返回此路径的最后一个组件
		fileroot.Child();
		/**
		 * nodeStructureChanged 方法:
		 * 如果完全更改了节点的子节点、子节点的子节点、依此类推,则调用此方法。
         *调用此方法将发布 treeStructureChanged 事件
		 */
		treeModel.nodeStructureChanged(fileroot); 
		this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
	}
	//当 TreeSelectionModel 中的选择发生更改时调用
	public void valueChanged(TreeSelectionEvent arg0) {
		String filePath = "";
		Object object = this.getLastSelectedPathComponent();//返回当前选择的第一个节点中的最后一个路径组件。
		if(object != null){
			filePath = ((File)(((DefaultMutableTreeNode)(object)).getUserObject())).getPath();
			
		}
	}
	public void mouseClicked(MouseEvent e) {	
		 FileRoot node = null;
		 TreePath path = null;
		 String str = "";
		int count = e.getClickCount();
		    if (count != 1) {
		      //System.out.println(count);
		    }
		    else {
		      int x = e.getX();
		      int y = e.getY();
		      int row = this.getRowForLocation(x, y);
		      path = this.getPathForRow(row);
		      if (path != null) {
		    	 node = (FileRoot) path.getLastPathComponent();
		       if(node.isLeaf())
		       {	    	  
		    		   File file = node.getFile();
		               /**
		                * 传过去创建一个新的文件 然后加到主窗体中
		                */ 		    		 
		    		  new Notepad_TreeOpenFile(parent_frame,file);			    	  
		       }
		       else
		       {    boolean isSelected = ! (node.Selection());
			        node.setSelected(isSelected);
			       ( (DefaultTreeModel)this.getModel()).nodeChanged(node);
		       }
		      }
		    }
	}
	public void mouseEntered(MouseEvent arg0) {		
	}
	public void mouseExited(MouseEvent arg0) {		
	}
	public void mousePressed(MouseEvent e) {		
		/**
		 * 右键菜单处理
		 */
		Component parent = e.getComponent();
//////////////////////////////////////////////////////////////////////////////////
		 FileRoot node = null;
		 TreePath path = null;		
		      int x1 = e.getX();
		      int y1 = e.getY();
		      int row = this.getRowForLocation(x1, y1);
		      path = this.getPathForRow(row);
		      if (path != null) {
		    	 node = (FileRoot) path.getLastPathComponent();
		       if(node.isLeaf())
		       {	    	  
		    	   right_Click_file = node.getFile(); 		    	      	  
		       }}	
//////////////////////////////////////////////////////////////////////////////////		
		
		if (e.getButton() == MouseEvent.BUTTON3) {
			int x = e.getX();
			int y = e.getY(); // 获得鼠标在父组件上的坐标
			Dimension parentSize = parent.getSize(); // 返回父组件的大小
			Dimension d = pm.getSize();
			y = ((parentSize.height - y) - d.height) > 0 ? y
					: (parentSize.height - d.height); // 如果坐标显示不开 则自动定位
			x = ((parentSize.width - x) - d.width) > 0 ? x
					: (parentSize.width - d.width);
			pm.show(parent, x, y);
		}
		
	}
	public void mouseReleased(MouseEvent arg0) {		
	}

	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	
}
	//文件节点类
class FileRoot extends DefaultMutableTreeNode{
	boolean isExpanded = false;//不展开路径标识的节点
	boolean isSelection = false;//该选择当前不为空
	public FileRoot(File files){
		this(files,false);
	}
	public FileRoot(File files, boolean b) {
		
		  super(files);
	      this.isSelection= b;
	}
	public boolean Selection(){
		return isSelection;
		
	}
	 public void setExplored(boolean b) {
		 isExpanded = b;
	    }
	 public boolean Expanded(){
		return isExpanded;
	 }
	  public boolean isDirectory() {
	      return getFile().isDirectory();
	    }
	 public File getFile(){
			return (File) getUserObject();
	 }
	   public boolean isLeaf() {
	        return !isDirectory();
	   }
	    public boolean getAllowsChildren() {
	        return isDirectory();
	      }  
	  public void setSelected(boolean isSelection) {
	      this.isSelection = isSelection;
	      if (children != null) {
	        Enumeration enum = children.elements();
	        while (enum.hasMoreElements()) {
	          FileRoot node = (FileRoot) enum.nextElement();
	          node.setSelected(isSelection);
	        }
	      }
	  }
	public void Child(){
	      if (!Expanded()) {
	         File file = getFile();
	         File[] children = file.listFiles();
	        //  String[] children =file.list(new FilenameFilter(){
	        	//  public boolean accept(File dir,String n){
						//String f =file.getName();
				//		return true;
				//	}
	        	  
	        //  });
	          if (children == null || children.length == 0)
	            return;
	          for (int i = 0; i < children.length; ++i) {
	             File f = children[i];
	             add(new FileRoot(f, isSelection));
	          }
	          isExpanded = true;
	        }
	      }
	public String toString() {
	      File file = (File) getUserObject();
	      String filename = file.toString();
	      int index = filename.lastIndexOf(File.separator);
	      return (index != -1 && index != filename.length() - 1)? filename.substring(index + 1) : filename;
	    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -