JTree: добавление узла в JTree с помощью узла типа файла - PullRequest
1 голос
/ 15 июня 2019

Я должен сделать File Explorer с опциями копирования, перемещения и удаления для изучения. Большая часть работы выполнена, но когда я пытаюсь добавить узел, используя способ из этого фильма на YouTube: https://www.youtube.com/watch?v=rhRcxwreeVc

Я получаю этот тип ошибок:

java.io.File cannot be cast to javax.swing.tree.DefaultMutableTreeNode

Кто-нибудь знает правильный способ изменения типов файлов на типы DefaultMutableTreeNode?

Класс GUI:

  import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.JButton;
import java.nio.file.*;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class GUI_2 {

    private JFrame frame;

    private JTextField leftPathTextField;
    private JTextField rightPathTextField;

    private Object selectedRightNode;
    private Object selectedLeftNode;

    private JTree rightTree;
    private JTree leftTree;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (InstantiationException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (UnsupportedLookAndFeelException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    GUI_2 window = new GUI_2();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public GUI_2() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 837, 548);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel mainPanel = new JPanel();
        frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
        mainPanel.setLayout(new GridLayout(1, 2, 0, 0));

        JScrollPane leftScrollPanel = new JScrollPane();
        mainPanel.add(leftScrollPanel);

        JPanel leftPathPanel = new JPanel();
        leftScrollPanel.setColumnHeaderView(leftPathPanel);
        leftPathPanel.setLayout(new GridLayout(1, 2, 0, 0));

        leftPathTextField = new JTextField();
        leftPathTextField.setText("C:\\");
        leftPathTextField.setColumns(10);
        leftPathPanel.add(leftPathTextField);

        leftTree = new JTree();
        leftTree.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (leftTree.getSelectionPath().getLastPathComponent() != null)
                    selectedLeftNode =  leftTree.getSelectionPath().getLastPathComponent();

            }
        });
        leftTree.setModel(new FilesContentProvider(leftPathTextField.getText()));
        leftScrollPanel.setViewportView(leftTree);

        JButton leftFindButton = new JButton("Find");
        leftFindButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                leftTree.setModel(new FilesContentProvider(leftPathTextField.getText()));

            }
        });
        leftPathPanel.add(leftFindButton);

        JScrollPane rightScrollPanel = new JScrollPane();
        mainPanel.add(rightScrollPanel);

        JPanel rightPathPanel = new JPanel();
        rightScrollPanel.setColumnHeaderView(rightPathPanel);
        rightPathPanel.setLayout(new GridLayout(1, 2, 0, 0));

        rightPathTextField = new JTextField();
        rightPathTextField.setText("C:\\");
        rightPathTextField.setColumns(10);
        rightPathPanel.add(rightPathTextField);

        rightTree = new JTree();
        rightTree.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {

                if (rightTree.getSelectionPath().getLastPathComponent() != null)
                    selectedRightNode =  rightTree.getSelectionPath().getLastPathComponent();

            }
        });
        rightTree.setModel(new FilesContentProvider(rightPathTextField.getText()));
        rightScrollPanel.setViewportView(rightTree);

        JButton rightFindButton = new JButton("Find");
        rightFindButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                rightTree.setModel(new FilesContentProvider(rightPathTextField.getText()));

            }
        });
        rightPathPanel.add(rightFindButton);

        JLabel helloLablel = new JLabel("File Explorer");
        helloLablel.setHorizontalAlignment(SwingConstants.CENTER);
        frame.getContentPane().add(helloLablel, BorderLayout.NORTH);

        JPanel panel = new JPanel();
        frame.getContentPane().add(panel, BorderLayout.SOUTH);
        panel.setLayout(new GridLayout(1, 3, 0, 0));

        JButton copyButton = new JButton("Copy");
        copyButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Path leftPathLocal = Paths.get(selectedLeftNode.toString());
                Path rightPathLocal = Paths.get(selectedRightNode.toString() + "\\" + leftPathLocal.getFileName());
                if (Files.isRegularFile(rightPathLocal))
                    try {
                        Files.copy(leftPathLocal, rightPathLocal, StandardCopyOption.REPLACE_EXISTING);
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                else {
                    try {
                        Files.copy(leftPathLocal, rightPathLocal, StandardCopyOption.REPLACE_EXISTING);
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    EngineDAOImpl engineDAOImpl = new EngineDAOImpl();
                    engineDAOImpl.copyFiles(leftPathLocal, rightPathLocal);
                }

                //selectedRightNode.add()

            }
        });
        panel.add(copyButton);

        JButton moveButton = new JButton("Move");
        moveButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Path leftPathLocal = Paths.get(leftPathTextField.getText());
                Path rightPathLocal = Paths.get(rightPathTextField.getText() + "\\" + leftPathLocal.getFileName());

                if (!Files.isRegularFile(leftPathLocal)) {
                    try {

                        Files.move(leftPathLocal, rightPathLocal, StandardCopyOption.REPLACE_EXISTING);
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                } else {
                    EngineDAOImpl engineDAOImpl = new EngineDAOImpl();
                    engineDAOImpl.moveFiles(leftPathLocal, rightPathLocal);

                    try {
                        Files.deleteIfExists(leftPathLocal);
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                }
            }
        });
        panel.add(moveButton);

        JButton deleteButton = new JButton("Delete");
        deleteButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                Path leftPathLocal = Paths.get(leftPathTextField.getText());
                System.out.println(leftPathLocal);

                if (Files.isRegularFile(leftPathLocal)) {
                    try {
                        Files.delete(leftPathLocal);
                    } catch (IOException e1) {

                        e1.printStackTrace();
                    }

                } else {
                    EngineDAOImpl engineDAOImpl = new EngineDAOImpl();
                    engineDAOImpl.deleteFiles(leftPathLocal);
                    try {
                        Files.delete(leftPathLocal);
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                }

                DefaultTreeModel model = (DefaultTreeModel) leftTree.getModel();

                model.removeNodeFromParent((DefaultMutableTreeNode) selectedLeftNode);

                model.reload();

            }
        });
        panel.add(deleteButton);

    }

    public void deleteNode(JTree tree) {

    }

}

Узлы создания класса:

import java.io.File;
import java.util.Arrays;
import java.util.List;

import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

public class FilesContentProvider implements TreeModel {

    private File node;

    public FilesContentProvider(String path) {
        node = new File(path);

    }
    public void addTreeModelListener(TreeModelListener l) {

    }

    public Object getChild(Object parent, int index) {
        if (parent == null)
            return null;
        return ((File) parent).listFiles()[index];
    }

    public int getChildCount(Object parent) {
        if (parent == null)
            return 0;
        return (((File) parent).listFiles() != null) ? ((File) parent).listFiles().length : 0;
    }

    public int getIndexOfChild(Object parent, Object child) {
        List<File> list = Arrays.asList(((File) parent).listFiles());
        return list.indexOf(child);
    }

    public Object getRoot() {
        return node;
    }

    public boolean isLeaf(Object node) {
        return ((File) node).isFile();
    }

    public void removeTreeModelListener(TreeModelListener l) {

    }

    public void valueForPathChanged(TreePath path, Object newValue) {

    }

}

Класс для опций:

import java.io.File;
import java.io.IOException;
import java.nio.file.*;

import javax.swing.JTree;


public class EngineDAOImpl  {

    public void copyFiles(Path leftURL, Path rightURL) {
        // TODO Auto-generated method stub
        if (Files.isRegularFile(leftURL)) {
            try {


                Files.copy(leftURL, rightURL, StandardCopyOption.REPLACE_EXISTING);

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        } else {

            File[] listFiles = leftURL.toFile().listFiles();

            for (File file : listFiles) {
                String tmpRightPathString = rightURL.toString() + "\\" + file.getName();
                System.out.println("Folder");
                try {

                    Files.copy(file.toPath(), Paths.get(tmpRightPathString), StandardCopyOption.REPLACE_EXISTING);

                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                copyFiles(file.toPath(), Paths.get(tmpRightPathString));
            }

        }
    }

    public void moveFiles(Path leftURL, Path rightURL) {
        // TODO Auto-generated method stub
        if (Files.isRegularFile(leftURL)) {
            try {

                Files.move(leftURL, rightURL, StandardCopyOption.REPLACE_EXISTING);

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        } else {

            File[] listFiles = leftURL.toFile().listFiles();

            for (File file : listFiles) {
                String tmpRightPathString = rightURL.toString() + "\\" + file.getName();

                try {

                    Files.copy(file.toPath(), Paths.get(tmpRightPathString), StandardCopyOption.REPLACE_EXISTING);

                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                copyFiles(file.toPath(), Paths.get(tmpRightPathString));
                try {
                    Files.deleteIfExists(file.toPath());
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
    }

    public void deleteFiles(Path URL) {
        if (Files.isRegularFile(URL)) {
            try {

                Files.delete(URL);;

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        } else {

            File[] listFiles = URL.toFile().listFiles();

            for (File file : listFiles) {
                String tmpRightPathString = URL.toString() + "\\" + file.getName();
                deleteFiles(Paths.get(tmpRightPathString));
                if (!Files.isRegularFile(Paths.get(tmpRightPathString))) {
                    try {
                        Files.delete(Paths.get(tmpRightPathString));
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }

        }

    }

}
...