List of usage examples for javax.swing JTree setRootVisible
@BeanProperty(description = "Whether or not the root node from the TreeModel is visible.") public void setRootVisible(boolean rootVisible)
TreeModel
is visible. From source file:Main.java
public Main() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); TreeNode root = getNodes();/* w ww . j a v a 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:ec.nbdemetra.ui.demo.ComponentsDemo.java
public ComponentsDemo() { initStaticResources();//from www . j a v a 2 s.co m final Map<Id, Component> demoData = lookupComponents(); final JPanel main = new JPanel(new BorderLayout()); final JTree tree = new JTree(); tree.setRootVisible(false); tree.setCellRenderer(new IdRenderer(demoData)); IdsTree.fill(tree, Lists.newArrayList(demoData.keySet())); expandAll(tree); tree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { TreePath p = tree.getSelectionPath(); if (p != null) { main.removeAll(); DefaultMutableTreeNode node = (DefaultMutableTreeNode) p.getLastPathComponent(); Id id = IdsTree.translate(node); Component c = demoData.get(id); main.add(c != null ? c : new JPanel()); main.validate(); main.repaint(); } } }); JTsList dragDrop = new JTsList(); dragDrop.setShowHeader(false); dragDrop.setInformation(new ITsList.InfoType[] { ITsList.InfoType.TsIdentifier, ITsList.InfoType.Data }); dragDrop.setPreferredSize(new Dimension(200, 200)); dragDrop.setTsAction(DemoTsActions.DO_NOTHING); JSplitPane left = NbComponents.newJSplitPane(JSplitPane.VERTICAL_SPLIT, NbComponents.newJScrollPane(tree), dragDrop); JSplitPane splitPane = NbComponents.newJSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, main); splitPane.getLeftComponent().setPreferredSize(new Dimension(200, 400)); setLayout(new BorderLayout()); add(splitPane, BorderLayout.CENTER); }
From source file:it.unibas.spicygui.controllo.window.operator.ProjectTreeGenerator.java
public void generateTree(JTree jTree) { Scenarios scenarios = (Scenarios) modello.getBean(Costanti.SCENARIOS); DefaultMutableTreeNode nodeRoot = new DefaultMutableTreeNode( new TreeTopComponentAdapter(null, false, true, false)); for (IScenario scenario : scenarios.getListaSceneri()) { analizzaScenario(nodeRoot, (Scenario) scenario); }//from www . ja va2 s . c o m ((DefaultTreeModel) jTree.getModel()).setRoot(nodeRoot); jTree.setRootVisible(false); jTree.setShowsRootHandles(true); TreeRenderer rendererTree = new TreeRenderer(); jTree.setCellRenderer(rendererTree); return; }
From source file:ca.sqlpower.architect.swingui.enterprise.SecurityPanel.java
public SecurityPanel(SPServerInfo serverInfo, Action closeAction, Dialog d, ArchitectSession session) { this.closeAction = closeAction; splitpane = new JSplitPane(); panel = new JPanel(); ArchitectClientSideSession clientSideSession = ArchitectClientSideSession.getSecuritySessions() .get(serverInfo.getServerAddress()); //Displaying an indeterminate progress bar in place of the split pane //until the security session has loaded fully. if (clientSideSession.getUpdater().getRevision() <= 0) { JLabel messageLabel = new JLabel("Opening"); JProgressBar progressBar = new JProgressBar(); progressBar.setIndeterminate(true); DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout("pref:grow, 5dlu, pref")); builder.setDefaultDialogBorder(); builder.append(messageLabel, 3); builder.nextLine();//from www. j a v a 2 s .co m builder.append(progressBar, 3); UpdateListener l = new UpdateListener() { @Override public void workspaceDeleted() { //do nothing } @Override public boolean updatePerformed(AbstractNetworkConflictResolver resolver) { panel.removeAll(); panel.add(splitpane); dialog.pack(); refreshTree(); return true; } @Override public boolean updateException(AbstractNetworkConflictResolver resolver, Throwable t) { //do nothing, the error will be handled elsewhere return true; } @Override public void preUpdatePerformed(AbstractNetworkConflictResolver resolver) { //do nothing } }; clientSideSession.getUpdater().addListener(l); panel.add(builder.getPanel()); } this.securityWorkspace = clientSideSession.getWorkspace(); this.username = serverInfo.getUsername(); this.dialog = d; this.session = session; try { digester = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } rootNode.add(usersNode); rootNode.add(groupsNode); rightSidePanel = new JPanel(); tree = new JTree(rootNode); tree.addTreeSelectionListener(treeListener); tree.setRootVisible(false); tree.setShowsRootHandles(true); tree.setCellRenderer(new DefaultTreeCellRenderer() { 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); Object userObject = ((DefaultMutableTreeNode) value).getUserObject(); if (userObject instanceof User) { setIcon(USER_ICON); } else if (userObject instanceof Group) { setIcon(GROUP_ICON); } return this; } }); treePane = new JScrollPane(tree); treePane.setPreferredSize(new Dimension(200, treePane.getPreferredSize().height)); tree.addMouseListener(popupListener); splitpane.setRightComponent(rightSidePanel); splitpane.setLeftComponent(treePane); if (clientSideSession.getUpdater().getRevision() > 0) { panel.removeAll(); panel.add(splitpane); } refreshTree(); try { tree.setSelectionPath(new TreePath(usersNode.getFirstChild())); } catch (NoSuchElementException e) { } // This just means that the node has no children, so we cannot expand the path. }
From source file:com.edduarte.protbox.ui.windows.RestoreFileWindow.java
private RestoreFileWindow(final PReg registry) { super();/*from ww w. j av a 2 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:gov.sandia.umf.platform.ui.jobs.RunPanel.java
public RunPanel() { root = new NodeBase(); model = new DefaultTreeModel(root); tree = new JTree(model); tree.setRootVisible(false); tree.setShowsRootHandles(true);//from w w w. ja va 2 s .c o m 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
/** * Aggiunge il pannello delle classificazioni all'interfaccia dei metadati * * @param innerPanel Pannello sul quale aggiungere i metadati * @param kv Valori dei metadati//from w w w. j av a 2s. com */ private void addClassification(JPanel innerPanel, Integer kv, final String sequence, final String panelname) throws Exception { try { ResourceBundle bundle = ResourceBundle.getBundle(Globals.RESOURCES, Globals.CURRENT_LOCALE, Globals.loader); DefaultMutableTreeNode hierarchy = new DefaultMutableTreeNode("root"); selected = null; String selectedPath = ""; String link = selectedClassificationList.get(panelname + "---" + sequence); recursiveOefosTreeviewBuild(hierarchy, oefos.get(link), sequence, panelname); DefaultTreeModel model = new DefaultTreeModel(hierarchy); final JTree tree = new JTree(model); tree.setRootVisible(false); if (selected != null) { TreePath selpath = new TreePath(selected.getPath()); tree.setSelectionPath(selpath); Object[] nodes = selpath.getPath(); for (int i = 1; i < nodes.length; i++) { selectedPath += nodes[i].toString(); selectedPath += (i != nodes.length - 1) ? "/" : ""; } } tree.setName("MID_" + Integer.toString(kv) + "---" + sequence); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { try { setOEFOS(tree, sequence, panelname); } catch (Exception ex) { logger.error(ex.getMessage()); } } }); javax.swing.JScrollPane tree_scroller = new javax.swing.JScrollPane(); tree_scroller .setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); tree_scroller.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); tree_scroller.setViewportView(tree); tree_scroller.setBorder(null); innerPanel.add(tree_scroller, "wrap, width 100:800:800"); JPanel iPanel = new JPanel(new MigLayout()); iPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), Utility.getBundleString("choose2", bundle), TitledBorder.LEFT, TitledBorder.TOP)); JLabel label = new JLabel(); label.setName("classification_path" + "---" + sequence); label.setText(selectedPath); iPanel.add(label, "wrap, growx, height 30:30:30"); innerPanel.add(iPanel, "wrap, width 100:800:800"); findLastClassification(panelname); } catch (Exception ex) { logger.error(ex.getMessage()); throw new Exception("Exception in addClassification: " + ex.getStackTrace() + "\n"); } }
From source file:de.codesourcery.jasm16.ide.ui.views.WorkspaceExplorer.java
private JPanel createPanel() { treeModel = createTreeModel();//from w ww .java 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:base.BasePlayer.AddGenome.java
public AddGenome() { super(new BorderLayout()); makeGenomes();/*w ww . j ava2 s. c o m*/ tree = new JTree(root); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); sizeError.setForeground(Draw.redColor); sizeError.setVisible(true); treemodel = (DefaultTreeModel) tree.getModel(); remscroll = new JScrollPane(remtable); tree.setCellRenderer(new DefaultTreeCellRenderer() { private static final long serialVersionUID = 1L; private Icon collapsedIcon = UIManager.getIcon("Tree.collapsedIcon"); private Icon expandedIcon = UIManager.getIcon("Tree.expandedIcon"); // private Icon leafIcon = UIManager.getIcon("Tree.leafIcon"); private Icon addIcon = UIManager.getIcon("Tree.closedIcon"); // private Icon saveIcon = UIManager.getIcon("OptionPane.informationIcon"); @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean isLeaf, int row, boolean focused) { Component c = super.getTreeCellRendererComponent(tree, value, selected, expanded, isLeaf, row, focused); if (!isLeaf) { //setFont(getFont().deriveFont(Font.PLAIN)); if (expanded) { setIcon(expandedIcon); } else { setIcon(collapsedIcon); } /* if(((DefaultMutableTreeNode) value).getUserObject().toString().equals("Annotations")) { this.setFocusable(false); setFont(getFont().deriveFont(Font.BOLD)); setIcon(null); } */ } else { if (((DefaultMutableTreeNode) value).getUserObject().toString().equals("Annotations")) { // setFont(getFont().deriveFont(Font.PLAIN)); setIcon(null); } else if (((DefaultMutableTreeNode) value).getUserObject().toString().startsWith("Add new")) { // setFont(getFont().deriveFont(Font.PLAIN)); setIcon(addIcon); } else { // setFont(getFont().deriveFont(Font.ITALIC)); setIcon(null); // setIcon(leafIcon); } } return c; } }); tree.addMouseListener(this); tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { try { DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (node == null) return; selectedNode = node; if (node.isLeaf()) { checkUpdates.setEnabled(false); } else { checkUpdates.setEnabled(true); } if (node.toString().startsWith("Add new") || node.toString().equals("Annotations")) { remove.setEnabled(false); } else { remove.setEnabled(true); } genometable.clearSelection(); download.setEnabled(false); } catch (Exception ex) { ex.printStackTrace(); } } }); tree.setToggleClickCount(1); tree.setRootVisible(false); treescroll = new JScrollPane(tree); checkGenomes(); genomeFileText = new JLabel("Select reference fasta-file"); annotationFileText = new JLabel("Select annotation gff3-file"); genomeName = new JTextField("Give name of the genome"); openRef = new JButton("Browse"); openAnno = new JButton("Browse"); add = new JButton("Add"); download = new JButton("Download"); checkEnsembl = new JButton("Ensembl fetch"); checkEnsembl.setMinimumSize(Main.buttonDimension); checkEnsembl.addActionListener(this); getLinks = new JButton("Get file links."); remove = new JButton("Remove"); checkUpdates = new JButton("Check updates"); download.setEnabled(false); getLinks.setEnabled(false); getLinks.addActionListener(this); remove.setEnabled(false); download.addActionListener(this); remove.addActionListener(this); panel.setBackground(Draw.sidecolor); checkUpdates.addActionListener(this); this.setBackground(Draw.sidecolor); frame.getContentPane().setBackground(Draw.sidecolor); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.insets = new Insets(2, 4, 2, 4); c.gridwidth = 2; genometable.setSelectionMode(0); genometable.setShowGrid(false); remtable.setSelectionMode(0); remtable.setShowGrid(false); JScrollPane scroll = new JScrollPane(); scroll.getViewport().setBackground(Color.white); scroll.getViewport().add(genometable); remscroll.getViewport().setBackground(Color.white); genometable.addMouseListener(this); remtable.addMouseListener(this); // panel.add(welcomeLabel,c); // c.gridy++; c.anchor = GridBagConstraints.NORTHWEST; panel.add(new JLabel("Download genome reference and annotation"), c); c.gridx++; c.anchor = GridBagConstraints.NORTHEAST; panel.add(checkEnsembl, c); c.anchor = GridBagConstraints.NORTHWEST; c.weightx = 1; c.weighty = 1; c.fill = GridBagConstraints.BOTH; c.gridx = 0; c.gridy++; //c.fill = GridBagConstraints.NONE; panel.add(scroll, c); c.gridy++; c.fill = GridBagConstraints.NONE; panel.add(download, c); c.gridx = 1; panel.add(sizeError, c); c.gridx = 1; panel.add(getLinks, c); c.gridy++; c.gridx = 0; c.fill = GridBagConstraints.BOTH; panel.add(new JLabel("Add/Remove installed genomes manually"), c); c.gridy++; panel.add(treescroll, c); c.gridy++; c.fill = GridBagConstraints.NONE; c.gridwidth = 1; remove.setMinimumSize(Main.buttonDimension); panel.add(remove, c); c.gridx = 1; panel.add(checkUpdates, c); checkUpdates.setMinimumSize(Main.buttonDimension); checkUpdates.setEnabled(false); c.gridwidth = 2; c.gridx = 0; c.gridy++; try { if (Main.genomeDir != null) { genomedirectory.setText(Main.genomeDir.getCanonicalPath()); } genomedirectory.setEditable(false); genomedirectory.setBackground(Color.white); genomedirectory.setForeground(Color.black); } catch (IOException e1) { e1.printStackTrace(); } panel.add(new JLabel("Genome directory:"), c); c.gridy++; panel.add(genomedirectory, c); /* c.fill = GridBagConstraints.BOTH; c.gridy++; panel.add(new JLabel("Add genome manually"),c); c.gridy++; c.gridwidth = 2; panel.add(new JSeparator(),c); c.gridwidth = 1; c.gridy++; panel.add(genomeFileText, c); c.fill = GridBagConstraints.NONE; c.gridx = 1; panel.add(openRef, c); c.gridx = 0; openRef.addActionListener(this); c.gridy++; panel.add(annotationFileText,c); c.gridx=1; panel.add(openAnno, c); c.gridy++; panel.add(add,c); openAnno.addActionListener(this); add.addActionListener(this); add.setEnabled(false); */ add(panel, BorderLayout.NORTH); if (Main.drawCanvas != null) { setFonts(Main.menuFont); } /* html.append("<a href=http:Homo_sapiens_GRCh37:Ensembl_genes> Homo sapiens GRCh37 with Ensembl</a> or <a href=http:Homo_sapiens_GRCh37:RefSeq_genes>RefSeq</a> gene annotations<br>"); html.append("<a href=http:Homo_sapiens_GRCh38:Ensembl_genes> Homo sapiens GRCh38 with Ensembl</a> or <a href=http:Homo_sapiens_GRCh38:RefSeq_genes>RefSeq</a> gene annotations<br><br>"); html.append("<a href=http:Mus_musculus_GRCm38:Ensembl_genes> Mus musculus GRCm38 with Ensembl</a> or <a href=http:Mus_musculus_GRCm38:RefSeq_genes>RefSeq</a> gene annotations<br>"); html.append("<a href=http:Rattus_norvegicus:Ensembl_genes> Rattus norvegicus with Ensembl gene annotations</a><br>"); html.append("<a href=http:Saccharomyces_cerevisiae:Ensembl_genes> Saccharomyces cerevisiae with Ensembl gene annotation</a><br>"); html.append("<a href=http:Ciona_intestinalis:Ensembl_genes> Ciona intestinalis with Ensembl gene annotation</a><br>"); Object[] row = {"Homo_sapiens_GRCh37"}; Object[] row = {"Homo_sapiens_GRCh38"}; model.addRow(row); /* genomeName.setPreferredSize(new Dimension(300,20)); this.add(genomeName); this.add(new JSeparator()); this.add(openRef); openRef.addActionListener(this); this.add(genomeFileText); this.add(openAnno); openAnno.addActionListener(this); this.add(annotationFileText); this.add(add); add.addActionListener(this); if(annotation) { openRef.setVisible(false); genomeFileText.setVisible(false); genomeName.setEditable(false); } genomeFileText.setEditable(false); annotationFileText.setEditable(false);*/ }
From source file:org.apache.jmeter.gui.MainFrame.java
/** * Create and initialize the GUI representation of the test tree. * * @param treeModel/* w w w . jav a2 s . c o m*/ * 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; }