Java Swing JTree

Java Swing应用:JTree实现部门和员工管理
这个Java Swing应用展示了如何使用JTree组件管理部门和员工数据。用户可以添加、删除和保存部门及员工信息,数据存储在文件`jtree_employee.dat`中。应用包含部门详情和员工详情面板,支持输入验证和树形结构的展开操作。
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package jtreeapp;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import jtreeapp.Model.Department;
import jtreeapp.Model.Employee;

/**
 *
 * @author thienlh
 */
public class JTreeForm extends javax.swing.JFrame {

	/**
	 * Creates new form JTreeForm
	 */
	String fileName = "jtree_employee.dat";
	DefaultMutableTreeNode root = null; // Root node
	DefaultMutableTreeNode currentDepNode = null; // Department node
	DefaultMutableTreeNode currentEmpNode = null; // Employee node
	boolean addNewDep = false;
	boolean addNewEmp = false;

	// Constructor
	public JTreeForm() {
		initComponents();
		this.setSize(629, 509); // WTF is this??
		root = (DefaultMutableTreeNode) this.treeDepartment.getModel().getRoot();
		loadData();
		TreePath path = new TreePath(root); // Expanding the tree
		treeDepartment.expandPath(path);
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated
	// Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		jScrollPane1 = new javax.swing.JScrollPane();
		treeDepartment = new javax.swing.JTree();
		pnlDeppartment = new javax.swing.JPanel();
		jLabel1 = new javax.swing.JLabel();
		jLabel2 = new javax.swing.JLabel();
		txtDepID = new javax.swing.JTextField();
		txtDepName = new javax.swing.JTextField();
		btnDepNew = new javax.swing.JButton();
		btnDepSave = new javax.swing.JButton();
		btnDepRemove = new javax.swing.JButton();
		pnlEmployee = new javax.swing.JPanel();
		jLabel3 = new javax.swing.JLabel();
		jLabel4 = new javax.swing.JLabel();
		jLabel5 = new javax.swing.JLabel();
		txtEmpID = new javax.swing.JTextField();
		txtEmpName = new javax.swing.JTextField();
		txtEmpSalary = new javax.swing.JTextField();
		btnEmpNew = new javax.swing.JButton();
		btnEmpSave = new javax.swing.JButton();
		btnEmpRemove = new javax.swing.JButton();
		jLabel6 = new javax.swing.JLabel();
		jLabel7 = new javax.swing.JLabel();
		txtEmpEmail = new javax.swing.JTextField();
		txtEmpAdrs = new javax.swing.JTextField();
		btnSave2File = new javax.swing.JButton();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
		setTitle("Department Detail");
		setPreferredSize(new java.awt.Dimension(610, 460));

		javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("Department");
		treeDepartment.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
		treeDepartment.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				treeDepartmentMouseClicked(evt);
			}
		});
		jScrollPane1.setViewportView(treeDepartment);

		pnlDeppartment.setBorder(javax.swing.BorderFactory.createTitledBorder("Department Detail"));

		jLabel1.setText("ID:");

		jLabel2.setText("Name:");

		btnDepNew.setText("New");
		btnDepNew.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnDepNewActionPerformed(evt);
			}
		});

		btnDepSave.setText("Save");
		btnDepSave.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnDepSaveActionPerformed(evt);
			}
		});

		btnDepRemove.setText("Remove");
		btnDepRemove.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnDepRemoveActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout pnlDeppartmentLayout = new javax.swing.GroupLayout(pnlDeppartment);
		pnlDeppartment.setLayout(pnlDeppartmentLayout);
		pnlDeppartmentLayout.setHorizontalGroup(pnlDeppartmentLayout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(pnlDeppartmentLayout.createSequentialGroup()
						.addGroup(pnlDeppartmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
								.addGroup(pnlDeppartmentLayout.createSequentialGroup().addGap(7, 7, 7)
										.addComponent(btnDepNew).addGap(12, 12, 12)
										.addComponent(btnDepRemove, javax.swing.GroupLayout.PREFERRED_SIZE, 94,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addGap(6, 6, 6).addComponent(btnDepSave,
												javax.swing.GroupLayout.PREFERRED_SIZE, 76,
												javax.swing.GroupLayout.PREFERRED_SIZE))
								.addGroup(pnlDeppartmentLayout.createSequentialGroup().addContainerGap()
										.addGroup(pnlDeppartmentLayout
												.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
												.addGroup(pnlDeppartmentLayout.createSequentialGroup()
														.addComponent(jLabel1).addGap(28, 28, 28).addComponent(txtDepID,
																javax.swing.GroupLayout.PREFERRED_SIZE, 212,
																javax.swing.GroupLayout.PREFERRED_SIZE))
												.addGroup(pnlDeppartmentLayout.createSequentialGroup()
														.addComponent(jLabel2).addGap(6, 6, 6).addComponent(txtDepName,
																javax.swing.GroupLayout.PREFERRED_SIZE, 212,
																javax.swing.GroupLayout.PREFERRED_SIZE)))))
						.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
		pnlDeppartmentLayout.setVerticalGroup(pnlDeppartmentLayout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(pnlDeppartmentLayout.createSequentialGroup().addContainerGap()
						.addGroup(pnlDeppartmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
								.addGroup(pnlDeppartmentLayout.createSequentialGroup().addGap(6, 6, 6)
										.addComponent(jLabel1))
								.addComponent(txtDepID, javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
						.addGap(18, 18, 18)
						.addGroup(pnlDeppartmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
								.addGroup(pnlDeppartmentLayout.createSequentialGroup().addGap(6, 6, 6)
										.addComponent(jLabel2))
								.addComponent(txtDepName, javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
						.addGap(18, 18, 18)
						.addGroup(pnlDeppartmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
								.addComponent(btnDepNew).addComponent(btnDepRemove).addComponent(btnDepSave))
						.addContainerGap()));

		pnlEmployee.setBorder(javax.swing.BorderFactory.createTitledBorder("Employee Detail"));

		jLabel3.setText("ID:");

		jLabel4.setText("Name:");

		jLabel5.setText("Salary:");

		btnEmpNew.setText("New");
		btnEmpNew.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnEmpNewActionPerformed(evt);
			}
		});

		btnEmpSave.setText("Save");
		btnEmpSave.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnEmpSaveActionPerformed(evt);
			}
		});

		btnEmpRemove.setText("Remove");
		btnEmpRemove.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnEmpRemoveActionPerformed(evt);
			}
		});

		jLabel6.setText("Email:");

		jLabel7.setText("Address:");

		javax.swing.GroupLayout pnlEmployeeLayout = new javax.swing.GroupLayout(pnlEmployee);
		pnlEmployee.setLayout(pnlEmployeeLayout);
		pnlEmployeeLayout.setHorizontalGroup(pnlEmployeeLayout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(pnlEmployeeLayout.createSequentialGroup().addContainerGap().addGroup(pnlEmployeeLayout
						.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(pnlEmployeeLayout.createSequentialGroup().addComponent(btnEmpNew).addGap(18, 18, 18)
								.addComponent(btnEmpRemove, javax.swing.GroupLayout.PREFERRED_SIZE, 93,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(btnEmpSave).addGap(0, 0, Short.MAX_VALUE))
						.addGroup(pnlEmployeeLayout.createSequentialGroup()
								.addGroup(pnlEmployeeLayout
										.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
										.addGroup(pnlEmployeeLayout.createSequentialGroup().addGroup(pnlEmployeeLayout
												.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
												.addComponent(jLabel3).addComponent(jLabel4).addComponent(jLabel5))
												.addGap(25, 25, 25)
												.addGroup(pnlEmployeeLayout
														.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
														.addComponent(txtEmpID,
																javax.swing.GroupLayout.Alignment.TRAILING)
														.addComponent(txtEmpName).addComponent(txtEmpSalary)))
										.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlEmployeeLayout
												.createSequentialGroup()
												.addGroup(pnlEmployeeLayout
														.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
														.addComponent(jLabel6).addComponent(jLabel7))
												.addPreferredGap(
														javax.swing.LayoutStyle.ComponentPlacement.RELATED,
														javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
												.addGroup(pnlEmployeeLayout
														.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING,
																false)
														.addComponent(txtEmpEmail, javax.swing.GroupLayout.DEFAULT_SIZE,
																201, Short.MAX_VALUE)
														.addComponent(txtEmpAdrs))))
								.addGap(6, 6, 6)))));
		pnlEmployeeLayout.setVerticalGroup(pnlEmployeeLayout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(pnlEmployeeLayout.createSequentialGroup().addContainerGap()
						.addGroup(pnlEmployeeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(jLabel3).addComponent(txtEmpID, javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addGroup(pnlEmployeeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(jLabel4).addComponent(txtEmpName, javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addGroup(pnlEmployeeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(jLabel6).addComponent(txtEmpEmail, javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addGroup(pnlEmployeeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(jLabel7).addComponent(txtEmpAdrs, javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
						.addGap(7, 7, 7)
						.addGroup(pnlEmployeeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(jLabel5).addComponent(txtEmpSalary,
										javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.PREFERRED_SIZE))
						.addGap(18, 18, 18)
						.addGroup(pnlEmployeeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(btnEmpNew).addComponent(btnEmpSave).addComponent(btnEmpRemove))));

		btnSave2File.setText("Save to file");
		btnSave2File.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnSave2FileActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(layout.createSequentialGroup().addContainerGap()
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
								.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 294,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addComponent(btnSave2File, javax.swing.GroupLayout.PREFERRED_SIZE, 294,
										javax.swing.GroupLayout.PREFERRED_SIZE))
						.addGap(6, 6, 6)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
								.addComponent(pnlEmployee, javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
								.addComponent(pnlDeppartment, javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
						.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
		layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout
				.createSequentialGroup().addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
				.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
						.addGroup(layout.createSequentialGroup()
								.addComponent(pnlDeppartment, javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
								.addGap(6, 6, 6).addComponent(pnlEmployee, javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
						.addGroup(layout.createSequentialGroup()
								.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 355,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(btnSave2File, javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
				.addContainerGap()));

		pack();
		setLocationRelativeTo(null);
	}// </editor-fold>//GEN-END:initComponents

	private void btnDepNewActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnDepNewActionPerformed
		// Clear junk data
		this.addNewDep = true;
		this.txtDepID.setText("");
		this.txtDepName.setText("");
		this.txtEmpID.setText("");
		this.txtEmpName.setText("");
		this.txtEmpEmail.setText("");
		this.txtEmpAdrs.setText("");
		this.txtEmpSalary.setText("");
		this.txtDepID.setEditable(true);
		this.txtDepID.requestFocus();
	}// GEN-LAST:event_btnDepNewActionPerformed

	private void treeDepartmentMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_treeDepartmentMouseClicked
		// Turn off on-tree editing mode
		treeDepartment.cancelEditing();
		// Get the clicked node at the last component of the path
		TreePath path = treeDepartment.getSelectionPath();
		if (path == null) {
			return;
		}

		DefaultMutableTreeNode selectedNode;
		selectedNode = (DefaultMutableTreeNode) treeDepartment.getLastSelectedPathComponent();
		// Get the selected object in the model
		Object selectedObj = selectedNode.getUserObject();
		// Identify selected Object
		if (selectedObj == root) {
			this.currentDepNode = null;
			this.currentEmpNode = null;
		} else {
			if (selectedObj instanceof Department) {
				this.currentDepNode = selectedNode;
				this.currentEmpNode = null;
			} else if (selectedObj instanceof Employee) {
				currentDepNode = (DefaultMutableTreeNode) selectedNode.getParent();
				currentEmpNode = selectedNode;
			}
			// View the result
			view();
		}
	}// GEN-LAST:event_treeDepartmentMouseClicked

	private void btnDepRemoveActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnDepRemoveActionPerformed
		// Only remove a department if Child = 0
		if (this.currentDepNode.getChildCount() > 0) {
			String msg = "You have to remove all employees before remove a department!";
			JOptionPane.showMessageDialog(null, msg);
		} else {
			int confirm = JOptionPane.showConfirmDialog(null, "Are you sure to remove this department?", "Confirm",
					JOptionPane.YES_NO_OPTION);
			if (confirm == JOptionPane.YES_OPTION) {
				root.remove(currentDepNode);
				treeDepartment.updateUI();
			}
		}
	}// GEN-LAST:event_btnDepRemoveActionPerformed

	private void btnDepSaveActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnDepSaveActionPerformed
		String id = this.txtDepID.getText().trim().toUpperCase();
		txtDepID.setText(id);
		String name = this.txtDepName.getText().trim();
		txtDepName.setText(name);
		if (!validDepDetail()) {
			return;
		}
		if (addNewDep == true) {
			Department newDep = new Department(id, name);
			root.add(new DefaultMutableTreeNode(newDep));
		} else {
			((Department) currentDepNode.getUserObject()).setDepName(name);
		}
		treeDepartment.updateUI();
		this.addNewDep = false;
	}// GEN-LAST:event_btnDepSaveActionPerformed

	private void btnEmpNewActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnEmpNewActionPerformed
		this.addNewEmp = true;
		this.txtEmpID.setText("");
		this.txtEmpName.setText("");
		this.txtEmpEmail.setText("");
		this.txtEmpAdrs.setText("");
		this.txtEmpSalary.setText("");
		this.txtEmpID.requestFocus();
		this.txtEmpID.setEditable(true);
	}// GEN-LAST:event_btnEmpNewActionPerformed

	private void btnEmpRemoveActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnEmpRemoveActionPerformed
		if (this.currentEmpNode != null) {
			int confirm = JOptionPane.showConfirmDialog(null, "Are your sure to delete this employee?", "Confirm",
					JOptionPane.YES_NO_OPTION);
			if (confirm == JOptionPane.YES_OPTION) {
				this.currentDepNode.remove(this.currentEmpNode);
				treeDepartment.updateUI();
			}
		}
	}// GEN-LAST:event_btnEmpRemoveActionPerformed

	private void btnEmpSaveActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnEmpSaveActionPerformed
		String id = this.txtEmpID.getText().trim().toUpperCase();
		txtEmpID.setText(id);
		String name = this.txtEmpName.getText().trim();
		txtEmpName.setText(name);
		String email = this.txtEmpEmail.getText().trim();
		txtEmpEmail.setText(email);
		String address = this.txtEmpAdrs.getText().trim();
		txtEmpAdrs.setText(address);
		String salaryStr = this.txtEmpSalary.getText();
		int salary = Integer.parseInt(salaryStr);
		txtEmpSalary.setText(salaryStr);

		if (!validEmpDetail()) {
			return;
		}
		if (addNewEmp == true) {
			Employee newEmp = new Employee(id, name, email, address, salary);
			currentDepNode.add(new DefaultMutableTreeNode(newEmp));
		} else {
			Employee emp = (Employee) (currentEmpNode.getUserObject());
			emp.setEmpName(name);
			emp.setEmpEmail(email);
			emp.setEmpAddress(address);
			emp.setSalary(salary);
		}
		treeDepartment.updateUI();
		addNewEmp = false;
	}// GEN-LAST:event_btnEmpSaveActionPerformed

	private void btnSave2FileActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnSave2FileActionPerformed
		if (root.getChildCount() == 0) {
			JOptionPane.showMessageDialog(null, "Nothing to save!");
			return;
		}
		String str;
		try {
			FileWriter fw = new FileWriter(fileName);
			PrintWriter pw = new PrintWriter(fw);
			Enumeration deps = root.children();
			while (deps.hasMoreElements()) {
				DefaultMutableTreeNode depNode = (DefaultMutableTreeNode) deps.nextElement();
				Department dep = (Department) depNode.getUserObject();
				str = dep.getDepID() + "-" + dep.getDepName() + ":";
				pw.println(str);
				Enumeration emps = depNode.children();
				while (emps.hasMoreElements()) {
					DefaultMutableTreeNode empNode = (DefaultMutableTreeNode) emps.nextElement();
					Employee emp = (Employee) empNode.getUserObject();
					str = emp.getEmpID() + "," + emp.getEmpName() + "," + emp.getEmpEmail() + "," + emp.getEmpAddress()
							+ "," + emp.getSalary();
					pw.println(str);
				}
			}
			pw.close();
			fw.close();
			JOptionPane.showMessageDialog(null, "Data saved!");
		} catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showConfirmDialog(null, "There are a problem while saving data to file!");
		}
	}// GEN-LAST:event_btnSave2FileActionPerformed

	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		/* Set the Nimbus look and feel */
		// <editor-fold defaultstate="collapsed" desc=" Look and feel setting code
		// (optional) ">
		/*
		 * If Nimbus (introduced in Java SE 6) is not available, stay with the default
		 * look and feel. For details see
		 * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
		 */
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(JTreeForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(JTreeForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(JTreeForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(JTreeForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		}
		// </editor-fold>

		/* Create and display the form */
		java.awt.EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				new JTreeForm().setVisible(true);
			}
		});
	}

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JButton btnDepNew;
	private javax.swing.JButton btnDepRemove;
	private javax.swing.JButton btnDepSave;
	private javax.swing.JButton btnEmpNew;
	private javax.swing.JButton btnEmpRemove;
	private javax.swing.JButton btnEmpSave;
	private javax.swing.JButton btnSave2File;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel3;
	private javax.swing.JLabel jLabel4;
	private javax.swing.JLabel jLabel5;
	private javax.swing.JLabel jLabel6;
	private javax.swing.JLabel jLabel7;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JPanel pnlDeppartment;
	private javax.swing.JPanel pnlEmployee;
	private javax.swing.JTree treeDepartment;
	private javax.swing.JTextField txtDepID;
	private javax.swing.JTextField txtDepName;
	private javax.swing.JTextField txtEmpAdrs;
	private javax.swing.JTextField txtEmpEmail;
	private javax.swing.JTextField txtEmpID;
	private javax.swing.JTextField txtEmpName;
	private javax.swing.JTextField txtEmpSalary;
	// End of variables declaration//GEN-END:variables

	// Load data from file
	private void loadData() {
		String str;
		StringTokenizer stk;
		try {
			FileReader fr = new FileReader(fileName);
			BufferedReader br = new BufferedReader(fr);
			while ((str = br.readLine()) != null) {
				str = str.trim();
				boolean isDep = (str.charAt(str.length() - 1) == ':');
				stk = new StringTokenizer(str, "-:,");
				String id = stk.nextToken().trim();
				String name = stk.nextToken().trim();
				if (isDep) {
					currentDepNode = new DefaultMutableTreeNode(new Department(id, name));
					root.add(currentDepNode); // Add current Department to root node
				} else {
					String email = stk.nextToken();
					String address = stk.nextToken();
					int salary = Integer.parseInt(stk.nextToken().trim());
					currentEmpNode = new DefaultMutableTreeNode(new Employee(id, name, email, address, salary));
					currentDepNode.add(currentEmpNode);
				}
			}
			br.close();
			fr.close();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "There are a problem while loading data from file!");
			e.printStackTrace();
		}
	}

	// View Deparment and Employee detail
	private void view() {
		Department currentDep = null;
		Employee currentEmp = null;

		if (currentDepNode != null) {
			currentDep = (Department) currentDepNode.getUserObject();
		}
		if (currentEmpNode != null) {
			currentEmp = (Employee) currentEmpNode.getUserObject();
		}

		this.txtDepID.setText(currentDep != null ? currentDep.getDepID() : "");
		this.txtDepName.setText(currentDep != null ? currentDep.getDepName() : "");
		this.txtEmpID.setText(currentEmp != null ? currentEmp.getEmpID() : "");
		this.txtEmpName.setText(currentEmp != null ? currentEmp.getEmpName() : "");
		this.txtEmpEmail.setText(currentEmp != null ? currentEmp.getEmpEmail() : "");
		this.txtEmpAdrs.setText(currentEmp != null ? currentEmp.getEmpAddress() : "");
		this.txtEmpSalary.setText("" + (currentEmp != null ? currentEmp.getSalary() : ""));
		this.txtDepID.setEditable(false);
		this.txtEmpID.setEditable(false);
	}

	// Department detail validation
	private boolean validDepDetail() {
		return true;
	}

	// Employee detail validation
	private boolean validEmpDetail() {
		return true;
	}
}
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package jtreeapp.Model;

/**
 *
 * @author thienlh
 */
public class Department {
	String depID;
	String depName;

	public Department(String depID, String depName) {
		this.depID = depID;
		this.depName = depName;
	}

	public String getDepID() {
		return depID;
	}

	public void setDepID(String depID) {
		this.depID = depID;
	}

	public String getDepName() {
		return depName;
	}

	public void setDepName(String depName) {
		this.depName = depName;
	}

	@Override
	public String toString() {
		return depID + "-" + depName;
	}
}
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package jtreeapp.Model;

/**
 *
 * @author thienlh
 */
public class Employee {

	String empID;
	String empName;
	String empEmail;
	String empAddress;

	public String getEmpEmail() {
		return empEmail;
	}

	public void setEmpEmail(String empEmail) {
		this.empEmail = empEmail;
	}

	public String getEmpAddress() {
		return empAddress;
	}

	public void setEmpAddress(String empAddress) {
		this.empAddress = empAddress;
	}

	int salary;

	public Employee(String empID, String empName, int salary) {
		this.empID = empID;
		this.empName = empName;
		this.salary = salary;
	}

	public Employee(String empID, String empName, String empEmail, String empAddress, int salary) {
		this.empID = empID;
		this.empName = empName;
		this.empEmail = empEmail;
		this.empAddress = empAddress;
		this.salary = salary;
	}

	public String getEmpID() {
		return empID;
	}

	public void setEmpID(String empID) {
		this.empID = empID;
	}

	public String getEmpName() {
		return empName;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public int getSalary() {
		return salary;
	}

	public void setSalary(int salary) {
		this.salary = salary;
	}

	@Override
	public String toString() {
		return empID + "-" + empName;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值