树:
用递归的方式遍历目录和子目录,控制了递归的次数,并将结果返回到树中;
完整代码:
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
/*
* 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.
*/
/**
*
* @author Highgo
*/
public class CheckboxSwing extends javax.swing.JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Creates new form CheckboxSwing
*
* @throws IOException
*/
public CheckboxSwing() throws IOException {
this.setTitle("CheckboxSwing");
initComponents();
inittable();
this.setLocationRelativeTo(null);
}
private CheckboxSwing getThis() {
return this;
}
private void dathinit() {
jTabcheckbox.getModel();
// String filedath = null;
// String dath = "./config/Checkbox.config";
// FileReader fr = new FileReader(dath);
// BufferedReader br = new BufferedReader(fr);
//
// String lineText = null;
// while ((lineText = br.readLine()) != null) {
// System.out.println(lineText);
// filedath = lineText;
// }
//
// System.out.println(filedath);
// br.close();
// filedath = "D://CPUZ";
String filedath = null;
filedath = jTextArea1.getText();
//jTextArea1.setText(filedath);
// if (filedath.equals("") == true) {
//
// }
if (filedath == null || filedath.trim().equals("")) {
}
else {
// File file = new File(filedath);
// File[] fileList = file.listFiles();
// for (int i = 0; i < fileList.length; i++) {
// if (fileList[i].isFile()) {
// String fileName = fileList[i].getName();
// System.out.println("fileName: " + fileName);
// model.addRow(new Object[] { true, model.getRowCount() + 1 ,fileName });
//
// }
//
// if (fileList[i].isDirectory()) {
// String fileName = fileList[i].getName();
// System.out.println("DirectoryName: " + fileName);
// }
// }
//getFile(filedath,0,rootNode,DirectoryName);
traverseFolder(filedath,0);
}
}
private DefaultMutableTreeNode traverseFolder(String path,int n) {
DefaultMutableTreeNode temp;
DefaultTableModel model = (DefaultTableModel) jTabcheckbox.getModel();
DefaultMutableTreeNode fujiedian = new DefaultMutableTreeNode(new File(path).getName());
File file = new File(path);
if (file.exists()) {
if(file.isDirectory()) {
File[] files = file.listFiles();
if (files.length == 0) {
if(file.isDirectory()) {//如果是空文件夹
DefaultMutableTreeNode dn = new DefaultMutableTreeNode(file.getName(), false);
return dn;
}
}else{
for (File file2 : files) {
if (file2.isDirectory()) {
//是目录的话,生成节点,并添加里面的节点
if( n < 5) {
n++;
fujiedian.add(traverseFolder(file2.getAbsolutePath(),n));
}
}else{
//是文件的话直接生成节点,并把该节点加到对应父节点上
String fileName = file2.getName();
model.addRow(new Object[] { true, model.getRowCount() + 1 ,fileName});
temp=new DefaultMutableTreeNode(file2.getName());
fujiedian.add(temp);
}
javax.swing.tree.DefaultTreeModel dm = new DefaultTreeModel(fujiedian);
// 将模型设给树,树上显示的将上前面所加载的节点
jTree.setModel(dm);
}
}
} else {
model.addRow(new Object[] { true, model.getRowCount() + 1 ,file.getName()});
}
} else {//文件不存在
return null;
}
return fujiedian;
}
private void getFile(String path,int n,DefaultMutableTreeNode rootNode,String DirectoryName) {
File file = new File(path);
File[] array = file.listFiles();
DefaultMutableTreeNode teamNode = new DefaultMutableTreeNode();
teamNode.setUserObject(DirectoryName);
// 将组节点加到根节点上:
rootNode.add(teamNode);
DefaultTableModel model = (DefaultTableModel) jTabcheckbox.getModel();
for (int i = 0; i < array.length; i++) {
if (array[i].isFile()) {
System.out.println(array[i].getName());
String fileName = array[i].getName();
model.addRow(new Object[] { true, model.getRowCount() + 1 ,fileName});
DefaultMutableTreeNode userNode = new DefaultMutableTreeNode();
userNode.setUserObject(fileName);
// 将用户节点加到组节点上:
teamNode.add(userNode);
} else if (array[i].isDirectory()) {
if( n < 5 ) {
DirectoryName = array[i].getName();
n++;
// 创建树的Model对象,创建时传入根节点:
javax.swing.tree.DefaultTreeModel dm = new DefaultTreeModel(rootNode);
// 将模型设给树,树上显示的将上前面所加载的节点
jTree.setModel(dm);
getFile(array[i].getPath(),n, rootNode, DirectoryName);
}
}
}
}
private void inittable() {
DefaultTableModel model = (DefaultTableModel) jTabcheckbox.getModel();
//dathinit();
//jTree();
jTree.setModel(null);
jBAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < model.getRowCount(); i++) {
model.setValueAt(Boolean.valueOf(true), i, 0);
}
}
});
jBAllNot.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < model.getRowCount(); i++) {
model.setValueAt(Boolean.valueOf(false), i, 0);
}
}
});
jBClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// while(model.getRowCount()>0){
// model.removeRow(model.getRowCount()-1);
// }
model.setRowCount(0);
}
});
jBDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// int i = 0;
int sum = model.getRowCount();
// while(i < sum)
// {
// if ( (boolean) model.getValueAt(i, 0) == true)
// {
// model.removeRow(i);
// } else {
// i++;
// }
// sum = model.getRowCount();
// }
// while(sum > 0) {
// if((boolean) model.getValueAt(sum - 1, 0) == true) {
// model.removeRow(sum - 1);
// }
// sum--;
// }
for(int i = sum - 1; i >=0; i--) {
if((boolean) model.getValueAt(i, 0) == true) {
model.removeRow(i);
}
}
}
});
getRootPane().setDefaultButton(jBOK);
jBOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object str = null;
for (int i = 0; i < model.getRowCount(); i++) {
str = model.getValueAt(i, 0);
// System.out.println(str);
if (str.equals(true)) {
// Object mojdlog = model.getValueAt(i, 2);
// System.out.println(mojdlog);
System.out.println("true" + (i + 1));
} else {
System.out.println("false" + (i + 1));
}
}
new NewJDialog(getThis(), true);
}
});
jBDath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dathinit();
}
});
// jTree.set
//String top = ("CCCCCCCCCC");
//top.add(new DefaultMutableTreeNode(("C1")));
//jTree.add(comp);
//jTree.addSelectionRow(2);
addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
System.exit(0);
System.out.println("exit");
}
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
});
}
/**
* 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
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jBAllNot = new javax.swing.JButton();
jBAll = new javax.swing.JButton();
jSPTabel = new javax.swing.JScrollPane();
jTabcheckbox = new javax.swing.JTable();
jBOK = new javax.swing.JButton();
jSPArea = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jBDath = new javax.swing.JButton();
jBClear = new javax.swing.JButton();
jBDelete = new javax.swing.JButton();
jSPTree = new javax.swing.JScrollPane();
jTree = new javax.swing.JTree();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jBAllNot.setText("ANOT");
jBAll.setText("ALL");
jTabcheckbox.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Choose", "line", "Name"
}
) {
Class[] types = new Class [] {
java.lang.Boolean.class, java.lang.Integer.class, java.lang.Object.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jSPTabel.setViewportView(jTabcheckbox);
if (jTabcheckbox.getColumnModel().getColumnCount() > 0) {
jTabcheckbox.getColumnModel().getColumn(0).setMinWidth(30);
jTabcheckbox.getColumnModel().getColumn(0).setPreferredWidth(100);
jTabcheckbox.getColumnModel().getColumn(0).setMaxWidth(200);
jTabcheckbox.getColumnModel().getColumn(1).setMinWidth(30);
jTabcheckbox.getColumnModel().getColumn(1).setPreferredWidth(65);
jTabcheckbox.getColumnModel().getColumn(1).setMaxWidth(200);
}
jBOK.setText("OK");
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jSPArea.setViewportView(jTextArea1);
jBDath.setText("Dath");
jBClear.setText("Clear");
jBDelete.setText("Delete");
jSPTree.setViewportView(jTree);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jBAllNot, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jBAll, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jBDelete, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jBClear, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 66, Short.MAX_VALUE)
.addComponent(jSPArea, javax.swing.GroupLayout.PREFERRED_SIZE, 428, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jBDath, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(162, 162, 162)
.addComponent(jBOK, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(169, 169, 169))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jSPTabel, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSPTree)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSPArea, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jBAll)
.addComponent(jBClear))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jBAllNot)
.addComponent(jBDelete)))
.addComponent(jBDath))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jSPTabel, javax.swing.GroupLayout.DEFAULT_SIZE, 437, Short.MAX_VALUE)
.addGap(3, 3, 3))
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(jSPTree)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addComponent(jBOK)
.addGap(6, 6, 6))
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @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(CheckboxSwing.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CheckboxSwing.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CheckboxSwing.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CheckboxSwing.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);
}
// </editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new CheckboxSwing().setVisible(true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jBAll;
private javax.swing.JButton jBAllNot;
private javax.swing.JButton jBClear;
private javax.swing.JButton jBDath;
private javax.swing.JButton jBDelete;
private javax.swing.JButton jBOK;
private javax.swing.JScrollPane jSPArea;
private javax.swing.JScrollPane jSPTabel;
private javax.swing.JScrollPane jSPTree;
private javax.swing.JTable jTabcheckbox;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTree jTree;
// End of variables declaration//GEN-END:variables
}
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/*
* 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.
*/
/**
*
* @author Highgo
*/
public class NewJDialog extends javax.swing.JDialog {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Creates new form NewJDialog
*/
public NewJDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
this.setTitle("NewjDialog");
this.setLocationRelativeTo(null);
this.setVisible(true);
this.addKeyListener(new KeyListener(){
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ESCAPE ) {
System.exit(0);
}
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
});
}
/**
* 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();
jTable1 = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Line", "Name", "Boolean"
}
));
jScrollPane1.setViewportView(jTable1);
if (jTable1.getColumnModel().getColumnCount() > 0) {
jTable1.getColumnModel().getColumn(0).setMinWidth(30);
jTable1.getColumnModel().getColumn(0).setPreferredWidth(60);
jTable1.getColumnModel().getColumn(0).setMaxWidth(150);
}
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @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(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
NewJDialog dialog = new NewJDialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
}