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

📄 browsedialog.java

📁 这个小软件( RealEditor )是同学一起编写的
💻 JAVA
字号:
package com.ecust.swing;

import javax.swing.*;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.util.*;

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.net.URL;

import javax.swing.tree.*;
import javax.swing.event.*;

public class BrowseDialog extends JDialog {

	/**
     * 
     */
    private static final long serialVersionUID = 9122233307844921409L;
    public final ImageIcon ICON_COMPUTER = new ImageIcon( getResources( "COMPUTER.gif" ) );
	public final ImageIcon ICON_DISK = new ImageIcon( getResources( "DISK.gif" ) );
	public final ImageIcon ICON_FOLDER = new ImageIcon( getResources( "FOLDER.gif" ) );
	public final ImageIcon ICON_EXPANDEDFOLDER = new ImageIcon( getResources( "EXPANDEDFOLDER.gif" ) );
	protected JTree  tree;
	protected DefaultTreeModel model;
	protected File directory;

	protected JTextField pathTextField;
	protected JButton newButton;
	protected JButton okButton;
	protected JButton cancelButton;
	
	
	protected DefaultMutableTreeNode selectedNode;

	DefaultMutableTreeNode top;
	
	public BrowseDialog(JDialog dialog, String title, boolean modal) {
		super(dialog, title, modal);
		setLayout(new BorderLayout());
		
		
		top = new DefaultMutableTreeNode(
				new IconData(ICON_COMPUTER, null, "Computer"));

		DefaultMutableTreeNode node;
		File[] roots = File.listRoots();
		for (int k=0; k<roots.length; k++)
		{
			node = new DefaultMutableTreeNode(new IconData(ICON_DISK, 
				null, new FileNode(roots[k])));
			top.add(node);
			node.add( new DefaultMutableTreeNode(new Boolean(true)));
		}

		model = new DefaultTreeModel(top);
		tree = new JTree(model);

                tree.putClientProperty("JTree.lineStyle", "Angled");

		TreeCellRenderer renderer = new 
			IconCellRenderer();
		tree.setCellRenderer(renderer);

		tree.addTreeExpansionListener(new 
			DirExpansionListener());

		tree.addTreeSelectionListener(new 
			DirSelectionListener());

		tree.getSelectionModel().setSelectionMode(
			TreeSelectionModel.SINGLE_TREE_SELECTION); 
		tree.setShowsRootHandles(true); 
		tree.setEditable(false);

		JLabel infoLabel = new JLabel("Choose a directory for the project contents:");
		JPanel treePanel = new JPanel(new BorderLayout());	           
		treePanel.add(infoLabel, BorderLayout.NORTH);
		
		JScrollPane s = new JScrollPane();
		s.getViewport().add(tree);
		treePanel.add(s, BorderLayout.CENTER);
		add(treePanel, BorderLayout.CENTER);
		
		
		JPanel panel = new JPanel(new GridLayout(2, 1));       //将folderPanel,buttonPanel放在一起
		
		JPanel folderPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		JLabel folderLabel = new JLabel("Path: ");		
		pathTextField = new JTextField("My Computer", 26);
		pathTextField.setEditable(false);
		folderPanel.add(folderLabel);
		folderPanel.add(pathTextField);
		panel.add(folderPanel);
		
		JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
		newButton = new JButton("New Folder");
		okButton = new JButton("OK");
		cancelButton = new JButton("Cancel");
		
		buttonPanel.add(newButton);
		buttonPanel.add(okButton);
		buttonPanel.add(cancelButton);
		panel.add(buttonPanel);
		
		add(panel, BorderLayout.SOUTH);
		
		newButton.addActionListener(
				new ActionListener() {
					public void actionPerformed(ActionEvent event) {
						String folderName = JOptionPane.showInputDialog("Input Folder Name:  ");
						
						String name = folderName;
						int count = 0;  //计算空格数
						for(count = 0; count < name.length() && name.charAt(count) == ' '; count++);
						name = name.substring(count);
						
						if(name.length() == 0) 
							JOptionPane.showMessageDialog(null, "Please Input Folder Name");	
						else {
							File newFile = new File(directory.getAbsolutePath());
							JFileChooser fc = new JFileChooser();
							if (name != null) {
				                File newDir = fc.getFileSystemView().createFileObject(newFile, name);
				                if (newDir == null || !newDir.mkdir()) {
				                    JOptionPane.showMessageDialog(null, "ee", "error", JOptionPane.ERROR_MESSAGE);
				                }
				                fc.rescanCurrentDirectory();
							}			
							DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(new IconData(ICON_FOLDER, null, name));
							model.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());	
							TreeNode[] nodes = model.getPathToRoot(newNode);
							TreePath path = new TreePath(nodes);
							tree.scrollPathToVisible(path);
							tree.validate();
						}

					}
				});
		
		okButton.addActionListener(
				new ActionListener() {
					public void actionPerformed(ActionEvent event) {
						if(directory == null) {
							JOptionPane.showMessageDialog(null, "Please Input Select a Path");
						} else {
							dispose();
						}
					}
				});
		
		cancelButton.addActionListener(
				new ActionListener() {
					public void actionPerformed(ActionEvent event) {
						directory = null;
						dispose();
					}
				});
		
		
		
		
		setSize(350, 400);
		setVisible(true);
	}
    
    private URL getResources( String filename ) {
        URL url = getClass().getResource( "Imgs/" + filename );
        return url;
    }
	
	public File getDirectory() {
		return directory;
	}
	
	DefaultMutableTreeNode getTreeNode(TreePath path)
	{
		return (DefaultMutableTreeNode)(path.getLastPathComponent());
	}


	FileNode getFileNode(DefaultMutableTreeNode node)
	{
		if (node == null)
			return null;
		Object obj = node.getUserObject();
		if (obj instanceof IconData)
			obj = ((IconData)obj).getObject();
		if (obj instanceof FileNode)
			return (FileNode)obj;
		else
			return null;
	}

	

	class DirExpansionListener implements TreeExpansionListener
	{
	    public void treeExpanded(TreeExpansionEvent event)
	    {
	        final DefaultMutableTreeNode node = getTreeNode(
	            event.getPath());
	        final FileNode fnode = getFileNode(node);

	        Thread runner = new Thread() 
	        {
	          public void run() 
	          {
	            if (fnode != null && fnode.expand(node)) 
	            {
	              Runnable runnable = new Runnable() 
	              {
	                public void run() 
	                {
	                   model.reload(node);
	                }
	              };
	              SwingUtilities.invokeLater(runnable);
	            }
	          }
	        };
	        runner.start();
	    }

	    public void treeCollapsed(TreeExpansionEvent event) {}
	}

	
	class DirSelectionListener 
		implements TreeSelectionListener 
	{
		public void valueChanged(TreeSelectionEvent event)
		{
			DefaultMutableTreeNode node = getTreeNode(event.getPath());
			FileNode fnode = getFileNode(node);

			if(fnode != null) {
				directory = fnode.getFile().getAbsoluteFile();
				pathTextField.setText(directory.getPath());	
				
				selectedNode = node;
			} else {
				directory = null;
				selectedNode = null;
			}
	
		}
	}

	public DefaultTreeModel getTreeModel() {
		return model;
	}

	public JTree getTree() {
		return tree;
	}
    
    class FileNode
    {
        protected File m_file;

        public FileNode(File file)
        {
            m_file = file;
        }

        public File getFile() 
        { 
            return m_file;
        }

        public String toString() 
        { 
            return m_file.getName().length() > 0 ? m_file.getName() : 
                m_file.getPath();
        }

        public boolean expand(DefaultMutableTreeNode parent)
        {
            DefaultMutableTreeNode flag = 
                (DefaultMutableTreeNode)parent.getFirstChild();
            if (flag==null)   // No flag
                return false;
            Object obj = flag.getUserObject();
            if (!(obj instanceof Boolean))
                return false;      // Already expanded

            parent.removeAllChildren();  // Remove Flag

            File[] files = listFiles();
            if (files == null)
                return true;

            Vector< FileNode > v = new Vector< FileNode >();

            for (int k=0; k<files.length; k++)
            {
                File f = files[k];
                if (!(f.isDirectory()))
                    continue;

                FileNode newNode = new FileNode(f);
                
                boolean isAdded = false;
                for (int i=0; i<v.size(); i++)
                {
                    FileNode nd = (FileNode)v.elementAt(i);
                    if (newNode.compareTo(nd) < 0)
                    {
                        v.insertElementAt(newNode, i);
                        isAdded = true;
                        break;
                    }
                }
                if (!isAdded)
                    v.addElement(newNode);
            }

            for (int i=0; i<v.size(); i++)
            {
                FileNode nd = (FileNode)v.elementAt(i);
                IconData idata = new IconData( ICON_FOLDER, 
                        ICON_EXPANDEDFOLDER, nd);
                DefaultMutableTreeNode node = new 
                    DefaultMutableTreeNode(idata);
                parent.add(node);
                    
                if (nd.hasSubDirs())
                    node.add(new DefaultMutableTreeNode( 
                        new Boolean(true) ));
            }

            return true;
        }

        public boolean hasSubDirs()
        {
            File[] files = listFiles();
            if (files == null)
                return false;
            for (int k=0; k<files.length; k++)
            {
                if (files[k].isDirectory())
                    return true;
            }
            return false;
        }
        
        public int compareTo(FileNode toCompare)
        { 
            return  m_file.getName().compareToIgnoreCase(
                toCompare.m_file.getName() ); 
        }

        protected File[] listFiles()
        {
            if (!m_file.isDirectory())
                return null;
            try
            {
                return m_file.listFiles();
            }
            catch (Exception ex)
            {
                JOptionPane.showMessageDialog(null, 
                    "Error reading directory "+m_file.getAbsolutePath(),
                    "Warning", JOptionPane.WARNING_MESSAGE);
                return null;
            }
        }
    }
}

class IconCellRenderer extends JLabel implements TreeCellRenderer {
	/**
     * 
     */
    private static final long serialVersionUID = -2914882552113180293L;
    protected Color m_textSelectionColor;
	protected Color m_textNonSelectionColor;
	protected Color m_bkSelectionColor;
	protected Color m_bkNonSelectionColor;
	protected Color m_borderSelectionColor;

	protected boolean m_selected;

	public IconCellRenderer()
	{
		super();
		m_textSelectionColor = UIManager.getColor(
			"Tree.selectionForeground");
		m_textNonSelectionColor = UIManager.getColor(
			"Tree.textForeground");
		m_bkSelectionColor = UIManager.getColor(
			"Tree.selectionBackground");
		m_bkNonSelectionColor = UIManager.getColor(
			"Tree.textBackground");
		m_borderSelectionColor = UIManager.getColor(
			"Tree.selectionBorderColor");
		setOpaque(false);
	}

	public Component getTreeCellRendererComponent(JTree tree, 
		Object value, boolean sel, boolean expanded, boolean leaf, 
		int row, boolean hasFocus) 
		
	{
		DefaultMutableTreeNode node = 
			(DefaultMutableTreeNode)value;
		Object obj = node.getUserObject();
		setText(obj.toString());

                if (obj instanceof Boolean)
                  setText("Retrieving data...");

		if (obj instanceof IconData)
		{
			IconData idata = (IconData)obj;
			if (expanded)
				setIcon(idata.getExpandedIcon());
			else
				setIcon(idata.getIcon());
		}
		else
			setIcon(null);

		setFont(tree.getFont());
		setForeground(sel ? m_textSelectionColor : 
			m_textNonSelectionColor);
		setBackground(sel ? m_bkSelectionColor : 
			m_bkNonSelectionColor);
		m_selected = sel;
		return this;
	}
    
	public void paintComponent(Graphics g) 
	{
		Color bColor = getBackground();
		Icon icon = getIcon();

		g.setColor(bColor);
		int offset = 0;
		if(icon != null && getText() != null) 
			offset = (icon.getIconWidth() + getIconTextGap());
		g.fillRect(offset, 0, getWidth() - 1 - offset,
			getHeight() - 1);
		
		if (m_selected) 
		{
			g.setColor(m_borderSelectionColor);
			g.drawRect(offset, 0, getWidth()-1-offset, getHeight()-1);
		}
		super.paintComponent(g);
    }
}

class IconData
{
	protected Icon   m_icon;
	protected Icon   m_expandedIcon;
	protected Object m_data;

	public IconData(Icon icon, Object data)
	{
		m_icon = icon;
		m_expandedIcon = null;
		m_data = data;
	}

	public IconData(Icon icon, Icon expandedIcon, Object data)
	{
		m_icon = icon;
		m_expandedIcon = expandedIcon;
		m_data = data;
	}

	public Icon getIcon() 
	{ 
		return m_icon;
	}

	public Icon getExpandedIcon() 
	{ 
		return m_expandedIcon!=null ? m_expandedIcon : m_icon;
	}

	public Object getObject() 
	{ 
		return m_data;
	}

	public String toString() 
	{ 
		return m_data.toString();
	}
    
    

}


⌨️ 快捷键说明

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