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

📄 notepad_jtreebasic.java

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

import javax.swing.tree.*;
import javax.swing.filechooser.*;
import javax.swing.event.*;
import java.awt.Cursor;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.io.*;
import java.awt.*;
import javax.swing.*;

import java.util.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

/**
 * @value 树形结构的实现
 * @version 1.0
 */
public class Notepad_JTreeBasic extends JTree implements
		TreeExpansionListener, TreeSelectionListener, MouseListener {
	private static final long serialVersionUID = 7211417824936567713L;
	private JMenuItem copy = null, paste = null, cut = null, per = null,
	refresh = null, find = null, new_file = null; // 右键功能菜单
	private JPopupMenu jpm = null;  //右键菜单
	protected DefaultTreeModel treeModel;

	protected FileSystemView fileSystemView; // 建立文件系统视类对象

	protected FileNode root;

	public Notepad_JTreeBasic() {
		Font myFont = new Font("宋体", 11, 12);
		fileSystemView = FileSystemView.getFileSystemView();
		root = new FileNode(fileSystemView.getRoots()[0]);
		root.explore();
		treeModel = new DefaultTreeModel(root);
		this.setModel(treeModel); // 设定树形菜单
		this.setEditable(false);
		this.addTreeExpansionListener(this); // 打开/关闭节点事件
		this.addTreeSelectionListener(this); // 选择的事件
		this.setCellRenderer(new MyTreeCellRenderer()); // 生成图标
		this.setFont(myFont);
		this.setRootVisible(true);
		this.setRowHeight(18);
		this.addMouseListener(this);
	}

	// 图标生成类
	protected class MyTreeCellRenderer extends JPanel implements
		TreeCellRenderer ,ActionListener{
		JCheckBox check = new JCheckBox();
		
		BorderLayout borderLayout1 = new BorderLayout();

		JLabel label = new JLabel();

		public MyTreeCellRenderer() {
			this.setLayout(null);            
			//this.add(check);
			this.add(label);
			jpm = getJPopuMenu();
			//check.setBackground(UIManager.getColor("Tree.textBackground"));
			label.setBackground(UIManager.getColor("Tree.textBackground"));
			this.setBackground(UIManager.getColor("Tree.textBackground"));

		}
		/**
		 * 得到右键菜单
		 * @return PopupMenu
		 * @author 小豆包
		 * @time 08/1/4
		 */
		public JPopupMenu getJPopuMenu() {
			JPopupMenu pm1 = new JPopupMenu();
			pm1.add(new_file = new JMenuItem("新建"));
			pm1.add(refresh = new JMenuItem("刷新"));
			pm1.addSeparator();
			pm1.add(cut = new JMenuItem("剪切"));
			pm1.addSeparator();
			pm1.add(find = new JMenuItem("查找"));			
			
			cut.setAccelerator(KeyStroke.getKeyStroke('X', InputEvent.CTRL_MASK));
			find.setAccelerator(KeyStroke.getKeyStroke('F', InputEvent.SHIFT_MASK));
			new_file.setAccelerator(KeyStroke
					.getKeyStroke('C', InputEvent.SHIFT_MASK));
			refresh.setAccelerator(KeyStroke.getKeyStroke('R',
					InputEvent.SHIFT_MASK));			
			cut.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					/**
					 * 事件处理代码
					 */
				}
			});
			return pm1;
		}
		public Dimension getPreferredSize() {
			Dimension checkDimension = check.getPreferredSize();
			Dimension labelDimension = label.getPreferredSize();
			return new Dimension(
					checkDimension.width + labelDimension.width,
					(checkDimension.height < labelDimension.height ? labelDimension.height
							: checkDimension.height));
		}

		public Component getTreeCellRendererComponent(JTree tree, Object value,
				boolean sel, boolean expanded, boolean leaf, int row,
				boolean hasFocus) {
			String stringValue = tree.convertValueToText(value, sel, expanded,
					leaf, row, hasFocus);
			setEnabled(tree.isEnabled());
			label.setFont(tree.getFont());
			check.setSelected(((FileNode) value).isSelected());
			// 设置图标为系统的文件类型图标
			FileSystemView fileSystemView = FileSystemView.getFileSystemView();
			label.setIcon(fileSystemView.getSystemIcon(((FileNode) value)
					.getFile()));
			label.setText(stringValue);
			return this;
		}

		public void doLayout() {
			Dimension checkDimension = check.getPreferredSize();
			Dimension labelDimension = label.getPreferredSize();
			int checkY = 0;
			int labelY = 0;
			if (checkDimension.height > labelDimension.height) {
				labelY = (checkDimension.height - labelDimension.height) / 2;
			} else {
				checkY = (labelDimension.height - checkDimension.height) / 2;
			}
			check.setLocation(0, checkY);
			check.setBounds(0, checkY, checkDimension.width,
					checkDimension.height);
			label.setLocation(checkDimension.width, labelY);
			label.setBounds(checkDimension.width, labelY, labelDimension.width,
					labelDimension.height);
		}
		public void actionPerformed(ActionEvent arg0) {
			
			
		}

	}

	// 节点张开事件
	public void treeExpanded(TreeExpansionEvent event) {
		// 判断是否是叶节点
		// if (this.getLastSelectedPathComponent() == null) {
		// System.out.println("ok");
		// return;
		// }
		setCursor(new Cursor(Cursor.WAIT_CURSOR));
		TreePath path = event.getPath();		
		FileNode node = (FileNode) path.getLastPathComponent();
		node.explore();
		treeModel.nodeStructureChanged(node);
		this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

	}

	// 节点闭合事件
	public void treeCollapsed(TreeExpansionEvent event) {

	}

	// 文件节点类
	protected class FileNode extends DefaultMutableTreeNode {
		private static final long serialVersionUID = -6749139017001603418L;

		private boolean isSelected = false;

		private boolean explored = false;

		public FileNode(File file) {
			this(file, false);
		}

		public FileNode(File file, boolean bool) {
			super(file);
			this.isSelected = bool;
		}

		//
		public boolean isSelected() {
			return isSelected;
		}

		public void setSelected(boolean isSelected) {
			this.isSelected = isSelected;
			if (children != null) {
				Enumeration enum1 = children.elements();
				while (enum1.hasMoreElements()) {
					FileNode node = (FileNode) enum1.nextElement();
					node.setSelected(isSelected);
				}
			}
		}

		//
		public boolean getAllowsChildren() {
			return isDirectory();
		}

		public boolean isLeaf() {
			return !isDirectory();
		}

		public File getFile() {
			return (File) getUserObject();
		}

		public boolean isExplored() {
			return explored;
		}

		public void setExplored(boolean b) {
			explored = b;
		}

		public boolean isDirectory() {
			return getFile().isDirectory();
		}

		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;
		}

		public void explore() {
			if (!isExplored()) {
				File file = getFile();
				File[] children = file.listFiles();
				if (children == null || children.length == 0)
					return;
				for (int i = 0; i < children.length; ++i) {
					File f = children[i];
					if (f.isDirectory())
						add(new FileNode(children[i], isSelected));
				}
				explored = true;
			}
		}

	}

	/**
	 * 选择节点触发的事件 继承或是直接引用需要重新写此方法
	 * @param e
	 */
	public void valueChanged(TreeSelectionEvent e) {
		// 文件路径
		String sFilePath = "";
		Object myobj = this.getLastSelectedPathComponent();
		if (myobj != null) {
			sFilePath = ((File) (((DefaultMutableTreeNode) (myobj))
					.getUserObject())).getPath();
		}		
	}

	public void mouseClicked(MouseEvent e) {
		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);
			TreePath path = this.getPathForRow(row);
			if (path != null) {
				FileNode node = (FileNode) path.getLastPathComponent();
				boolean isSelected = !(node.isSelected());
				node.setSelected(isSelected);
				((DefaultTreeModel) this.getModel()).nodeChanged(node);
			}
		}

	}

   /**
    * @value 右键菜单的实现部分
    */
	
		public void mousePressed(MouseEvent e) {
			Component parner = e.getComponent();// 
			if (e.getButton() == MouseEvent.BUTTON3) {
				int x = e.getX();
				int y = e.getY(); // 获得鼠标在父组件上的坐标
				Dimension parentSize = parner.getSize(); // 返回父组件的大小
				Dimension d = jpm.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);
				jpm.show(parner, x, y);
			}
		}
		
	


	public void mouseReleased(MouseEvent e) {
	}


	public void mouseEntered(MouseEvent e) {
	}


	public void mouseExited(MouseEvent e) {
		
	}
	 
}

⌨️ 快捷键说明

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