Example usage for javax.swing.tree DefaultTreeModel DefaultTreeModel

List of usage examples for javax.swing.tree DefaultTreeModel DefaultTreeModel

Introduction

In this page you can find the example usage for javax.swing.tree DefaultTreeModel DefaultTreeModel.

Prototype

@ConstructorProperties({ "root" })
public DefaultTreeModel(TreeNode root) 

Source Link

Document

Creates a tree in which any node can have children.

Usage

From source file:com.softeffect.primemovers.ui.ClientApplication.java

/**
 * @return application functions (ApplicationFunction objects), organized as
 *         a tree/*from ww w.j  a  va  2 s. c  om*/
 */
public DefaultTreeModel getApplicationFunctions() {
    DefaultMutableTreeNode root = new OpenSwingTreeNode("Insurance Certicate Database");
    DefaultTreeModel model = new DefaultTreeModel(root);
    ApplicationFunction n1 = new ApplicationFunction("Administration", null);
    ApplicationFunction n10 = new ApplicationFunction("Configuration", "", null, "getConfigurationFunction");
    n1.add(n10);

    ApplicationFunction n2 = new ApplicationFunction("Tasks", null);
    ApplicationFunction n20 = new ApplicationFunction("Add Records", "", null, "getAddRecordsFunction");
    ApplicationFunction n21 = new ApplicationFunction("List Records", "", null, "getListRecordsFunction");
    ApplicationFunction n22 = new ApplicationFunction("Reports", "", null, "getReportsFunction");
    n2.add(n20);
    n2.add(n21);
    n2.add(n22);
    root.add(n1);
    root.add(n2);
    return model;
}

From source file:EditorPaneExample12.java

public void loadNewPage(Object page) {
    try {//  w w  w .ja v  a2  s . c om
        loadingPage = true;

        // Check if the new page and the old
        // page are the same.
        URL url;
        if (page instanceof URL) {
            url = (URL) page;
        } else {
            url = new URL((String) page);
        }

        urlCombo.setSelectedItem(page);

        URL loadedURL = pane.getPage();
        if (loadedURL != null && loadedURL.sameFile(url)) {
            return;
        }

        // Try to display the page
        urlCombo.setEnabled(false); // Disable input
        urlCombo.paintImmediately(0, 0, urlCombo.getSize().width, urlCombo.getSize().height);
        setCursor(waitCursor); // Busy cursor
        loadingState.setText("Loading...");
        loadingState.paintImmediately(0, 0, loadingState.getSize().width, loadingState.getSize().height);
        loadedType.setText("");
        loadedType.paintImmediately(0, 0, loadedType.getSize().width, loadedType.getSize().height);

        timeLabel.setText("");
        timeLabel.paintImmediately(0, 0, timeLabel.getSize().width, timeLabel.getSize().height);

        // Display an empty tree while loading
        tree.setModel(emptyModel);
        tree.paintImmediately(0, 0, tree.getSize().width, tree.getSize().height);

        startTime = System.currentTimeMillis();

        // Choose the loading method
        if (onlineLoad.isSelected()) {
            // Usual load via setPage
            pane.setPage(url);
            loadedType.setText(pane.getContentType());
        } else {
            pane.setContentType("text/html");
            loadedType.setText(pane.getContentType());
            if (loader == null) {
                loader = new HTMLDocumentLoader();
            }
            HTMLDocument doc = loader.loadDocument(url);
            loadComplete();
            pane.setDocument(doc);
            displayLoadTime();
            populateCombo(findLinks(doc, null));
            TreeNode node = buildHeadingTree(doc);
            tree.setModel(new DefaultTreeModel(node));
            enableInput();
            loadingPage = false;
        }
    } catch (Exception e) {
        System.out.println(e);
        JOptionPane.showMessageDialog(pane, new String[] { "Unable to open file", page.toString() },
                "File Open Error", JOptionPane.ERROR_MESSAGE);
        loadingState.setText("Failed");
        enableInput();
        loadingPage = false;
    }
}

From source file:BasicDnD.java

public BasicDnD() {
    super(new BorderLayout());
    JPanel leftPanel = createVerticalBoxPanel();
    JPanel rightPanel = createVerticalBoxPanel();

    // Create a table model.
    DefaultTableModel tm = new DefaultTableModel();
    tm.addColumn("Column 0");
    tm.addColumn("Column 1");
    tm.addColumn("Column 2");
    tm.addColumn("Column 3");
    tm.addRow(new String[] { "Table 00", "Table 01", "Table 02", "Table 03" });
    tm.addRow(new String[] { "Table 10", "Table 11", "Table 12", "Table 13" });
    tm.addRow(new String[] { "Table 20", "Table 21", "Table 22", "Table 23" });
    tm.addRow(new String[] { "Table 30", "Table 31", "Table 32", "Table 33" });

    // LEFT COLUMN
    // Use the table model to create a table.
    table = new JTable(tm);
    leftPanel.add(createPanelForComponent(table, "JTable"));

    // Create a color chooser.
    colorChooser = new JColorChooser();
    leftPanel.add(createPanelForComponent(colorChooser, "JColorChooser"));

    // RIGHT COLUMN
    // Create a textfield.
    textField = new JTextField(30);
    textField.setText("Favorite foods:\nPizza, Moussaka, Pot roast");
    rightPanel.add(createPanelForComponent(textField, "JTextField"));

    // Create a scrolled text area.
    textArea = new JTextArea(5, 30);
    textArea.setText("Favorite shows:\nBuffy, Alias, Angel");
    JScrollPane scrollPane = new JScrollPane(textArea);
    rightPanel.add(createPanelForComponent(scrollPane, "JTextArea"));

    // Create a list model and a list.
    DefaultListModel listModel = new DefaultListModel();
    listModel.addElement("Martha Washington");
    listModel.addElement("Abigail Adams");
    listModel.addElement("Martha Randolph");
    listModel.addElement("Dolley Madison");
    listModel.addElement("Elizabeth Monroe");
    listModel.addElement("Louisa Adams");
    listModel.addElement("Emily Donelson");
    list = new JList(listModel);
    list.setVisibleRowCount(-1);// w w w . j  av a2s .  c  om
    list.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    list.setTransferHandler(new TransferHandler() {

        public boolean canImport(TransferHandler.TransferSupport info) {
            // we only import Strings
            if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                return false;
            }

            JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
            if (dl.getIndex() == -1) {
                return false;
            }
            return true;
        }

        public boolean importData(TransferHandler.TransferSupport info) {
            if (!info.isDrop()) {
                return false;
            }

            // Check for String flavor
            if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                displayDropLocation("List doesn't accept a drop of this type.");
                return false;
            }

            JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
            DefaultListModel listModel = (DefaultListModel) list.getModel();
            int index = dl.getIndex();
            boolean insert = dl.isInsert();
            // Get the current string under the drop.
            String value = (String) listModel.getElementAt(index);

            // Get the string that is being dropped.
            Transferable t = info.getTransferable();
            String data;
            try {
                data = (String) t.getTransferData(DataFlavor.stringFlavor);
            } catch (Exception e) {
                return false;
            }

            // Display a dialog with the drop information.
            String dropValue = "\"" + data + "\" dropped ";
            if (dl.isInsert()) {
                if (dl.getIndex() == 0) {
                    displayDropLocation(dropValue + "at beginning of list");
                } else if (dl.getIndex() >= list.getModel().getSize()) {
                    displayDropLocation(dropValue + "at end of list");
                } else {
                    String value1 = (String) list.getModel().getElementAt(dl.getIndex() - 1);
                    String value2 = (String) list.getModel().getElementAt(dl.getIndex());
                    displayDropLocation(dropValue + "between \"" + value1 + "\" and \"" + value2 + "\"");
                }
            } else {
                displayDropLocation(dropValue + "on top of " + "\"" + value + "\"");
            }

            /**
             * This is commented out for the basicdemo.html tutorial page. * If you
             * add this code snippet back and delete the * "return false;" line, the
             * list will accept drops * of type string. // Perform the actual
             * import. if (insert) { listModel.add(index, data); } else {
             * listModel.set(index, data); } return true;
             */
            return false;
        }

        public int getSourceActions(JComponent c) {
            return COPY;
        }

        protected Transferable createTransferable(JComponent c) {
            JList list = (JList) c;
            Object[] values = list.getSelectedValues();

            StringBuffer buff = new StringBuffer();

            for (int i = 0; i < values.length; i++) {
                Object val = values[i];
                buff.append(val == null ? "" : val.toString());
                if (i != values.length - 1) {
                    buff.append("\n");
                }
            }
            return new StringSelection(buff.toString());
        }
    });
    list.setDropMode(DropMode.ON_OR_INSERT);

    JScrollPane listView = new JScrollPane(list);
    listView.setPreferredSize(new Dimension(300, 100));
    rightPanel.add(createPanelForComponent(listView, "JList"));

    // Create a tree.
    DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Mia Familia");
    DefaultMutableTreeNode sharon = new DefaultMutableTreeNode("Sharon");
    rootNode.add(sharon);
    DefaultMutableTreeNode maya = new DefaultMutableTreeNode("Maya");
    sharon.add(maya);
    DefaultMutableTreeNode anya = new DefaultMutableTreeNode("Anya");
    sharon.add(anya);
    sharon.add(new DefaultMutableTreeNode("Bongo"));
    maya.add(new DefaultMutableTreeNode("Muffin"));
    anya.add(new DefaultMutableTreeNode("Winky"));
    DefaultTreeModel model = new DefaultTreeModel(rootNode);
    tree = new JTree(model);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    JScrollPane treeView = new JScrollPane(tree);
    treeView.setPreferredSize(new Dimension(300, 100));
    rightPanel.add(createPanelForComponent(treeView, "JTree"));

    // Create the toggle button.
    toggleDnD = new JCheckBox("Turn on Drag and Drop");
    toggleDnD.setActionCommand("toggleDnD");
    toggleDnD.addActionListener(this);

    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
    splitPane.setOneTouchExpandable(true);

    add(splitPane, BorderLayout.CENTER);
    add(toggleDnD, BorderLayout.PAGE_END);
    setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
}

From source file:EditorPaneExample15.java

public void loadNewPage(Object page) {
    try {/* w  w  w .j  av a2s. c  o m*/
        loadingPage = true;

        // Check if the new page and the old
        // page are the same.
        URL url;
        if (page instanceof URL) {
            url = (URL) page;
        } else {
            url = new URL((String) page);
        }

        urlCombo.setSelectedItem(page);

        URL loadedURL = pane.getPage();
        if (loadedURL != null && loadedURL.sameFile(url)) {
            return;
        }

        // Try to display the page
        urlCombo.setEnabled(false); // Disable input
        urlCombo.paintImmediately(0, 0, urlCombo.getSize().width, urlCombo.getSize().height);
        setCursor(waitCursor); // Busy cursor
        loadingState.setText("Loading...");
        loadingState.paintImmediately(0, 0, loadingState.getSize().width, loadingState.getSize().height);
        loadedType.setText("");
        loadedType.paintImmediately(0, 0, loadedType.getSize().width, loadedType.getSize().height);

        timeLabel.setText("");
        timeLabel.paintImmediately(0, 0, timeLabel.getSize().width, timeLabel.getSize().height);

        // Display an empty tree while loading
        tree.setModel(emptyModel);
        tree.paintImmediately(0, 0, tree.getSize().width, tree.getSize().height);

        startTime = System.currentTimeMillis();

        // Choose the loading method
        if (onlineLoad.isSelected()) {
            // Usual load via setPage
            pane.setPage(url);
            loadedType.setText(pane.getContentType());
        } else {
            pane.setContentType("text/html");
            loadedType.setText(pane.getContentType());
            if (loader == null) {
                loader = new HTMLDocumentLoader();
            }
            HTMLDocument doc = loader.loadDocument(url);

            // Modify styles for this document only
            modifyStyleSheet(doc.getStyleSheet());

            loadComplete();
            pane.setDocument(doc);
            displayLoadTime();
            populateCombo(findLinks(doc, null));
            TreeNode node = buildHeadingTree(doc);
            tree.setModel(new DefaultTreeModel(node));
            enableInput();
            loadingPage = false;
        }
    } catch (Exception e) {
        System.out.println(e);
        JOptionPane.showMessageDialog(pane, new String[] { "Unable to open file", page.toString() },
                "File Open Error", JOptionPane.ERROR_MESSAGE);
        loadingState.setText("Failed");
        enableInput();
        loadingPage = false;
    }
}

From source file:EditorPaneExample16.java

public void loadNewPage(Object page) {
    try {/*from   www.ja  v  a  2  s .c o  m*/
        loadingPage = true;

        // Check if the new page and the old
        // page are the same.
        URL url;
        if (page instanceof URL) {
            url = (URL) page;
        } else {
            url = new URL((String) page);
        }

        urlCombo.setSelectedItem(page);

        URL loadedURL = pane.getPage();
        if (loadedURL != null && loadedURL.sameFile(url)) {
            return;
        }

        // Try to display the page
        urlCombo.setEnabled(false); // Disable input
        urlCombo.paintImmediately(0, 0, urlCombo.getSize().width, urlCombo.getSize().height);
        setCursor(waitCursor); // Busy cursor
        loadingState.setText("Loading...");
        loadingState.paintImmediately(0, 0, loadingState.getSize().width, loadingState.getSize().height);
        loadedType.setText("");
        loadedType.paintImmediately(0, 0, loadedType.getSize().width, loadedType.getSize().height);

        timeLabel.setText("");
        timeLabel.paintImmediately(0, 0, timeLabel.getSize().width, timeLabel.getSize().height);

        // Display an empty tree while loading
        tree.setModel(emptyModel);
        tree.paintImmediately(0, 0, tree.getSize().width, tree.getSize().height);

        startTime = System.currentTimeMillis();

        // Choose the loading method
        if (onlineLoad.isSelected()) {
            // Usual load via setPage
            pane.setPage(url);
            loadedType.setText(pane.getContentType());
        } else {
            pane.setContentType("text/html");
            loadedType.setText(pane.getContentType());
            if (loader == null) {
                loader = new HTMLDocumentLoader();
            }
            HTMLDocument doc = loader.loadDocument(url);

            loadComplete();
            pane.setDocument(doc);
            displayLoadTime();
            populateCombo(findLinks(doc, null));
            TreeNode node = buildHeadingTree(doc);
            tree.setModel(new DefaultTreeModel(node));
            enableInput();
            loadingPage = false;
        }
    } catch (Exception e) {
        System.out.println(e);
        JOptionPane.showMessageDialog(pane, new String[] { "Unable to open file", page.toString() },
                "File Open Error", JOptionPane.ERROR_MESSAGE);
        loadingState.setText("Failed");
        enableInput();
        loadingPage = false;
    }
}

From source file:display.containers.FileManager.java

public Container getPane() {
    //if (gui==null) {

    fileSystemView = FileSystemView.getFileSystemView();
    desktop = Desktop.getDesktop();

    JPanel detailView = new JPanel(new BorderLayout(3, 3));
    //fileTableModel = new FileTableModel();

    table = new JTable();
    table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    table.setAutoCreateRowSorter(true);// w w  w.  j  a v a 2  s .c  o  m
    table.setShowVerticalLines(false);
    table.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            if (e.getClickCount() >= 2) {
                Point p = e.getPoint();
                int row = table.convertRowIndexToModel(table.rowAtPoint(p));
                int column = table.convertColumnIndexToModel(table.columnAtPoint(p));
                if (row >= 0 && column >= 0) {
                    mouseDblClicked(row, column);
                }
            }
        }
    });
    table.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent arg0) {

        }

        @Override
        public void keyReleased(KeyEvent arg0) {
            if (KeyEvent.VK_DELETE == arg0.getKeyCode()) {
                if (mode != 2) {
                    parentFrame.setLock(true);
                    parentFrame.getProgressBarPanel().setVisible(true);
                    Thread t = new Thread(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                deleteSelectedFiles();
                            } catch (IOException e) {
                                JOptionPane.showMessageDialog(parentFrame, "Error during the deletion.",
                                        "Deletion error", JOptionPane.ERROR_MESSAGE);
                                WindowManager.mwLogger.log(Level.SEVERE, "Error during the deletion.", e);
                            } finally {
                                parentFrame.setLock(false);
                                refresh();
                                parentFrame.getProgressBarPanel().setVisible(false);
                            }
                        }
                    });
                    t.start();

                } else {
                    if (UserProfile.CURRENT_USER.getLevel() == 3) {
                        parentFrame.setLock(true);
                        parentFrame.getProgressBarPanel().setVisible(true);
                        Thread delThread = new Thread(new Runnable() {

                            @Override
                            public void run() {
                                int[] rows = table.getSelectedRows();
                                int[] columns = table.getSelectedColumns();
                                for (int i = 0; i < rows.length; i++) {
                                    if (!continueAction) {
                                        continueAction = true;
                                        return;
                                    }
                                    int row = table.convertRowIndexToModel(rows[i]);
                                    try {
                                        deleteServerFile(row);
                                    } catch (Exception e) {
                                        WindowManager.mwLogger.log(Level.SEVERE, "Error during the deletion.",
                                                e);
                                    }
                                }
                                refresh();
                                parentFrame.setLock(false);
                                parentFrame.getProgressBarPanel().setVisible(false);
                            }
                        });
                        delThread.start();

                    }
                }
            }
        }

        @Override
        public void keyPressed(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }
    });
    table.getSelectionModel().addListSelectionListener(listSelectionListener);
    JScrollPane tableScroll = new JScrollPane(table);
    Dimension d = tableScroll.getPreferredSize();
    tableScroll.setPreferredSize(new Dimension((int) d.getWidth(), (int) d.getHeight() / 2));
    detailView.add(tableScroll, BorderLayout.CENTER);

    // the File tree
    DefaultMutableTreeNode root = new DefaultMutableTreeNode();
    treeModel = new DefaultTreeModel(root);
    table.getRowSorter().addRowSorterListener(new RowSorterListener() {

        @Override
        public void sorterChanged(RowSorterEvent e) {
            ((FileTableModel) table.getModel()).fireTableDataChanged();
        }
    });

    // show the file system roots.
    File[] roots = fileSystemView.getRoots();
    for (File fileSystemRoot : roots) {
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(fileSystemRoot);
        root.add(node);
        //showChildren(node);
        //
        File[] files = fileSystemView.getFiles(fileSystemRoot, true);
        for (File file : files) {
            if (file.isDirectory()) {
                node.add(new DefaultMutableTreeNode(file));
            }
        }
        //
    }
    JScrollPane treeScroll = new JScrollPane();

    Dimension preferredSize = treeScroll.getPreferredSize();
    Dimension widePreferred = new Dimension(200, (int) preferredSize.getHeight());
    treeScroll.setPreferredSize(widePreferred);

    JPanel fileView = new JPanel(new BorderLayout(3, 3));

    detailView.add(fileView, BorderLayout.SOUTH);

    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, treeScroll, detailView);

    JPanel simpleOutput = new JPanel(new BorderLayout(3, 3));
    progressBar = new JProgressBar();
    simpleOutput.add(progressBar, BorderLayout.EAST);
    progressBar.setVisible(false);
    showChildren(getCurrentDir().toPath());
    //table.setDragEnabled(true);
    table.setColumnSelectionAllowed(false);

    // Menu popup
    Pmenu = new JPopupMenu();
    changeProjectitem = new JMenuItem("Reassign");
    renameProjectitem = new JMenuItem("Rename");
    twitem = new JMenuItem("To workspace");
    tlitem = new JMenuItem("To local");
    processitem = new JMenuItem("Select for process");
    switch (mode) {
    case 0:
        Pmenu.add(twitem);
        twitem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                parentFrame.getBtnlocalTowork().doClick();
            }
        });
        break;
    case 1:
        Pmenu.add(tlitem);
        Pmenu.add(processitem);
        tlitem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                parentFrame.getBtnWorkTolocal().doClick();
            }
        });
        processitem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        // Recupere les lignes selectionnees
                        int[] indices = table.getSelectedRows();
                        // On recupere les fichiers correspondants
                        ArrayList<File> files = new ArrayList<File>();
                        for (int i = 0; i < indices.length; i++) {
                            int row = table.convertRowIndexToModel(indices[i]);
                            File fi = ((FileTableModel) table.getModel()).getFile(row);
                            if (fi.isDirectory())
                                files.add(fi);
                        }
                        ImageProcessingFrame imf = new ImageProcessingFrame(files);
                    }
                });

            }
        });
        break;
    case 2:
        if (UserProfile.CURRENT_USER.getLevel() == 3) {
            Pmenu.add(changeProjectitem);
            Pmenu.add(renameProjectitem);
        }
        Pmenu.add(twitem);
        twitem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                parentFrame.getBtndistToWorkspace().doClick();
            }
        });
        Pmenu.add(tlitem);
        tlitem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                parentFrame.getBtndistToLocal().doClick();
            }
        });
        break;
    }
    changeProjectitem.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            table.setEnabled(false);
            File from = ((FileTableModel) table.getModel())
                    .getFile(table.convertRowIndexToModel(table.getSelectedRows()[0]));

            ReassignProjectPanel reas = new ReassignProjectPanel(from.toPath()); // mode creation de liens
            Popup popup = PopupFactory.getSharedInstance().getPopup(WindowManager.MAINWINDOW, reas,
                    (int) WindowManager.MAINWINDOW.getX() + 200, (int) WindowManager.MAINWINDOW.getY() + 150);
            reas.setPopupWindow(popup);
            popup.show();
            table.setEnabled(true);
        }
    });
    renameProjectitem.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            table.setEnabled(false);
            final File from = ((FileTableModel) table.getModel())
                    .getFile(table.convertRowIndexToModel(table.getSelectedRows()[0]));
            JDialog.setDefaultLookAndFeelDecorated(true);
            String s = (String) JOptionPane.showInputDialog(WindowManager.MAINWINDOW, "New project name ?",
                    "Rename project", JOptionPane.PLAIN_MESSAGE, null, null, from.getName());

            //If a string was returned, say so.
            if ((s != null) && (s.length() > 0)) {
                ProjectDAO pdao = new MySQLProjectDAO();
                if (new File(from.getParent() + File.separator + s).exists()) {
                    SwingUtilities.invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            JDialog.setDefaultLookAndFeelDecorated(true);
                            JOptionPane.showMessageDialog(WindowManager.MAINWINDOW,
                                    "Couldn't rename " + from.getName()
                                            + " (A file with this filename already exists)",
                                    "Renaming error", JOptionPane.ERROR_MESSAGE);
                        }
                    });
                    WindowManager.mwLogger.log(Level.SEVERE,
                            "Error during file project renaming (" + from.getName() + "). [Duplication error]");
                } else {
                    try {
                        boolean succeed = pdao.renameProject(from.getName(), s);
                        if (!succeed) {
                            SwingUtilities.invokeLater(new Runnable() {

                                @Override
                                public void run() {
                                    JDialog.setDefaultLookAndFeelDecorated(true);
                                    JOptionPane.showMessageDialog(WindowManager.MAINWINDOW,
                                            "Couldn't rename " + from.getName()
                                                    + " (no project with this name)",
                                            "Renaming error", JOptionPane.ERROR_MESSAGE);
                                }
                            });
                        } else {
                            from.renameTo(new File(from.getParent() + File.separator + s));
                            // on renomme le repertoire nifti ou dicom correspondant si il existe
                            switch (from.getParentFile().getName()) {
                            case ServerInfo.NRI_ANALYSE_NAME:
                                if (new File(from.getAbsolutePath().replaceAll(ServerInfo.NRI_ANALYSE_NAME,
                                        ServerInfo.NRI_DICOM_NAME)).exists())
                                    try {
                                        Files.move(Paths.get(from.getAbsolutePath().replaceAll(
                                                ServerInfo.NRI_ANALYSE_NAME, ServerInfo.NRI_DICOM_NAME)),
                                                Paths.get(from.getParent().replaceAll(
                                                        ServerInfo.NRI_ANALYSE_NAME, ServerInfo.NRI_DICOM_NAME)
                                                        + File.separator + s));
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                        SwingUtilities.invokeLater(new Runnable() {

                                            @Override
                                            public void run() {
                                                JDialog.setDefaultLookAndFeelDecorated(true);
                                                JOptionPane.showMessageDialog(WindowManager.MAINWINDOW,
                                                        "Couldn't rename " + from.getName()
                                                                + " (error with file system)",
                                                        "Renaming error", JOptionPane.ERROR_MESSAGE);
                                            }
                                        });
                                        WindowManager.mwLogger.log(Level.SEVERE,
                                                "Error during file project renaming (" + from.getName() + ")",
                                                e);
                                    } //from.renameTo(new File(from.getParent().replaceAll(ServerInfo.NRI_ANALYSE_NAME, ServerInfo.NRI_DICOM_NAME)+File.separator+s));
                                break;
                            case ServerInfo.NRI_DICOM_NAME:
                                if (new File(from.getAbsolutePath().replaceAll(ServerInfo.NRI_DICOM_NAME,
                                        ServerInfo.NRI_ANALYSE_NAME)).exists())
                                    try {
                                        Files.move(Paths.get(from.getAbsolutePath().replaceAll(
                                                ServerInfo.NRI_DICOM_NAME, ServerInfo.NRI_ANALYSE_NAME)),
                                                Paths.get(from.getParent().replaceAll(ServerInfo.NRI_DICOM_NAME,
                                                        ServerInfo.NRI_ANALYSE_NAME) + File.separator + s));
                                    } catch (IOException e) {
                                        SwingUtilities.invokeLater(new Runnable() {

                                            @Override
                                            public void run() {
                                                JDialog.setDefaultLookAndFeelDecorated(true);
                                                JOptionPane.showMessageDialog(WindowManager.MAINWINDOW,
                                                        "Couldn't rename " + from.getName()
                                                                + " (error with file system)",
                                                        "Renaming error", JOptionPane.ERROR_MESSAGE);
                                            }
                                        });
                                        e.printStackTrace();
                                        WindowManager.mwLogger.log(Level.SEVERE,
                                                "Error during file project renaming (" + from.getName() + ")",
                                                e);
                                    } //from.renameTo(new File(from.getParent().replaceAll(ServerInfo.NRI_DICOM_NAME, ServerInfo.NRI_ANALYSE_NAME)+File.separator+s));
                                break;
                            }
                            refresh();
                        }
                    } catch (final SQLException e) {
                        WindowManager.mwLogger.log(Level.SEVERE, "Error during SQL project renaming", e);
                        SwingUtilities.invokeLater(new Runnable() {

                            @Override
                            public void run() {
                                JDialog.setDefaultLookAndFeelDecorated(true);
                                JOptionPane.showMessageDialog(WindowManager.MAINWINDOW,
                                        "Exception : " + e.toString(), "Openning error",
                                        JOptionPane.ERROR_MESSAGE);
                            }
                        });
                    }
                }
            }
            table.setEnabled(true);
        }
    });
    table.addMouseListener(new MouseListener() {

        public void mouseClicked(MouseEvent me) {

        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent me) {
            if (me.getButton() == 3 && table.getSelectedRowCount() > 0) {
                int row = table.convertRowIndexToModel(table.rowAtPoint(me.getPoint()));
                changeProjectitem.setVisible(isPatient(((FileTableModel) table.getModel()).getFile(row)));
                renameProjectitem.setVisible(isProject(((FileTableModel) table.getModel()).getFile(row)));
                Pmenu.show(me.getComponent(), me.getX(), me.getY());
            }
        }
    });
    //

    //}
    return tableScroll;
}

From source file:EditorPaneExample19.java

public void loadNewPage(Object page) {
    try {//from  w w  w. jav a2s  .com
        loadingPage = true;

        // Check if the new page and the old
        // page are the same.
        URL url;
        if (page instanceof URL) {
            url = (URL) page;
        } else {
            url = new URL((String) page);
        }

        urlCombo.setSelectedItem(page);

        URL loadedURL = pane.getPage();
        if (loadedURL != null && loadedURL.sameFile(url)) {
            return;
        }

        enableMenuBar(false);
        urlCombo.paintImmediately(0, 0, menuBar.getSize().width, menuBar.getSize().height);

        // Try to display the page
        urlCombo.setEnabled(false); // Disable input
        urlCombo.paintImmediately(0, 0, urlCombo.getSize().width, urlCombo.getSize().height);
        setCursor(waitCursor); // Busy cursor
        loadingState.setText("Loading...");
        loadingState.paintImmediately(0, 0, loadingState.getSize().width, loadingState.getSize().height);
        loadedType.setText("");
        loadedType.paintImmediately(0, 0, loadedType.getSize().width, loadedType.getSize().height);

        timeLabel.setText("");
        timeLabel.paintImmediately(0, 0, timeLabel.getSize().width, timeLabel.getSize().height);

        // Display an empty tree while loading
        tree.setModel(emptyModel);
        tree.paintImmediately(0, 0, tree.getSize().width, tree.getSize().height);

        startTime = System.currentTimeMillis();

        // Choose the loading method               
        if (onlineLoad.isSelected()) {
            // Usual load via setPage
            pane.setPage(url);
            loadedType.setText(pane.getContentType());
        } else {
            pane.setContentType("text/html");
            loadedType.setText(pane.getContentType());
            if (loader == null) {
                loader = new HTMLDocumentLoader();
            }
            HTMLDocument doc = loader.loadDocument(url);

            loadComplete();
            pane.setDocument(doc);
            displayLoadTime();
            populateCombo(findLinks(doc, null));
            TreeNode node = buildHeadingTree(doc);
            tree.setModel(new DefaultTreeModel(node));

            createMenuBar();
            enableMenuBar(true);
            getRootPane().revalidate();

            enableInput();
            loadingPage = false;
        }
    } catch (Exception e) {
        System.out.println(e);
        JOptionPane.showMessageDialog(pane, new String[] { "Unable to open file", page.toString() },
                "File Open Error", JOptionPane.ERROR_MESSAGE);
        loadingState.setText("Failed");
        enableMenuBar(true);
        enableInput();
        loadingPage = false;
    }
}

From source file:edu.mbl.jif.datasetconvert.CheckboxTreeDimensions.java

protected TreeModel getDimensionsTreeModel(JSONObject sumMD_In) {
    try {/*from   w w w .  ja v a 2s. c om*/
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("All");
        DefaultMutableTreeNode parent;
        DimensionalExtents dsdIn = SumMetadata.getDimensionalExtents(sumMD_In);
        parent = new DefaultMutableTreeNode("Channel");
        root.add(parent);
        channelNamesOriginal = SumMetadata.getChannelNames(sumMD_In);
        for (int chan = 0; chan < dsdIn.numChannels; chan++) {
            parent.add(new DefaultMutableTreeNode(channelNamesOriginal[chan]));
        }
        if (dsdIn.numSlices > 1) {
            parent = new DefaultMutableTreeNode("Z-Section");
            root.add(parent);
            for (int slice = 0; slice < dsdIn.numSlices; slice++) {
                parent.add(new DefaultMutableTreeNode(slice));
            }
        }
        if (dsdIn.numFrames > 1) {
            parent = new DefaultMutableTreeNode("TimePoint");
            root.add(parent);
            for (int frame = 0; frame < dsdIn.numFrames; frame++) {
                parent.add(new DefaultMutableTreeNode(frame));
            }
        }
        if (dsdIn.numPositions > 1) {
            parent = new DefaultMutableTreeNode("Position");
            root.add(parent);
            for (int pos = 0; pos < dsdIn.numPositions; pos++) {
                parent.add(new DefaultMutableTreeNode(pos));
            }
        }
        return new DefaultTreeModel(root);
    } catch (Exception ex) {
        Logger.getLogger(CheckboxTreeDimensions.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:org.dcm4chee.dashboard.ui.filesystem.FileSystemPanel.java

@Override
public void onBeforeRender() {
    super.onBeforeRender();

    try {/*from  w  w w .j a  va2 s  .  c o m*/
        DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(new FileSystemModel());
        for (String groupname : DashboardDelegator
                .getInstance(
                        (((BaseWicketApplication) getApplication()).getInitParameter("DashboardServiceName")))
                .listAllFileSystemGroups()) {
            FileSystemModel group = new FileSystemModel();

            int index = groupname.indexOf("group=");
            if (index < 0)
                continue;
            group.setDirectoryPath(groupname.substring(index + 6));
            group.setDescription(groupname + ",AET=" + DashboardDelegator.getInstance(
                    (((BaseWicketApplication) getApplication()).getInitParameter("DashboardServiceName")))
                    .getDefaultRetrieveAETitle(groupname));
            group.setGroup(true);
            DefaultMutableTreeNode groupNode;
            rootNode.add(groupNode = new DefaultMutableTreeNode(group));

            File[] fileSystems = null;
            try {
                fileSystems = DashboardDelegator.getInstance(
                        (((BaseWicketApplication) getApplication()).getInitParameter("DashboardServiceName")))
                        .listFileSystemsOfGroup(groupname);
            } catch (MBeanException mbe) {
            }

            if (!((fileSystems == null) || (fileSystems.length == 0))) {
                long minBytesFree = DashboardDelegator.getInstance(
                        (((BaseWicketApplication) getApplication()).getInitParameter("DashboardServiceName")))
                        .getMinimumFreeDiskSpaceOfGroup(groupname);

                for (File file : fileSystems) {
                    FileSystemModel fsm = new FileSystemModel();
                    fsm.setDirectoryPath(file.getName());
                    fsm.setDescription(
                            file.getName().startsWith("tar:") ? file.getName() : file.getAbsolutePath());
                    fsm.setOverallDiskSpace(file.getTotalSpace() / FileSystemModel.MEGA);
                    fsm.setUsedDiskSpace(
                            Math.max((file.getTotalSpace() - file.getUsableSpace()) / FileSystemModel.MEGA, 0));
                    fsm.setFreeDiskSpace(Math.max(file.getUsableSpace() / FileSystemModel.MEGA, 0));
                    fsm.setMinimumFreeDiskSpace(
                            fsm.getOverallDiskSpaceLong() == 0 ? 0 : minBytesFree / FileSystemModel.MEGA);
                    fsm.setUsableDiskSpace(
                            Math.max((file.getUsableSpace() - minBytesFree) / FileSystemModel.MEGA, 0));
                    fsm.setRemainingTime(Math.max((file.getUsableSpace() - minBytesFree) / DashboardDelegator
                            .getInstance((((BaseWicketApplication) getApplication())
                                    .getInitParameter("DashboardServiceName")))
                            .getExpectedDataVolumePerDay(groupname), 0));

                    group.setOverallDiskSpace(group.getOverallDiskSpaceLong() + fsm.getOverallDiskSpaceLong());
                    group.setUsedDiskSpace(group.getUsedDiskSpaceLong() + fsm.getUsedDiskSpaceLong());
                    group.setFreeDiskSpace(group.getFreeDiskSpaceLong() + fsm.getFreeDiskSpaceLong());
                    group.setMinimumFreeDiskSpace(
                            group.getMinimumFreeDiskSpaceLong() + fsm.getMinimumFreeDiskSpaceLong());
                    group.setUsableDiskSpace(group.getUsableDiskSpaceLong() + fsm.getUsableDiskSpaceLong());
                    group.setRemainingTime(group.getRemainingTime() + fsm.getRemainingTime());
                    groupNode.add(new DefaultMutableTreeNode(fsm));
                }
            }
        }

        String[] otherFileSystems = DashboardDelegator
                .getInstance(
                        (((BaseWicketApplication) getApplication()).getInitParameter("DashboardServiceName")))
                .listOtherFileSystems();
        if (otherFileSystems != null && otherFileSystems.length > 0) {

            FileSystemModel group = new FileSystemModel();
            group.setDirectoryPath(
                    new ResourceModel("dashboard.filesystem.group.other").wrapOnAssignment(this).getObject());
            group.setGroup(true);
            group.setRemainingTime(-1);
            DefaultMutableTreeNode groupNode;
            rootNode.add(groupNode = new DefaultMutableTreeNode(group));

            for (String otherFileSystem : otherFileSystems) {
                File file = new File(otherFileSystem);
                FileSystemModel fsm = new FileSystemModel();
                fsm.setDirectoryPath(file.getAbsolutePath());
                fsm.setDescription(file.getName().startsWith("tar:") ? file.getName() : file.getAbsolutePath());
                fsm.setOverallDiskSpace(file.getTotalSpace() / FileSystemModel.MEGA);
                fsm.setUsedDiskSpace(
                        Math.max((file.getTotalSpace() - file.getUsableSpace()) / FileSystemModel.MEGA, 0));
                fsm.setFreeDiskSpace(Math.max(file.getUsableSpace() / FileSystemModel.MEGA, 0));
                fsm.setMinimumFreeDiskSpace(fsm.getOverallDiskSpaceLong() / FileSystemModel.MEGA);
                fsm.setUsableDiskSpace(Math.max(file.getUsableSpace() / FileSystemModel.MEGA, 0));
                fsm.setRemainingTime(-1);

                group.setOverallDiskSpace(group.getOverallDiskSpaceLong() + fsm.getOverallDiskSpaceLong());
                group.setUsedDiskSpace(group.getUsedDiskSpaceLong() + fsm.getUsedDiskSpaceLong());
                group.setFreeDiskSpace(group.getFreeDiskSpaceLong() + fsm.getFreeDiskSpaceLong());
                group.setMinimumFreeDiskSpace(
                        group.getMinimumFreeDiskSpaceLong() + fsm.getMinimumFreeDiskSpaceLong());
                group.setUsableDiskSpace(group.getUsableDiskSpaceLong() + fsm.getUsableDiskSpaceLong());
                group.setVisible(false);
                groupNode.add(new DefaultMutableTreeNode(fsm));
            }
        }

        FileSystemTreeTable fileSystemTreeTable = new FileSystemTreeTable("filesystem-tree-table",
                new DefaultTreeModel(rootNode),
                new IColumn[] {
                        new PropertyTreeColumn(new ColumnLocation(Alignment.LEFT, 25, Unit.PERCENT),
                                new ResourceModel("dashboard.filesystem.table.column.name")
                                        .wrapOnAssignment(this).getObject(),
                                "userObject.directoryPath"),
                        new ImageRenderableColumn(new ColumnLocation(Alignment.MIDDLE, 30, Unit.PROPORTIONAL),
                                new ResourceModel("dashboard.filesystem.table.column.image")
                                        .wrapOnAssignment(this).getObject(),
                                "userObject.directoryPath"),
                        new PropertyRenderableColumn(new ColumnLocation(Alignment.RIGHT, 7, Unit.PERCENT),
                                new ResourceModel("dashboard.filesystem.table.column.overall")
                                        .wrapOnAssignment(this).getObject(),
                                "userObject.overallDiskSpaceString"),
                        new PropertyRenderableColumn(new ColumnLocation(Alignment.RIGHT, 7, Unit.PERCENT),
                                new ResourceModel("dashboard.filesystem.table.column.used")
                                        .wrapOnAssignment(this).getObject(),
                                "userObject.usedDiskSpaceString"),
                        new PropertyRenderableColumn(new ColumnLocation(Alignment.RIGHT, 7, Unit.PERCENT),
                                new ResourceModel("dashboard.filesystem.table.column.free")
                                        .wrapOnAssignment(this).getObject(),
                                "userObject.freeDiskSpaceString"),
                        new PropertyRenderableColumn(new ColumnLocation(Alignment.RIGHT, 7, Unit.PERCENT),
                                new ResourceModel("dashboard.filesystem.table.column.minimumfree")
                                        .wrapOnAssignment(this).getObject(),
                                "userObject.minimumFreeDiskSpaceString"),
                        new PropertyRenderableColumn(new ColumnLocation(Alignment.RIGHT, 7, Unit.PERCENT),
                                new ResourceModel("dashboard.filesystem.table.column.usable")
                                        .wrapOnAssignment(this).getObject(),
                                "userObject.usableDiskSpaceString"),
                        new PropertyRenderableColumn(new ColumnLocation(Alignment.RIGHT, 10, Unit.PERCENT),
                                new ResourceModel("dashboard.filesystem.table.column.remainingtime")
                                        .wrapOnAssignment(this).getObject(),
                                "userObject.remainingTimeString") });
        fileSystemTreeTable.getTreeState().setAllowSelectMultiple(true);
        fileSystemTreeTable.getTreeState().collapseAll();
        fileSystemTreeTable.setRootLess(true);
        addOrReplace(fileSystemTreeTable);
    } catch (Exception e) {
        log.error(this.getClass().toString() + ": " + "onBeforeRender: " + e.getMessage());
        log.debug("Exception: ", e);
        throw new WicketRuntimeException(e.getLocalizedMessage(), e);
    }
}

From source file:net.sf.jhylafax.addressbook.AddressBook.java

private void initializeContent() {
    horizontalSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    horizontalSplitPane.setBorder(GUIHelper.createEmptyBorder(5));

    rootNode = new DefaultMutableTreeNode();
    addressBookTreeModel = new DefaultTreeModel(rootNode);
    addressBookTree = new JTree(addressBookTreeModel);
    addressBookTree.setRootVisible(false);
    addressBookTree.setCellRenderer(new ContactCollectionCellRenderer());
    horizontalSplitPane.add(new JScrollPane(addressBookTree));

    JPanel contactPanel = new JPanel();
    contactPanel.setLayout(new BorderLayout(0, 10));
    horizontalSplitPane.add(contactPanel);

    DefaultFormBuilder builder = new DefaultFormBuilder(
            new FormLayout("min, 3dlu, min, 3dlu, pref:grow, 3dlu, min", ""));
    contactPanel.add(builder.getPanel(), BorderLayout.NORTH);

    searchTextField = new JTextField(10);
    EraseTextFieldAction eraseAction = new EraseTextFieldAction(searchTextField) {
        public void actionPerformed(ActionEvent event) {
            super.actionPerformed(event);
            filterAction.actionPerformed(event);
        };//from ww  w  .  j av a 2s  .  c o m
    };
    builder.append(new TabTitleButton(eraseAction));
    filterLabel = new JLabel();
    builder.append(filterLabel);
    builder.append(searchTextField);
    GUIHelper.bindEnterKey(searchTextField, filterAction);

    builder.append(Builder.createButton(filterAction));

    JPopupMenu tablePopupMenu = new JPopupMenu();
    tablePopupMenu.add(Builder.createMenuItem(newAction));
    tablePopupMenu.addSeparator();
    tablePopupMenu.add(Builder.createMenuItem(editAction));
    tablePopupMenu.addSeparator();
    tablePopupMenu.add(Builder.createMenuItem(deleteAction));

    contactTableModel = new AddressTableModel();
    TableSorter sorter = new TableSorter(contactTableModel);
    contactTable = new ColoredTable(sorter);
    contactTableLayoutManager = new TableLayoutManager(contactTable);
    contactTableLayoutManager.addColumnProperties("displayName", "", 180, true);
    contactTableLayoutManager.addColumnProperties("company", "", 80, true);
    contactTableLayoutManager.addColumnProperties("faxNumber", "", 60, true);
    contactTableLayoutManager.initializeTableLayout();
    contactPanel.add(new JScrollPane(contactTable), BorderLayout.CENTER);

    contactTable.setShowVerticalLines(true);
    contactTable.setShowHorizontalLines(false);
    contactTable.setAutoCreateColumnsFromModel(true);
    contactTable.setIntercellSpacing(new java.awt.Dimension(2, 1));
    contactTable.setBounds(0, 0, 50, 50);
    contactTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    contactTable.getSelectionModel().addListSelectionListener(this);
    contactTable.addMouseListener(new PopupListener(tablePopupMenu));
    contactTable.addMouseListener(new DoubleClickListener(new TableDoubleClickAction()));
    contactTable.setTransferHandler(new ContactTransferHandler());
    contactTable.setDragEnabled(true);

    contactTable.setDefaultRenderer(String.class, new StringCellRenderer());

    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(horizontalSplitPane, BorderLayout.CENTER);
}