Display file(s) name and select it under the folder in JTree - java

I managed to come this far using stackoverflow examples, JTree displays all the system drives and folders, wanted to display all the corresponding files from the folder as well, got all the file names in a loop need to add them, that's where I got stuck!
Please give me direction to add the files under the folder, Thanks!
CODE:
public class viewGui extends JFrame {
private FileSystemView fileSystemView;
private Desktop desktop;
private static final long serialVersionUID = 1083130296343096642L;
public static JTree tree;
private DefaultTreeModel treeModel;
private JTable table;
private ListSelectionListener listSelectionListener;
private static final LayoutManager H = new GridLayout(1, 0);
private static final LayoutManager V = new GridLayout(0, 1);
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
viewGui mainWindow = new viewGui();
mainWindow.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public viewGui() {
fileSystemView = FileSystemView.getFileSystemView();
desktop = Desktop.getDesktop();
this.setTitle("Student Record Book");
getContentPane().setLayout(H);
getContentPane().setLayout(V);
this.setPreferredSize(new Dimension(1200, 800));
this.setExtendedState(NORMAL);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(null);
this.setResizable(true);
DefaultMutableTreeNode root = new DefaultMutableTreeNode();
treeModel = new DefaultTreeModel(root);
TreeSelectionListener treeSelectionListener = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent tse){
DefaultMutableTreeNode node = (DefaultMutableTreeNode)tse.getPath().getLastPathComponent();
System.out.println("Node: "+node);
showChildren(node);
}
};
File[] roots = fileSystemView.getRoots();
for (File fileSystemRoot : roots) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(fileSystemRoot);
root.add( node );
File[] files = fileSystemView.getFiles(fileSystemRoot, true);
for (File file : files) {
if (file.isDirectory()) {
node.add(new DefaultMutableTreeNode(file));
}
}
}
tree = new JTree(treeModel);
tree.setBounds(10, 11, 387, 740);
tree.setRootVisible(false);
tree.addTreeSelectionListener(treeSelectionListener);
tree.expandRow(0);
JScrollPane treeScroll = new JScrollPane(tree);
tree.setVisibleRowCount(15);
Dimension preferredSize = treeScroll.getPreferredSize();
Dimension widePreferred = new Dimension(200,(int)preferredSize.getHeight());
treeScroll.setPreferredSize( widePreferred );
this.setLayout(H);
this.validate();
this.add(treeScroll, BorderLayout.WEST);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
table = new JTable();
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setAutoCreateRowSorter(true);
table.setShowVerticalLines(false);
listSelectionListener = new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent lse) {
int row = table.getSelectionModel().getLeadSelectionIndex();
}
};
table.getSelectionModel().addListSelectionListener(listSelectionListener);
JScrollPane tableScroll = new JScrollPane(table);
Dimension d = tableScroll.getPreferredSize();
tableScroll.setPreferredSize(new Dimension((int)d.getWidth(), (int)d.getHeight()/2));
getContentPane().add(tableScroll, BorderLayout.CENTER);
}
private void showChildren(final DefaultMutableTreeNode node) {
tree.setEnabled(false);
SwingWorker<Void, File> worker = new SwingWorker<Void, File>() {
#Override
public Void doInBackground() {
File file = (File) node.getUserObject();
if (file.isDirectory()) {
File[] files = fileSystemView.getFiles(file, true); //!!
if (node.isLeaf()) {
for (File child : files) {
System.out.println("child:"+child);
if (child.isDirectory()) {
publish(child);
//Need to add the file names under the folder
}
}
}
}
return null;
}
#Override
protected void process(List<File> chunks) {
for (File child : chunks) {
node.add(new DefaultMutableTreeNode(child));
if (child.isDirectory()){
}
}
}
#Override
protected void done() {
tree.setEnabled(true);
}
};
worker.execute();
}
}

Don't add all the file names in a loop. Instead, create a FileTreeModel that implements TreeModel, as shown here. The implementation simply invokes the File method listFiles() in getChild() and getIndexOfChild(). Then you can create a tree and expand any desired row; use setSelectionPath() as shown here.
TreeModel model = new FileTreeModel(new File(System.getProperty("user.dir")));
JTree tree = new JTree(model);
tree.expandRow(0);
I get only the c:\; please give me directions to get all the system drives, etc.
You can get a list of filesystem roots with File.listRoots(), as shown in Find all drive letters in Java, or FileSystemView#getRoots(), as shown in File Browser GUI.

Related

Transfer file path from file tree to another class

This may be a bit confusing to explain but I will try my best. I have a class called FileBrowser and there is a line which is String hello=fileNode.getFile that takes the clicked file node from the Jtree and saves it to the variable hello. Full class is below.
FileBrowser.java
import java.awt.BorderLayout;
import java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import org.apache.commons.io.FileUtils;
public class FileBrowser extends JPanel {
public DefaultMutableTreeNode root;
public DefaultTreeModel treeModel;
public JTree tree;
public FileBrowser() {
//JFrame frame = new JFrame("File Browser");
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
File fileRoot = new File("C://");
root = new DefaultMutableTreeNode(new FileNode(fileRoot));
treeModel = new DefaultTreeModel(root);
tree = new JTree(treeModel);
tree.setShowsRootHandles(true);
JScrollPane scrollPane = new JScrollPane(tree);
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent event) {
/* new */
DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)
tree.getLastSelectedPathComponent();
FileNode fileNode = (FileNode)dmtn.getUserObject();
File file = fileNode.getFile();
//THIS THE STRING I WOULD LIKE TO TRANSFER TO VIEWER_NAVIGATOR
String hello=file.toString();
call(hello,dmtn);
}
});
// frame.add(scrollPane);
//frame.setLocationByPlatform(true);
//frame.setSize(640, 480);
//frame.setVisible(true);
CreateChildNodes ccn =
new CreateChildNodes(fileRoot, root);
new Thread(ccn).start();
}
private void call(String file, DefaultMutableTreeNode dmtn) {
System.out.println("Exporting file and converting to HTML");
String[] arguments = new String[] {file, dmtn+".html", "HTML"};
OITSample.func(arguments);
}
public class CreateChildNodes implements Runnable {
private DefaultMutableTreeNode root;
private File fileRoot;
public CreateChildNodes(File fileRoot,
DefaultMutableTreeNode root) {
this.fileRoot = fileRoot;
this.root = root;
}
public void run() {
createChildren(fileRoot, root);
}
private void createChildren(File fileRoot,
DefaultMutableTreeNode node) {
File[] files = fileRoot.listFiles();
if (files == null) return;
for (File file : files) {
DefaultMutableTreeNode childNode =
new DefaultMutableTreeNode(new FileNode(file));
node.add(childNode);
if (file.isDirectory()) {
createChildren(file, childNode);
}}}}
public class FileNode {
private File file;
public FileNode(File file) {
this.file = file;
}
public File getFile() {
return file;
}
#Override
public String toString() {
String name = file.getName();
if (name.equals("")) {
return file.getAbsolutePath();
} else {
return name;
}}}}
I would like to take the String variable,hello, and when a file node is clicked, the variable gets sent to the Viewer_Navigator class below, to the area which takes a file at the editorpane. This is area specifically:
File file = new File("the string hello from the other class should go in here");
Viewer_Navigator.java
public class Viewer_Navigator {
private JFrame frame;
public static void main(String[] args) {
String defStartParams = "AdminStart.xml";
String adminParams = parseXML(defStartParams);
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Viewer_Navigator window = new Viewer_Navigator();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private static String parseXML(String defStartParams) {
// We're cheating for now
String params = "sb_ContName='com.staorbase.service.SB_AdminSvc'";
params += ";";
return params;
}
/**
* Create the application.
*/
public Viewer_Navigator() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
frame.setBounds(100, 100, 840, 545);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null); //put the jframe on center of the screen -added
JToolBar toolBar = new JToolBar();
frame.getContentPane().add(toolBar, BorderLayout.NORTH);
final JSplitPane splitPane = new JSplitPane();
splitPane.setDividerLocation(0.8);
splitPane.setResizeWeight(0.3);
frame.getContentPane().add(splitPane, BorderLayout.CENTER);
FileBrowser testing=new FileBrowser();
final JEditorPane editorpane= new JEditorPane();
final JScrollPane editorScrollPane = new JScrollPane(editorpane);
editorScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
final JPanel panel2 = new JPanel(new BorderLayout());
panel2.add(editorScrollPane);
File file = new File("the string 'hello' from the other class should go in here");
try {
editorpane.setPage(file.toURI().toURL());
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JScrollPane jScrollPane=new JScrollPane();
jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jScrollPane.setViewportBorder(new LineBorder(Color.BLUE));
jScrollPane.getViewport().add(testing.tree);
final JPanel panel = new JPanel(new BorderLayout());
panel.add(jScrollPane,BorderLayout.CENTER);
splitPane.setLeftComponent(panel);
splitPane.setRightComponent(panel2);
}
}
Any suggestions on how I should go about doing this? Please let me know if you need any clarifications.
Thank you

Drag and Drop from JTree to JList with own objects

I have a JTree with DefaultMutableTreeNodes. On some levels these nodes were initialized with my own serializable objects. In total there are two different types of objects (called "Step" and "Order"). I want to be able to drop only nodes which were initialized with either of these two objects. Any other nodes which are just Strings shouldn't be droppable. One "Order" can contain many "Steps". I want to be able to drag them onto a JPanel were they get inserted into a JList. If a "Order" was dropped all of the "Steps" are supposed to be inserted, if only a "Step" was dropped only that particular "Step" is supposed to be inserted.
SSCCE below!
JTree:
tree = new JTree();
tree.setShowsRootHandles(true);
tree.setRootVisible(false);
tree.setDragEnabled(true);
tree.setModel(treeModel);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
JPanel:
public class TablePanel extends JPanel
{
private static final long serialVersionUID = 3216206960422611905L;
public TablePanel()
{
super();
setLayout(new MigLayout("", "[grow]", "[][grow]"));
JProgressBar progressBar = new JProgressBar();
progressBar.setMaximum(28800); // 8 hours in seconds
progressBar.setStringPainted(true);
add(progressBar, "cell 0 0,growx");
DefaultListModel<Step> listModel = new DefaultListModel<Step>();
JList<Step> list = new JList<Step>();
list.setModel(listModel);
setDropTarget(new DropTarget(this, TransferHandler.COPY, new DropTargetAdapter()
{
private int index = 0;
private int amount = 0;
#Override
public void drop(DropTargetDropEvent dtde)
{
amount = 0;
index = 0;
}
#Override
public void dragExit(DropTargetEvent dte)
{
if (listModel.size() > 0)
{
if (amount == 1)
{
listModel.remove(index);
}
else
{
for (int i = 0; i < amount; i++)
{
listModel.remove(index + i);
}
}
amount = 0;
}
}
#Override
public void dragEnter(DropTargetDragEvent dtde)
{
try
{
Transferable tr = dtde.getTransferable();
if (dtde.isDataFlavorSupported(Order.auftragFlavor))
{
Order a = (Order) tr.getTransferData(Order.auftragFlavor); // Wrong, how do I get this?
dtde.acceptDrag(DnDConstants.ACTION_COPY);
amount = a.getSteps().size();
}
else if (dtde.isDataFlavorSupported(Step.arbeitsgangFlavor))
{
Step ag = (Step) tr.getTransferData(Step.arbeitsgangFlavor);
dtde.acceptDrag(DnDConstants.ACTION_COPY);
amount = 1;
}
else
{
dtde.rejectDrag();
}
}
catch (Exception e)
{
e.printStackTrace();
dtde.rejectDrag();
}
}
#Override
public void dragOver(DropTargetDragEvent dtde)
{
try
{
Transferable tr = dtde.getTransferable();
if (dtde.isDataFlavorSupported(Order.auftragFlavor))
{
Order a = (Order) tr.getTransferData(Order.auftragFlavor); // Wrong, how do I get this?
dtde.acceptDrag(DnDConstants.ACTION_COPY);
amount = a.getSteps().size();
}
else if (dtde.isDataFlavorSupported(Step.arbeitsgangFlavor))
{
Step ag = (Step) tr.getTransferData(Step.arbeitsgangFlavor);
dtde.acceptDrag(DnDConstants.ACTION_COPY);
amount = 1;
}
else dtde.rejectDrag();
}
catch (Exception e)
{
e.printStackTrace();
dtde.rejectDrag();
}
}
}, true, null));
add(list, "cell 0 1,grow");
}
}
When you are dragging over the JList, then the data should be inserted into the list to give the user feedback and the possibility to place it in the list. If not dropped, it should be removed again.
How can drag and drop my objects onto the JPanel, but not nodes which are just Strings?
EDIT:
With (String) tr.getTransferData(DataFlavor.stringFlavor) I am able to get the label of the node, but this is not really helpfull, because I don't know if it was a Order, Step or just a string node.
EDIT2 SSCCE:
public class Test extends JFrame
{
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
Test window = new Test();
window.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
public Test()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
DefaultMutableTreeNode string1 = new DefaultMutableTreeNode("String 1");
DefaultMutableTreeNode order1 = new DefaultMutableTreeNode(new ParentObject());
order1.add(new DefaultMutableTreeNode(new ChildObject()));
order1.add(new DefaultMutableTreeNode(new ChildObject()));
string1.add(order1);
root.add(string1);
DefaultTreeModel model = new DefaultTreeModel(root);
JTree tree = new JTree(model);
tree.setShowsRootHandles(true);
tree.setRootVisible(false);
tree.setDragEnabled(true);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
contentPane.add(tree, BorderLayout.WEST);
CustPanel panel = new CustPanel();
contentPane.add(panel, BorderLayout.CENTER);
}
}
class CustPanel extends JPanel
{
private static final long serialVersionUID = 1L;
public CustPanel()
{
super();
setLayout(new MigLayout("", "[grow]", "[][grow]"));
JProgressBar progressBar = new JProgressBar();
add(progressBar, "cell 0 0,growx");
DefaultListModel<ChildObject> listModel = new DefaultListModel<ChildObject>();
JList<ChildObject> list = new JList<ChildObject>();
list.setModel(listModel);
setDropTarget(new DropTarget(this, TransferHandler.COPY, new DropTargetAdapter()
{
#Override
public void drop(DropTargetDropEvent dtde)
{
Transferable tr = dtde.getTransferable();
if (dtde.isDataFlavorSupported(DataFlavor.stringFlavor))
{
try
{
System.out.println((String) tr.getTransferData(DataFlavor.stringFlavor)); // I want the actual object
}
catch (UnsupportedFlavorException | IOException e)
{
e.printStackTrace();
}
}
}
#Override
public void dragExit(DropTargetEvent dte)
{
}
#Override
public void dragEnter(DropTargetDragEvent dtde)
{
Transferable tr = dtde.getTransferable();
if (dtde.isDataFlavorSupported(DataFlavor.stringFlavor))
{
try
{
System.out.println((String) tr.getTransferData(DataFlavor.stringFlavor)); // I want the actual object
}
catch (UnsupportedFlavorException | IOException e)
{
e.printStackTrace();
}
}
}
#Override
public void dragOver(DropTargetDragEvent dtde)
{
Transferable tr = dtde.getTransferable();
if (dtde.isDataFlavorSupported(DataFlavor.stringFlavor))
{
try
{
System.out.println((String) tr.getTransferData(DataFlavor.stringFlavor)); // I want the actual object
}
catch (UnsupportedFlavorException | IOException e)
{
e.printStackTrace();
}
}
}
}, true, null));
add(list, "cell 0 1,grow");
}
}
class ParentObject implements Serializable
{
private static final long serialVersionUID = 1279985471254050120L;
public ArrayList<ChildObject> getChildren()
{
return new ArrayList<ChildObject>();
}
#Override
public String toString()
{
return "ParentObject";
}
}
class ChildObject implements Serializable
{
private static final long serialVersionUID = -5833860202973614790L;
#Override
public String toString()
{
return "ChildObject";
}
}
but not nodes which are just Strings?
You might be able to use a TransferHandler#createTransferable(...) method to get the DefaultMutableTreeNode.
TransferHandler#createTransferable(JComponent) (Java Platform SE 8 )
Demo - DropDemo (The Java™ Tutorials > Creating a GUI With JFC/Swing > Drag and Drop and Data Transfer)
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.io.*;
import java.util.*;
import javax.activation.*;
import javax.swing.*;
import javax.swing.tree.*;
public class Test2 {
public JComponent makeUI() {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
DefaultMutableTreeNode string1 = new DefaultMutableTreeNode("String 1");
DefaultMutableTreeNode order1 = new DefaultMutableTreeNode(new ParentObject());
order1.add(new DefaultMutableTreeNode(new ChildObject()));
order1.add(new DefaultMutableTreeNode(new ChildObject()));
string1.add(order1);
root.add(string1);
DefaultTreeModel model = new DefaultTreeModel(root);
JTree tree = new JTree(model);
tree.setShowsRootHandles(true);
tree.setRootVisible(false);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setTransferHandler(new TreeTransferHandler());
tree.setDragEnabled(true);
DefaultListModel<ChildObject> listModel = new DefaultListModel<ChildObject>();
JList<ChildObject> list = new JList<ChildObject>();
list.setModel(listModel);
list.setDropTarget(new DropTarget(list, TransferHandler.COPY, new DropTargetAdapter() {
private void print(Transferable tr) {
try {
Object node = tr.getTransferData(TreeTransferHandler.FLAVOR);
System.out.println(node); // I want the actual object
} catch (UnsupportedFlavorException | IOException ex) {
ex.printStackTrace();
}
}
#Override
public void drop(DropTargetDropEvent dtde) {
if (dtde.isDataFlavorSupported(TreeTransferHandler.FLAVOR)) {
print(dtde.getTransferable());
}
}
#Override public void dragExit(DropTargetEvent dte) {}
#Override public void dragEnter(DropTargetDragEvent dtde) {}
#Override public void dragOver(DropTargetDragEvent dtde) {}
}, true, null));
JPanel contentPane = new JPanel(new GridLayout(1, 2));
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.add(new JScrollPane(tree), BorderLayout.WEST);
contentPane.add(new JScrollPane(list), BorderLayout.CENTER);
return contentPane;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
try {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new Test2().makeUI());
f.setBounds(100, 100, 450, 300);
f.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
class ParentObject implements Serializable {
public ArrayList<ChildObject> getChildren() {
return new ArrayList<ChildObject>();
}
#Override
public String toString() {
return "ParentObject";
}
}
class ChildObject implements Serializable {
#Override
public String toString() {
return "ChildObject";
}
}
class TreeTransferHandler extends TransferHandler {
public static final DataFlavor FLAVOR = new ActivationDataFlavor(
DefaultMutableTreeNode[].class,
DataFlavor.javaJVMLocalObjectMimeType,
"Array of DefaultMutableTreeNode");
#Override protected Transferable createTransferable(JComponent c) {
JTree source = (JTree) c;
TreePath[] paths = source.getSelectionPaths();
DefaultMutableTreeNode[] nodes = new DefaultMutableTreeNode[paths.length];
for (int i = 0; i < paths.length; i++) {
nodes[i] = (DefaultMutableTreeNode) paths[i].getLastPathComponent();
}
return new DataHandler(nodes, FLAVOR.getMimeType());
}
#Override public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
}

How to show only directories in JTree?

I am trying to show only directories in JTree but my below code is showing is directories and files both .can anyone please help me to show only directories.
//Class1
public class FileBrowser implements Runnable {
private DefaultMutableTreeNode root;
private DefaultTreeModel treeModel;
private JTree tree;
#Override
public void run() {
JFrame frame = new JFrame("File Browser");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
File fileRoot = new File("C:\\JDeveloper\\Testing");
root = new DefaultMutableTreeNode(new FileNodes(fileRoot));
treeModel = new DefaultTreeModel(root);
tree = new JTree(treeModel);
tree.setCellRenderer(new DefaultTreeCellRenderer() {
private Icon loadIcon = UIManager.getIcon("OptionPane.errorIcon");
private Icon saveIcon = UIManager.getIcon("OptionPane.informationIcon");
#Override
public Component getTreeCellRendererComponent(JTree tree,
Object value,
boolean bSelected,
boolean bExpanded,
boolean bLeaf,
int iRow,
boolean bHasFocus ) {
Component c = super.getTreeCellRendererComponent(tree, value,
bSelected, bExpanded, bLeaf, iRow, bHasFocus);
return c;
}
});
tree.setShowsRootHandles(true);
JScrollPane scrollPane = new JScrollPane(tree);
frame.add(scrollPane);
frame.setLocationByPlatform(true);
frame.setSize(640, 480);
frame.setVisible(true);
CreateChildNode ccn = new CreateChildNode(fileRoot, root);
new Thread(ccn).start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new FileBrowser());
}
}
//Class 2
class CreateChildNode implements Runnable {
private DefaultMutableTreeNode root;
private File fileRoot;
public CreateChildNode(File fileRoot, DefaultMutableTreeNode root) {
this.fileRoot = fileRoot;
this.root = root;
}
#Override
public void run() {
createChildren(fileRoot, root);
}
private void createChildren(File fileRoot,
DefaultMutableTreeNode root) {
File[] files = fileRoot.listFiles();
for (File child : files) {
System.out.println("Path :" +child.getName());
DefaultMutableTreeNode childNode =
new DefaultMutableTreeNode(new FileNodes(child));
System.out.println("Child Node :" +childNode);
System.out.println("File :" +child.getAbsoluteFile());
root.add(childNode);
if (child.isDirectory() ) {
createChildren(child, childNode);
}
}
}
}
class FileNodes {
private File file;
public FileNodes(File file) {
this.file = file;
}
public File getFile() {
return file;
}
#Override
public String toString() {
String name = file.getName();
if (name.equals("")) {
return file.getAbsolutePath();
} else {
return name;
}
}
}
Simply check for a directory before add to the tree
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import java.awt.*;
import java.io.File;
/**
* Created by keshan on 7/26/2016.
*/
public class FileBrowser implements Runnable {
private DefaultMutableTreeNode root;
private DefaultTreeModel treeModel;
private JTree tree;
#Override
public void run() {
JFrame frame = new JFrame("File Browser");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
File fileRoot = new File("C:");
root = new DefaultMutableTreeNode(new FileNodes(fileRoot));
treeModel = new DefaultTreeModel(root);
tree = new JTree(treeModel);
tree.setCellRenderer(new DefaultTreeCellRenderer() {
private Icon loadIcon = UIManager.getIcon("OptionPane.errorIcon");
private Icon saveIcon = UIManager.getIcon("OptionPane.informationIcon");
#Override
public Component getTreeCellRendererComponent( JTree tree,
Object value,
boolean bSelected,
boolean bExpanded,
boolean bLeaf,
int iRow,
boolean bHasFocus ) {
Component c = super.getTreeCellRendererComponent(tree, value,
bSelected, bExpanded, false, iRow, bHasFocus);
return c;
}
});
tree.setShowsRootHandles(true);
JScrollPane scrollPane = new JScrollPane(tree);
frame.add(scrollPane);
frame.setLocationByPlatform(true);
frame.setSize(640, 480);
frame.setVisible(true);
CreateChildNode ccn = new CreateChildNode(fileRoot, root);
new Thread(ccn).start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new FileBrowser());
}
}
class CreateChildNode implements Runnable {
private DefaultMutableTreeNode root;
private File fileRoot;
public CreateChildNode(File fileRoot, DefaultMutableTreeNode root) {
this.fileRoot = fileRoot;
this.root = root;
}
#Override
public void run() {
createChildren(fileRoot, root);
}
private void createChildren(File fileRoot, DefaultMutableTreeNode root)
{
File[] files = fileRoot.listFiles();
if ( files != null )
{
for( File child : files )
{
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode( new FileNodes( child ) );
if( child.isDirectory() )
{
root.add( childNode );
createChildren( child, childNode );
}
}
}
}
}
class FileNodes {
private File file;
public FileNodes(File file) {
this.file = file;
}
public File getFile() {
return file;
}
#Override
public String toString() {
String name = file.getName();
if (name.equals("")) {
return file.getAbsolutePath();
} else {
return name;
}
}
}
You can do this in java as below
File file=new File("PATH_TO_FILE");
String directories[]=file.list(new FilenameFilter()
{
public boolean accept(File yourFile, String name) {
return new File(yourFile, name).isDirectory();
}
}

Recursively reading a Directory into an ArrayList/Array in Java

I am currently stuck at reading a directory into an ArrayList or better an Array in Java.
I want to use the Data in a JTree.
That's the code I currently use:
//After the definiton of the Class
private ArrayList<File> files = new ArrayList<File>();
// In the main method
this.parse(new File("."));
DefaultMutableTreeNode root = processHierarchy(files.toArray());
this.tree = new JTree(root);
private void parse(File parent)
{
files.add(parent);
if(parent.isDirectory())
{
System.out.println("DIR: "+parent.getName());
String[] child = parent.list();
if(child != null)
{
for(int i = 0; i < child.length; i++)
{
File f = new File(parent, child[i]);
this.parse(f);
}
}
}
else
{
System.out.println("FILE: "+parent.getName());
}
}
Anyone got an idea?
I found this code online that searches a path and then displays it in a JTree.
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.io.*;
public class SimpleTree extends JPanel {
JTree tree;
DefaultMutableTreeNode root;
public SimpleTree() {
root = new DefaultMutableTreeNode("root", true);
getList(root, new File("C:\\Program Files")); // change path here
setLayout(new BorderLayout());
tree = new JTree(root);
tree.setRootVisible(false);
add(new JScrollPane((JTree)tree),"Center");
}
public Dimension getPreferredSize(){
return new Dimension(200, 120);
}
public void getList(DefaultMutableTreeNode node, File f) {
if(!f.isDirectory()) {
// We keep only JAVA source file for display in this HowTo
if (f.getName().endsWith("java")) {
System.out.println("FILE - " + f.getName());
DefaultMutableTreeNode child = new DefaultMutableTreeNode(f);
node.add(child);
}
}
else {
System.out.println("DIRECTORY - " + f.getName());
DefaultMutableTreeNode child = new DefaultMutableTreeNode(f);
node.add(child);
File fList[] = f.listFiles();
for(int i = 0; i < fList.length; i++)
getList(child, fList[i]);
}
}
public static void main(String s[]){
MyJFrame frame = new MyJFrame("Directory explorer");
}
}
class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent e) {
Window win = e.getWindow();
win.setVisible(false);
System.exit(0);
}
}
class MyJFrame extends JFrame {
JButton b1, b2, b3;
SimpleTree panel;
MyJFrame(String s) {
super(s);
panel = new SimpleTree();
getContentPane().add(panel,"Center");
setSize(300,300);
setVisible(true);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowCloser());
}
}
Source: http://www.rgagnon.com/javadetails/java-0324.html

How do I auto-expand a JTree when setting a new TreeModel?

I have a custom JTree and a custom JModel; I would for the JTree to "auto-expand" when I give it a new model. At the moment, it simply collapse all the nodes to the root.
Here is an example:
private class CustomTree extends JTree {
#Override
public boolean isExpanded(TreePath path) {
return ((Person) path.getLastPathComponent).hasChildren();
}
private class CustomTreeModel extends TreeModel {
// ... omitting various implementation details
#Override
public boolean isLeaf(Object object) {
return !((Person) object).hasChildren();
}
}
Model model = new Model();
Person bob = new Person();
Person alice = new Person();
bob.addChild(alice);
model.setRoot(bob);
JTree tree = new CustomTree(new CustomTreeModel(model));
At this point, the tree correctly displays:
- BOB
- ALICE
where Alice is a child of Bob (both in the data and in the visual tree)
However, if I call:
tree.setModel(new CustomTreeModel(model));
everything is collapsed:
+ BOB
Is there a way to "auto-expand" everything in the tree when setting a new model?
The following worked for me (called after setting the new model):
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
I had a similar problem.
Your solution (as posted https://stackoverflow.com/a/15211697/837530) seemed to work for me only for the top level tree nodes.
But I needed to expand all the a descendants node. So I solved it with the following recursive method:
private void expandAllNodes(JTree tree, int startingIndex, int rowCount){
for(int i=startingIndex;i<rowCount;++i){
tree.expandRow(i);
}
if(tree.getRowCount()!=rowCount){
expandAllNodes(tree, rowCount, tree.getRowCount());
}
}
which is invoked with
expandAllNodes(tree, 0, tree.getRowCount());
where, tree is a JTree.
Unless someone has a better solution.
There's also this non-recursive version.
private void expandAllNodes(JTree tree) {
int j = tree.getRowCount();
int i = 0;
while(i < j) {
tree.expandRow(i);
i += 1;
j = tree.getRowCount();
}
}
this worked for me..
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeNode;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Enumeration;
public class JTreeNodeAutoExpandCollapse extends JFrame {
public JTreeNodeAutoExpandCollapse() throws HeadlessException {
initializeUI();
}
private void initializeUI() {
setSize(200, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode chapter1 = new DefaultMutableTreeNode("Chapter 1");
DefaultMutableTreeNode sub1 = new DefaultMutableTreeNode("1.1");
DefaultMutableTreeNode sub2 = new DefaultMutableTreeNode("1.2");
DefaultMutableTreeNode sub3 = new DefaultMutableTreeNode("1.3");
DefaultMutableTreeNode sub31 = new DefaultMutableTreeNode("1.3.1");
DefaultMutableTreeNode sub32 = new DefaultMutableTreeNode("1.3.2");
root.add(chapter1);
chapter1.add(sub1);
chapter1.add(sub2);
chapter1.add(sub3);
sub3.add(sub31);
sub3.add(sub32);
final JTree tree = new JTree(root);
expandTree(tree, false);
JScrollPane pane = new JScrollPane(tree);
pane.setPreferredSize(new Dimension(200, 200));
JPanel buttonPanel = new JPanel(new BorderLayout());
JButton expandAll = new JButton("Expand All");
expandAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
expandTree(tree, true);
}
});
JButton collapseAll = new JButton("Collapse All");
collapseAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
expandTree(tree, false);
}
});
buttonPanel.add(expandAll, BorderLayout.WEST);
buttonPanel.add(collapseAll, BorderLayout.EAST);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(pane, BorderLayout.CENTER);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
}
private void expandTree(JTree tree, boolean expand) {
TreeNode root = (TreeNode) tree.getModel().getRoot();
expandAll(tree, new TreePath(root), expand);
}
private void expandAll(JTree tree, TreePath path, boolean expand) {
TreeNode node = (TreeNode) path.getLastPathComponent();
if (node.getChildCount() >= 0) {
Enumeration enumeration = node.children();
while (enumeration.hasMoreElements()) {
TreeNode n = (TreeNode) enumeration.nextElement();
TreePath p = path.pathByAddingChild(n);
expandAll(tree, p, expand);
}
}
if (expand) {
tree.expandPath(path);
} else {
tree.collapsePath(path);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JTreeNodeAutoExpandCollapse().setVisible(true);
}
});
}
}
public void expandTree(){
int row = 1;
while (row++ < tree.getRowCount()){
tree.expandRow(row);
}
public void collapseTree(){
int row = tree.getRowCount() - 1;
while (row-- > 0){
tree.collapseRow(row);
}
}

Categories