Example usage for javax.swing JTree addKeyListener

List of usage examples for javax.swing JTree addKeyListener

Introduction

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

Prototype

public synchronized void addKeyListener(KeyListener l) 

Source Link

Document

Adds the specified key listener to receive key events from this component.

Usage

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);//  ww 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:de.codesourcery.jasm16.ide.ui.views.WorkspaceExplorer.java

private JPanel createPanel() {
    treeModel = createTreeModel();// w w w .  j ava 2 s.co m
    tree.setModel(treeModel);
    setColors(tree);
    tree.setRootVisible(false);

    //      for (int i = 0; i < tree.getRowCount(); i++) {
    //         tree.expandRow(i);
    //      }

    tree.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_DELETE) {
                final WorkspaceTreeNode selection = getSelectedNode();
                if (selection != null) {
                    deleteResource(selection);
                }
            } else if (e.getKeyCode() == KeyEvent.VK_F5) {
                refreshWorkspace(null);
            }
        }
    });

    tree.addMouseListener(new MouseAdapter() {

        public void mouseClicked(java.awt.event.MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
                final TreePath path = tree.getPathForLocation(e.getX(), e.getY());
                if (path != null) {
                    final WorkspaceTreeNode selected = (WorkspaceTreeNode) path.getLastPathComponent();
                    final IAssemblyProject project = getProject(selected);
                    try {
                        if (project != null) {
                            onTreeNodeLeftClick(project, selected);
                        } else {
                            System.err.println("Unable to locate project for " + selected);
                        }
                    } catch (IOException e1) {
                        LOG.error("mouseClicked(): Internal error", e1);
                    }
                }
            }
        }
    });

    final TreeSelectionListener selectionListener = new TreeSelectionListener() {

        @Override
        public void valueChanged(TreeSelectionEvent e) {

        }
    };

    tree.getSelectionModel().addTreeSelectionListener(selectionListener);

    tree.setCellRenderer(new DefaultTreeCellRenderer() {

        public Color getTextSelectionColor() {
            return Color.GREEN;
        };

        public java.awt.Color getTextNonSelectionColor() {
            return Color.GREEN;
        };

        public Color getBackgroundSelectionColor() {
            return Color.BLACK;
        };

        public Color getBackgroundNonSelectionColor() {
            return Color.BLACK;
        };

        public java.awt.Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel,
                boolean expanded, boolean leaf, int row, boolean hasFocus) {

            java.awt.Component result = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf,
                    row, hasFocus);

            String label = value.toString();
            Color color = getTextColor();
            if (value instanceof WorkspaceTreeNode) {
                if (value instanceof ProjectNode) {
                    final ProjectNode projectNode = (ProjectNode) value;
                    final IAssemblyProject project = projectNode.getValue();
                    label = project.getName();

                    if (project.isClosed()) {
                        color = Color.LIGHT_GRAY;
                    } else {
                        if (projectNode.hasCompilationErrors()) {
                            color = Color.RED;
                        }
                    }
                } else if (value instanceof FileNode) {
                    FileNode fn = (FileNode) value;
                    label = fn.getValue().getName();
                    switch (fn.type) {
                    case DIRECTORY:
                        if (fn.hasCompilationErrors()) {
                            color = Color.RED;
                        }
                        break;
                    case OBJECT_FILE:
                        label = "[O] " + label;
                        break;
                    case EXECUTABLE:
                        label = "[E] " + label;
                        break;
                    case SOURCE_CODE:
                        label = "[S] " + label;
                        if (fn.hasCompilationErrors()) {
                            color = Color.RED;
                        }
                        break;
                    default:
                        // ok
                    }
                }
            }
            setForeground(color);
            setText(label);
            return result;
        };

    });

    setupPopupMenu();

    final JScrollPane pane = new JScrollPane(tree);
    setColors(pane);

    final JPanel result = new JPanel();
    result.setLayout(new GridBagLayout());
    GridBagConstraints cnstrs = constraints(0, 0, true, true, GridBagConstraints.BOTH);
    setColors(result);
    result.add(pane, cnstrs);
    return result;
}

From source file:org.apache.jmeter.gui.MainFrame.java

/**
 * Create and initialize the GUI representation of the test tree.
 *
 * @param treeModel/*from   w  w w .j a va2 s.  com*/
 *            the test tree model
 * @param treeListener
 *            the test tree listener
 *
 * @return the initialized test tree GUI
 */
private JTree makeTree(TreeModel treeModel, JMeterTreeListener treeListener) {
    JTree treevar = new JTree(treeModel) {
        private static final long serialVersionUID = 240L;

        @Override
        public String getToolTipText(MouseEvent event) {
            TreePath path = this.getPathForLocation(event.getX(), event.getY());
            if (path != null) {
                Object treeNode = path.getLastPathComponent();
                if (treeNode instanceof DefaultMutableTreeNode) {
                    Object testElement = ((DefaultMutableTreeNode) treeNode).getUserObject();
                    if (testElement instanceof TestElement) {
                        String comment = ((TestElement) testElement).getComment();
                        if (comment != null && comment.length() > 0) {
                            return comment;
                        }
                    }
                }
            }
            return null;
        }
    };
    treevar.setToolTipText("");
    treevar.setCellRenderer(getCellRenderer());
    treevar.setRootVisible(false);
    treevar.setShowsRootHandles(true);

    treeListener.setJTree(treevar);
    treevar.addTreeSelectionListener(treeListener);
    treevar.addMouseListener(treeListener);
    treevar.addKeyListener(treeListener);

    // enable drag&drop, install a custom transfer handler
    treevar.setDragEnabled(true);
    treevar.setDropMode(DropMode.ON_OR_INSERT);
    treevar.setTransferHandler(new JMeterTreeTransferHandler());

    addQuickComponentHotkeys(treevar);

    return treevar;
}