Example usage for javax.swing JTree getLastSelectedPathComponent

List of usage examples for javax.swing JTree getLastSelectedPathComponent

Introduction

In this page you can find the example usage for javax.swing JTree getLastSelectedPathComponent.

Prototype

@BeanProperty(bound = false)
public Object getLastSelectedPathComponent() 

Source Link

Document

Returns the last path component of the selected path.

Usage

From source file:Main.java

public static void main(String[] args) {
    JFrame frame = new JFrame(Main.class.getSimpleName());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JTree tree = new JTree(createTreeModel(new File(System.getProperty("user.dir")), true));
    tree.setCellRenderer(new DefaultTreeCellRenderer() {
        @Override//www  .ja va2 s .c  o m
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
                boolean leaf, int row, boolean hasFocus) {
            super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
            if (value instanceof DefaultMutableTreeNode) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                if (node.getUserObject() instanceof File) {
                    setText(((File) node.getUserObject()).getName());
                }
            }
            return this;
        }
    });
    tree.getSelectionModel().addTreeSelectionListener(e -> {
        Object object = tree.getLastSelectedPathComponent();
        if (object instanceof DefaultMutableTreeNode) {
            Object userObject = ((DefaultMutableTreeNode) object).getUserObject();
            if (userObject instanceof File) {
                File file = (File) userObject;
                System.out.println(
                        "Selected file" + file.getAbsolutePath() + " Is directory? " + file.isDirectory());
            }
        }
    });
    JScrollPane pane = new JScrollPane(tree);
    frame.add(pane);
    frame.setSize(400, 600);
    frame.setVisible(true);
}

From source file:UsingTreeSelectionListener.java

public void valueChanged(TreeSelectionEvent se) {
    JTree tree = (JTree) se.getSource();
    DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
    String selectedNodeName = selectedNode.toString();
    if (selectedNode.isLeaf()) {

        System.out.println(selectedNodeName);

    }//w ww.j av a  2  s .c  om
}

From source file:it.unibas.spicygui.vista.listener.ConstraintColoringTreeSelectionListener.java

public void valueChanged(TreeSelectionEvent e) {
    JTree albero = (JTree) e.getSource();
    DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) albero.getLastSelectedPathComponent();
    if (treeNode == null) {
        return;// w ww  .java  2s . c  o m
    }
    TreeNodeAdapter adapter = (TreeNodeAdapter) treeNode.getUserObject();
    INode node = adapter.getINode();
    analyzeConnectionConstraints(node);
    analyzeJoinConditions(node);
    analyzeConnections(node);
}

From source file:Main.java

public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    TreeNode root = getNodes();// www.  j  a va  2 s.  c  o  m
    DefaultTreeModel model = new DefaultTreeModel(root);
    JTree tree = new JTree(model);
    tree.setRootVisible(false);

    JButton add = new JButton("add new");
    add.addActionListener(e -> {
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        if (selectedNode == null) {
            return;
        }
        MyObject obj = (MyObject) selectedNode.getUserObject();
        MyObject newChild = new MyObject(obj.name + "-" + (obj.childs.size() + 1));
        obj.childs.add(newChild);
        DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(newChild);
        model.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
        TreeNode[] nodes = model.getPathToRoot(newNode);
        TreePath path = new TreePath(nodes);
        tree.scrollPathToVisible(path);
    });

    JButton print = new JButton("print childs");
    print.addActionListener(e -> {
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        if (selectedNode == null) {
            return;
        }
        MyObject obj = (MyObject) selectedNode.getUserObject();
        System.out.println(obj.childs);
    });
    JPanel btns = new JPanel();
    btns.add(add);
    btns.add(print);

    add(new JScrollPane(tree));
    add(btns, BorderLayout.SOUTH);
    pack();
    setVisible(true);
}

From source file:wsattacker.plugin.intelligentdos.ui.dialog.Result_NB.java

private void resultTreeValueChanged(javax.swing.event.TreeSelectionEvent evt) {// GEN-FIRST:event_jTree1ValueChanged
    JTree tree = (JTree) evt.getSource();
    DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
    if (selectedNode != null && selectedNode.isLeaf()) {
        SuccessfulAttack sa = (SuccessfulAttack) selectedNode.getUserObject();
        jLabel1.setText(FormatHelper.toHTML(sa));

        StringBuilder builder = new StringBuilder();
        builder.append("<html>");
        String format = "-";
        if (!Double.isNaN(sa.getRatio())) {
            format = df.format(sa.getRatio());
        }/*w w  w .j  a v  a  2  s  . co  m*/
        builder.append("Attack roundtrip time ratio: ").append(format);
        builder.append("<br />");
        builder.append("the payload is ").append(sa.getEfficiency().name());
        builder.append("<br />");
        builder.append("<br />");
        double reuqestsPerSecond = ((int) (sa.getParamItem().getReuqestsPerSecond() * 100.0)) / 100.0;
        builder.append(reuqestsPerSecond).append(" requests per second were sent");
        builder.append("<br />");
        if (sa.getTamperedContent() != null) {
            long l = (long) (sa.getTamperedContent().getBytes(Charset.forName("UTF-8")).length
                    * sa.getParamItem().getReuqestsPerSecond());
            builder.append("the traffic was (approx) ").append(FileUtils.byteCountToDisplaySize(l))
                    .append(" per second");
        }

        builder.append("</html>");

        successMetric.setText(builder.toString());

        jTextArea1.setText(sa.getXmlWithPlaceholder());

        JFreeChart createOverlaidChart = ChartHelper.createOverlaidChart(sa);
        JFreeChart createWhiskerChart = ChartHelper.createWhiskerChart(sa);
        ((ChartPanel) chartPanel1).setChart(createOverlaidChart);
        ((ChartPanel) chartPanel2).setChart(createWhiskerChart);
    } else {
        jLabel1.setText("");
        successMetric.setText("");
    }
}

From source file:gov.sandia.umf.platform.ui.jobs.RunPanel.java

public RunPanel() {
    root = new NodeBase();
    model = new DefaultTreeModel(root);
    tree = new JTree(model);
    tree.setRootVisible(false);//w  w  w .  ja v  a2  s  .  c o m
    tree.setShowsRootHandles(true);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);

    tree.setCellRenderer(new DefaultTreeCellRenderer() {
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                boolean expanded, boolean leaf, int row, boolean hasFocus) {
            super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);

            NodeBase node = (NodeBase) value;
            Icon icon = node.getIcon(expanded); // A node knows whether it should hold other nodes or not, so don't pass leaf to it.
            if (icon == null) {
                if (leaf)
                    icon = getDefaultLeafIcon();
                else if (expanded)
                    icon = getDefaultOpenIcon();
                else
                    icon = getDefaultClosedIcon();
            }
            setIcon(icon);

            return this;
        }
    });

    tree.addTreeSelectionListener(new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent e) {
            NodeBase newNode = (NodeBase) tree.getLastSelectedPathComponent();
            if (newNode == null)
                return;
            if (newNode == displayNode)
                return;

            if (displayThread != null)
                synchronized (displayText) {
                    displayThread.stop = true;
                }
            displayNode = newNode;
            if (displayNode instanceof NodeFile)
                viewFile();
            else if (displayNode instanceof NodeJob)
                viewJob();
        }
    });

    tree.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent e) {
            int keycode = e.getKeyCode();
            if (keycode == KeyEvent.VK_DELETE || keycode == KeyEvent.VK_BACK_SPACE) {
                delete();
            }
        }
    });

    tree.addTreeWillExpandListener(new TreeWillExpandListener() {
        public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
            TreePath path = event.getPath(); // TODO: can this ever be null?
            Object o = path.getLastPathComponent();
            if (o instanceof NodeJob)
                ((NodeJob) o).build(tree);
        }

        public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
        }
    });

    tree.addTreeExpansionListener(new TreeExpansionListener() {
        public void treeExpanded(TreeExpansionEvent event) {
            Rectangle node = tree.getPathBounds(event.getPath());
            Rectangle visible = treePane.getViewport().getViewRect();
            visible.height -= node.y - visible.y;
            visible.y = node.y;
            tree.repaint(visible);
        }

        public void treeCollapsed(TreeExpansionEvent event) {
            Rectangle node = tree.getPathBounds(event.getPath());
            Rectangle visible = treePane.getViewport().getViewRect();
            visible.height -= node.y - visible.y;
            visible.y = node.y;
            tree.repaint(visible);
        }
    });

    Thread refreshThread = new Thread() {
        public void run() {
            try {
                // Initial load
                synchronized (running) {
                    for (MNode n : AppData.runs)
                        running.add(0, new NodeJob(n)); // This should be efficient on a doubly-linked list.
                    for (NodeJob job : running)
                        root.add(job);
                }
                EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        model.nodeStructureChanged(root);
                        if (model.getChildCount(root) > 0)
                            tree.setSelectionRow(0);
                    }
                });

                // Periodic refresh to show status of running jobs
                int shortCycles = 100; // Force full scan on first cycle.
                while (true) {
                    NodeBase d = displayNode; // Make local copy (atomic action) to prevent it changing from under us
                    if (d instanceof NodeJob)
                        ((NodeJob) d).monitorProgress(RunPanel.this);
                    if (shortCycles++ < 20) {
                        Thread.sleep(1000);
                        continue;
                    }
                    shortCycles = 0;

                    synchronized (running) {
                        Iterator<NodeJob> i = running.iterator();
                        while (i.hasNext()) {
                            NodeJob job = i.next();
                            if (job != d)
                                job.monitorProgress(RunPanel.this);
                            if (job.complete >= 1)
                                i.remove();
                        }
                    }
                }
            } catch (InterruptedException e) {
            }
        }
    };
    refreshThread.setDaemon(true);
    refreshThread.start();

    displayText = new JTextArea();
    displayText.setEditable(false);

    final JCheckBox chkFixedWidth = new JCheckBox("Fixed-Width Font");
    chkFixedWidth.setFocusable(false);
    chkFixedWidth.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int size = displayText.getFont().getSize();
            if (chkFixedWidth.isSelected()) {
                displayText.setFont(new Font(Font.MONOSPACED, Font.PLAIN, size));
            } else {
                displayText.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, size));
            }
        }
    });

    displayPane.setViewportView(displayText);

    ActionListener graphListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (displayNode instanceof NodeFile) {
                NodeFile nf = (NodeFile) displayNode;
                if (nf.type == NodeFile.Type.Output || nf.type == NodeFile.Type.Result) {
                    String graphType = e.getActionCommand();
                    if (displayPane.getViewport().getView() instanceof ChartPanel
                            && displayGraph.equals(graphType)) {
                        viewFile();
                        displayGraph = "";
                    } else {
                        if (graphType.equals("Graph")) {
                            Plot plot = new Plot(nf.path.getAbsolutePath());
                            if (!plot.columns.isEmpty())
                                displayPane.setViewportView(plot.createGraphPanel());
                        } else // Raster
                        {
                            Raster raster = new Raster(nf.path.getAbsolutePath(), displayPane.getHeight());
                            displayPane.setViewportView(raster.createGraphPanel());
                        }
                        displayGraph = graphType;
                    }
                }
            }
        }
    };

    buttonGraph = new JButton("Graph", ImageUtil.getImage("analysis.gif"));
    buttonGraph.setFocusable(false);
    buttonGraph.addActionListener(graphListener);
    buttonGraph.setActionCommand("Graph");

    buttonRaster = new JButton("Raster", ImageUtil.getImage("prnplot.gif"));
    buttonRaster.setFocusable(false);
    buttonRaster.addActionListener(graphListener);
    buttonRaster.setActionCommand("Raster");

    Lay.BLtg(this, "C",
            Lay.SPL(Lay.BL("C", treePane = Lay.sp(tree)), Lay.BL("N",
                    Lay.FL(chkFixedWidth, Lay.FL(buttonGraph, buttonRaster), "hgap=50"), "C", displayPane),
                    "divpixel=250"));
    setFocusCycleRoot(true);
}

From source file:it.imtech.metadata.MetaUtility.java

/**
 * Metodo che setta il TreeMap oefos_path con i valori del nodo selezionato
 * e aggiorna il label che descrive il path dei nodi selezionati
 *
 * @param e L'albero sul quale ricercare il path selezionato
 *///from  ww  w. j  ava2  s.com
private void setOEFOS(JTree e, String sequence, String panelname) throws Exception {
    try {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getLastSelectedPathComponent();
        String completePath = "";
        //OefosPaths path = new OefosPaths(panelname, sequence);

        BookImporter.getInstance()
                .createComponentMap(BookImporter.getInstance().metadatapanels.get(panelname).getPanel());
        Component controls = BookImporter.getInstance().getComponentByName("classification_path---" + sequence);

        //Se e' una foglia aggiorna il path nell'interfaccia e oefos_path
        if (node != null) {
            TreePath selpath = new TreePath(node.getPath());
            e.setSelectionPath(selpath);

            Object[] nodes = selpath.getPath();

            TreeMap<Integer, Integer> single_path = new TreeMap<Integer, Integer>();

            for (int i = 1; i < nodes.length; i++) {
                Object nodeInfo = nodes[i];
                DefaultMutableTreeNode nodeC = (DefaultMutableTreeNode) nodeInfo;
                ClassNode c = (ClassNode) nodeC.getUserObject();
                single_path.put(i, Integer.parseInt(c.getKey().toString()));

                completePath += nodes[i].toString();
                completePath += (i != nodes.length - 1) ? "/" : "";
            }

            this.oefos_path.put(panelname + "----" + sequence, single_path);
        } else {
            this.oefos_path.put(panelname + "----" + sequence, null);
        }

        JLabel label = (JLabel) controls;
        if (completePath.length() > 120) {
            label.setText(completePath.substring(0, 120));
        } else {
            label.setText(completePath);
        }

        label.revalidate();
    } catch (Exception ex) {
        throw new Exception("Exception in setOEFOS: " + ex.getStackTrace() + "\n");
    }
}

From source file:com.edduarte.protbox.ui.windows.RestoreFileWindow.java

private RestoreFileWindow(final PReg registry) {
    super();/*from  w w  w .  j  av  a2 s  .  c om*/
    setLayout(null);

    final JTextField searchField = new JTextField();
    searchField.setLayout(null);
    searchField.setBounds(2, 2, 301, 26);
    searchField.setBorder(new LineBorder(Color.lightGray));
    searchField.setFont(Constants.FONT);
    add(searchField);

    final JLabel noBackupFilesLabel = new JLabel("<html>No backups files were found!<br><br>"
            + "<font color=\"gray\">If you think there is a problem with the<br>"
            + "backup system, please create an issue here:<br>"
            + "<a href=\"#\">https://github.com/com.edduarte/protbox/issues</a></font></html>");
    noBackupFilesLabel.setLayout(null);
    noBackupFilesLabel.setBounds(20, 50, 300, 300);
    noBackupFilesLabel.setFont(Constants.FONT.deriveFont(14f));
    noBackupFilesLabel.addMouseListener((OnMouseClick) e -> {
        String urlPath = "https://github.com/com.edduarte/protbox/issues";

        try {

            if (Desktop.isDesktopSupported()) {
                Desktop.getDesktop().browse(new URI(urlPath));

            } else {
                if (SystemUtils.IS_OS_WINDOWS) {
                    Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + urlPath);

                } else {
                    java.util.List<String> browsers = Lists.newArrayList("firefox", "opera", "safari",
                            "mozilla", "chrome");

                    for (String browser : browsers) {
                        if (Runtime.getRuntime().exec(new String[] { "which", browser }).waitFor() == 0) {

                            Runtime.getRuntime().exec(new String[] { browser, urlPath });
                            break;
                        }
                    }
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    });

    DefaultMutableTreeNode rootTreeNode = registry.buildEntryTree();
    final JTree tree = new JTree(rootTreeNode);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    if (rootTreeNode.getChildCount() == 0) {
        searchField.setEnabled(false);
        add(noBackupFilesLabel);
    }
    expandTree(tree);
    tree.setLayout(null);
    tree.setRootVisible(false);
    tree.setEditable(false);
    tree.setCellRenderer(new SearchableTreeCellRenderer(searchField));
    searchField.addKeyListener((OnKeyReleased) e -> {

        // update and expand tree
        DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
        model.nodeStructureChanged((TreeNode) model.getRoot());
        expandTree(tree);
    });
    final JScrollPane scroll = new JScrollPane(tree, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scroll.setBorder(new DropShadowBorder());
    scroll.setBorder(new LineBorder(Color.lightGray));
    scroll.setBounds(2, 30, 334, 360);
    add(scroll);

    JLabel close = new JLabel(new ImageIcon(Constants.getAsset("close.png")));
    close.setLayout(null);
    close.setBounds(312, 7, 18, 18);
    close.setFont(Constants.FONT);
    close.setForeground(Color.gray);
    close.addMouseListener((OnMouseClick) e -> dispose());
    add(close);

    final JLabel permanentDeleteButton = new JLabel(new ImageIcon(Constants.getAsset("permanent.png")));
    permanentDeleteButton.setLayout(null);
    permanentDeleteButton.setBounds(91, 390, 40, 39);
    permanentDeleteButton.setBackground(Color.black);
    permanentDeleteButton.setEnabled(false);
    permanentDeleteButton.addMouseListener((OnMouseClick) e -> {
        if (permanentDeleteButton.isEnabled()) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            PbxEntry entry = (PbxEntry) node.getUserObject();

            if (JOptionPane.showConfirmDialog(null,
                    "Are you sure you wish to permanently delete '" + entry.realName()
                            + "'?\nThis file and its "
                            + "backup copies will be deleted immediately. You cannot undo this action.",
                    "Confirm Cancel", JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) {

                registry.permanentDelete(entry);
                dispose();
                RestoreFileWindow.getInstance(registry);

            } else {
                setVisible(true);
            }
        }
    });
    add(permanentDeleteButton);

    final JLabel configBackupsButton = new JLabel(new ImageIcon(Constants.getAsset("config.png")));
    configBackupsButton.setLayout(null);
    configBackupsButton.setBounds(134, 390, 40, 39);
    configBackupsButton.setBackground(Color.black);
    configBackupsButton.setEnabled(false);
    configBackupsButton.addMouseListener((OnMouseClick) e -> {
        if (configBackupsButton.isEnabled()) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            PbxEntry entry = (PbxEntry) node.getUserObject();
            if (entry instanceof PbxFile) {
                PbxFile pbxFile = (PbxFile) entry;

                JFrame frame = new JFrame("Choose backup policy");
                Object option = JOptionPane.showInputDialog(frame,
                        "Choose below the backup policy for this file:", "Choose backup",
                        JOptionPane.QUESTION_MESSAGE, null, PbxFile.BackupPolicy.values(),
                        pbxFile.getBackupPolicy());

                if (option == null) {
                    setVisible(true);
                    return;
                }
                PbxFile.BackupPolicy pickedPolicy = PbxFile.BackupPolicy.valueOf(option.toString());
                pbxFile.setBackupPolicy(pickedPolicy);
            }
            setVisible(true);
        }
    });
    add(configBackupsButton);

    final JLabel restoreBackupButton = new JLabel(new ImageIcon(Constants.getAsset("restore.png")));
    restoreBackupButton.setLayout(null);
    restoreBackupButton.setBounds(3, 390, 85, 39);
    restoreBackupButton.setBackground(Color.black);
    restoreBackupButton.setEnabled(false);
    restoreBackupButton.addMouseListener((OnMouseClick) e -> {
        if (restoreBackupButton.isEnabled()) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            PbxEntry entry = (PbxEntry) node.getUserObject();
            if (entry instanceof PbxFolder) {
                registry.restoreFolderFromEntry((PbxFolder) entry);

            } else if (entry instanceof PbxFile) {
                PbxFile pbxFile = (PbxFile) entry;
                java.util.List<String> snapshots = pbxFile.snapshotsToString();
                if (snapshots.isEmpty()) {
                    setVisible(true);
                    return;
                }

                JFrame frame = new JFrame("Choose backup");
                Object option = JOptionPane.showInputDialog(frame,
                        "Choose below what backup snapshot would you like restore:", "Choose backup",
                        JOptionPane.QUESTION_MESSAGE, null, snapshots.toArray(), snapshots.get(0));

                if (option == null) {
                    setVisible(true);
                    return;
                }
                int pickedIndex = snapshots.indexOf(option.toString());
                registry.restoreFileFromEntry((PbxFile) entry, pickedIndex);
            }
            dispose();
        }
    });
    add(restoreBackupButton);

    tree.addMouseListener((OnMouseClick) e -> {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        if (node != null) {
            PbxEntry entry = (PbxEntry) node.getUserObject();
            if ((entry instanceof PbxFolder && entry.areNativeFilesDeleted())) {
                permanentDeleteButton.setEnabled(true);
                restoreBackupButton.setEnabled(true);
                configBackupsButton.setEnabled(false);

            } else if (entry instanceof PbxFile) {
                permanentDeleteButton.setEnabled(true);
                restoreBackupButton.setEnabled(true);
                configBackupsButton.setEnabled(true);

            } else {
                permanentDeleteButton.setEnabled(false);
                restoreBackupButton.setEnabled(false);
                configBackupsButton.setEnabled(false);
            }
        }
    });

    final JLabel cancel = new JLabel(new ImageIcon(Constants.getAsset("cancel.png")));
    cancel.setLayout(null);
    cancel.setBounds(229, 390, 122, 39);
    cancel.setBackground(Color.black);
    cancel.addMouseListener((OnMouseClick) e -> dispose());
    add(cancel);

    addWindowFocusListener(new WindowFocusListener() {
        private boolean gained = false;

        @Override
        public void windowGainedFocus(WindowEvent e) {
            gained = true;
        }

        @Override
        public void windowLostFocus(WindowEvent e) {
            if (gained) {
                dispose();
            }
        }
    });

    setSize(340, 432);
    setUndecorated(true);
    getContentPane().setBackground(Color.white);
    setResizable(false);
    getRootPane().setBorder(BorderFactory.createLineBorder(new Color(100, 100, 100)));
    Utils.setComponentLocationOnCenter(this);
    setVisible(true);
}

From source file:GUI.MainWindow.java

public void deleteReferences(JTree tree, JList list) {

    DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
    if (node == null) {
        return;/*w w  w.java2 s  . c  o m*/
    }

    Object obj = node.getUserObject();
    if (!(obj instanceof Vulnerability)) {
        return;
    }

    // Get currently selected vulnerability
    Vulnerability vuln = (Vulnerability) obj;
    DefaultListModel dlm = (DefaultListModel) list.getModel();
    List selected = list.getSelectedValuesList();
    for (Object ref_obj : selected) {
        if (ref_obj instanceof Reference) {
            Reference ref = (Reference) ref_obj;
            vuln.deleteReference(ref);
            dlm.removeElement(ref_obj);
            System.out.println("Deleted Reference: " + ref);
        } else {
            System.out.println("Somehow the references list contained a non-Regerence object");
        }
    }
}

From source file:GUI.MainWindow.java

public void addReference(JTree tree, JList list, Reference current) {
    DefaultMutableTreeNode node = ((DefaultMutableTreeNode) tree.getLastSelectedPathComponent());
    if (node == null) {
        return;//from   w w  w . j  av a 2 s.c o m
    }

    Object obj = node.getUserObject();
    if (!(obj instanceof Vulnerability)) {
        return; // here be monsters, most likely in the merge tree
    }
    Vulnerability vuln = (Vulnerability) obj;
    DefaultListModel dlm = (DefaultListModel) list.getModel();
    // Build Input Field and display it
    JTextField description = new JTextField();
    JTextField url = new JTextField();

    // If current is not null then pre-set the description and risk
    if (current != null) {
        description.setText(current.getDescription());
        url.setText(current.getUrl());
    }

    JLabel error = new JLabel(
            "A valid URL needs to be supplied including the protocol i.e. http://www.github.com");
    error.setForeground(Color.red);
    Object[] message = { "Description:", description, "URL:", url };

    String url_string = null;
    Reference newref = null;
    while (url_string == null) {
        int option = JOptionPane.showConfirmDialog(null, message, "Add Reference",
                JOptionPane.OK_CANCEL_OPTION);
        if (option == JOptionPane.OK_OPTION) {
            System.out.println("User clicked ok, validating data");
            String ref_desc = description.getText();
            String ref_url = url.getText();
            if (!ref_desc.equals("") || !ref_url.equals("")) {
                // Both have values
                // Try to validate URL
                try {

                    URL u = new URL(url.getText());
                    u.toURI();
                    url_string = url.getText(); // Causes loop to end with a valid url

                } catch (MalformedURLException ex) {
                    url_string = null;
                    //ex.printStackTrace();
                } catch (URISyntaxException ex) {
                    url_string = null;
                    //ex.printStackTrace();
                }

            }

        } else if (option == JOptionPane.CANCEL_OPTION || option == JOptionPane.CLOSED_OPTION) {
            System.out.println("User clicked cancel/close");
            return; // ends the loop without making any chages
        }

        if (url_string == null) {
            // We need to show an error saying that the url failed to parse
            Object[] message2 = { error, "Description:", description, "URL:", url };
            message = message2;

        }
    }

    // If you get here there is a valid reference URL and description
    Reference ref = new Reference(description.getText(), url.getText());

    if (current == null) {
        // Add it to the vuln
        vuln.addReference(ref);
        // Add it to the GUI 
        dlm.addElement(ref);
        System.out.println("Valid reference added: " + ref);
    } else {
        // Modify it in the vuln
        vuln.modifyReference(current, ref);
        // Update the GUI
        dlm.removeElement(current);
        dlm.addElement(ref);
        System.out.println("Valid reference modified: " + ref);
    }

}