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

📄 projectcreatordialog.java

📁 用Swing实现的CHM制作工具
💻 JAVA
字号:
package g2w.app.gchm.gui;

import g2w.app.gchm.GChm;
import g2w.app.gchm.lib.GWindowUtility;
import g2w.app.gchm.util.FileUtility;
import g2w.app.gchm.util.HTMUtility;
import g2w.app.gchm.util.ProjectUtility;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;

/**
 * The dialog used to create new project.
 * 
 * @author GreatGhoul
 * @version 014 2009-3-21 19:47:48
 */
public class ProjectCreatorDialog extends JDialog {
	/** The project to return. */
	private Project project;

	/** File chooser */
	private JFileChooser chooser;

	/** Used to display the project's name. */
	private JTextField projectName;

	/** Used to display the project's path. */
	private JTextField projectPath;

	/** Browse button. */
	private JButton browse;

	/** OK button */
	private JButton ok;

	/**
	 * Used to indicated whether to create the new porject in the workspace or
	 * not.
	 */
	private JCheckBox useWorkspace;

	/**
	 * Constructs a modal dialog to create a new project.
	 * 
	 * @param owner
	 *            The owner window.
	 */
	public ProjectCreatorDialog(JFrame owner) {
		super(owner, "创建CHM文档");
		initComponents();
	}

	/**
	 * Initializes all the components.
	 */
	private void initComponents() {
		// Initialize the file chooser.
		chooser = new JFileChooser(GChm.getProperty("Workspace"));
		chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

		// Configure the dialog.
		setModal(true);
		JPanel contentPane = (JPanel) getContentPane();
		contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
		contentPane.setBorder(BorderFactory.createEmptyBorder(10, 8, 10, 8));
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setSize(500, 150);
		setMinimumSize(getSize());
		GWindowUtility.bringToCenter(this);

		Box row1 = Box.createHorizontalBox();
		row1.add(new JLabel("工程名称"));
		row1.add(Box.createHorizontalStrut(2));
		projectName = new JTextField();
		projectName.getDocument().addDocumentListener(new DocumentListener() {
			@Override
			public void changedUpdate(DocumentEvent e) {
				ProjectCreatorDialog.this.projectNameChanged();
			}

			@Override
			public void insertUpdate(DocumentEvent e) {
				ProjectCreatorDialog.this.projectNameChanged();
			}

			@Override
			public void removeUpdate(DocumentEvent e) {
				ProjectCreatorDialog.this.projectNameChanged();
			}
		});
		row1.add(projectName);
		add(row1);

		add(Box.createVerticalStrut(5));

		Box row2 = Box.createHorizontalBox();
		row2.add(new JLabel("工程路径"));
		row2.add(Box.createHorizontalStrut(2));
		projectPath = new JTextField();
		projectPath.setEditable(false);
		row2.add(projectPath);
		row2.add(Box.createHorizontalStrut(2));
		browse = new JButton(new AbstractAction("浏览..") {
			@Override
			public void actionPerformed(ActionEvent evt) {
				browseProjectPath();
			}
		});
		row2.add(browse);
		add(row2);

		add(Box.createVerticalStrut(5));

		Box row3 = Box.createHorizontalBox();
		useWorkspace = new JCheckBox("使用工作空间");
		useWorkspace.addChangeListener(new ChangeListener() {
			@Override
			public void stateChanged(ChangeEvent evt) {
				useWorkspace(useWorkspace.isSelected());
			}
		});
		row3.add(useWorkspace);
		row3.add(Box.createHorizontalGlue());
		row3.add(new JButton(new AbstractAction("取消") {
			@Override
			public void actionPerformed(ActionEvent evt) {
				onCancel();
			}
		}));
		row3.add(Box.createHorizontalStrut(2));
		row3.add(ok = new JButton(new AbstractAction("确定") {
			@Override
			public void actionPerformed(ActionEvent evt) {
				onOK();
			}

		}));
		add(row3);

		useWorkspace.setSelected(true);
		validate();
	}

	/**
	 * Invoked when OK button clicked.
	 */
	private void onCancel() {
		dispose();
	}

	/**
	 * Incoked when Cancel button clicked.
	 */
	private void onOK() {
		String name = projectName.getText().trim();
		String path = projectPath.getText().trim();

		String filename = name + ".gchm";
		if (name.isEmpty() || filename.length() > 255 || !FileUtility.isValidFileName(filename)) {
			JOptionPane.showMessageDialog(GChm.instance, "工程名称必须是一个有效的文件夹名.");
			return;
		}

		ok.setEnabled(false);
		
		try {
			Document document = createProjectFile(name, path);
			if (document != null)
				project = new Project(document);
			dispose();
		} catch (JDOMException e) {
			JOptionPane.showMessageDialog(this, "创建工程失败,解析文件错误");
		} catch (IOException e) {
			JOptionPane.showMessageDialog(this, "创建工程失败,生成文件错误");
		} catch (Exception e) {
			JOptionPane.showMessageDialog(this, "创建工程失败,访问受限");
		} finally {
			ok.setEnabled(true);
		}
	}

	protected void browseProjectPath() {
		int state = chooser.showOpenDialog(this);
		File projectDir = chooser.getSelectedFile();
		if (projectDir != null && state == JFileChooser.APPROVE_OPTION) {
			projectPath.setText(projectDir.getAbsolutePath() + "\\");
		}
	}

	public Project showDialog() {
		setVisible(true);
		return this.project;
	}

	/**
	 * Used to decide whether to create projects in the workspace or not.
	 * 
	 * @param aFlag
	 *            Set true to use the workspace.
	 */
	private void useWorkspace(boolean aFlag) {
		browse.setEnabled(!aFlag);
		if (aFlag)
			projectNameChanged();
	}

	/**
	 * Invoked when the filed projectName's value is changed.
	 */
	private void projectNameChanged() {
		if (useWorkspace.isSelected()) {
			projectPath.setText(GChm.getProperty("Workspace")
					+ projectName.getText());
		}
	}

	/**
	 * Creates the project file. This method will create and return the xml
	 * project document using a folder and a title.
	 * 
	 * @param projectTitle
	 *            The title of the project, Also used as the name of the project
	 *            files.
	 * @param projectPath
	 *            The path of the source folder. If the folder dose not exist,
	 *            it will be created.
	 * @return The xml project document.
	 * @throws IOException
	 * @throws JDOMException
	 * @throws Exception
	 */
	public Document createProjectFile(String name, String path)
			throws JDOMException, IOException, Exception {
		// Get the project dir object.
		final File projectDir = new File(path);
		if (!projectDir.exists())
			projectDir.mkdirs();

		// Get the project file object.
		File projectFile = new File(projectDir, name + ".gchm");
		if (projectFile.exists()) {
			int state = JOptionPane.showConfirmDialog(GChm.instance, "文件\""
					+ projectFile.getAbsolutePath() + "\"已经存在,是否覆盖?");
			if (state == JOptionPane.OK_OPTION)
				projectFile.delete();
			else
				throw new Exception() {
				};
		}
		ok.setEnabled(false);
		projectFile.createNewFile();

		Document document = new Document();
		final Element root = new Element("CHMDocument");
		root.setAttribute("name", name);
		root.setAttribute("local", path);
		root.setAttribute("title", name);
		root.setAttribute("filename", name + ".chm");
		root.setAttribute("homepage", "");
		root.setAttribute("defaultpage", "");
		root.setAttribute("aboutpage", "");
		document.setRootElement(root);
		scan(projectDir, root, 1);
		ProjectUtility.storeDocument(document, projectFile);
		return ProjectUtility.getProjectFile(projectFile);
	}

	private void scan(File dir, Element elem, int depth) {
		try {
			if (depth > 4)
				return;
			setTitle(dir.getAbsolutePath());
			Iterator<File> fileIterator = FileUtility.getFilesByNameExtensions(
					dir, "htm", "html").iterator();
			while (fileIterator.hasNext()) {
				File file = fileIterator.next();
				String filePath = file.getAbsolutePath();
				setTitle(file.getName());
				Element topic = new Element("Topic");
				topic.setAttribute("name", HTMUtility.getHTMLTitle(filePath));
				topic.setAttribute("local", filePath);
				elem.addContent(topic);
			}

			Iterator<File> dirIterator = FileUtility.getFolders(dir).iterator();
			while (dirIterator.hasNext()) {
				File subDir = dirIterator.next();
				Element heading = new Element("Topic");
				heading.setAttribute("name", subDir.getName());
				heading.setAttribute("local", "");
				scan(subDir, heading, depth + 1);
				if (heading.getContentSize() > 0)
					elem.addContent(heading);
			}
		} catch (Exception e) {
			return;
		}
	}
}

⌨️ 快捷键说明

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