List of usage examples for javax.swing.tree TreePath getLastPathComponent
public Object getLastPathComponent()
From source file:com.mirth.connect.client.ui.DashboardPanel.java
public synchronized void updateTableHighlighting() { // MIRTH-2301 // Since we are using addHighlighter here instead of using setHighlighters, we need to remove the old ones first. dashboardTable.setHighlighters();/* www . j a va 2s . co m*/ // Add the highlighters. Always add the error highlighter. if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) { Highlighter highlighter = HighlighterFactory.createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR, UIConstants.BACKGROUND_COLOR); dashboardTable.addHighlighter(highlighter); } HighlightPredicate queuedHighlighterPredicate = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { if (adapter.column == dashboardTable.getColumnViewIndex(QUEUED_COLUMN_NAME)) { Long value = (Long) dashboardTable.getValueAt(adapter.row, adapter.column); if (value != null && value.longValue() > 0) { return true; } } return false; } }; dashboardTable.addHighlighter(new ColorHighlighter(queuedHighlighterPredicate, new Color(240, 230, 140), Color.BLACK, new Color(240, 230, 140), Color.BLACK)); HighlightPredicate errorHighlighterPredicate = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { if (adapter.column == dashboardTable.getColumnViewIndex(ERROR_COLUMN_NAME)) { Long value = (Long) dashboardTable.getValueAt(adapter.row, adapter.column); if (value != null && value.longValue() > 0) { return true; } } return false; } }; Highlighter errorHighlighter = new ColorHighlighter(errorHighlighterPredicate, Color.PINK, Color.BLACK, Color.PINK, Color.BLACK); dashboardTable.addHighlighter(errorHighlighter); HighlightPredicate revisionDeltaHighlighterPredicate = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { if (adapter.column == dashboardTable.getColumnViewIndex(DEPLOYED_REVISION_DELTA_COLUMN_NAME)) { Integer value = (Integer) dashboardTable.getValueAt(adapter.row, adapter.column); if (value != null && value.intValue() > 0) { return true; } TreePath path = dashboardTable.getPathForRow(adapter.row); if (path != null) { AbstractDashboardTableNode dashboardTableNode = (AbstractDashboardTableNode) path .getLastPathComponent(); if (!dashboardTableNode.isGroupNode()) { DashboardStatus status = dashboardTableNode.getDashboardStatus(); if (status.getCodeTemplatesChanged() != null && status.getCodeTemplatesChanged()) { return true; } } } } return false; } }; dashboardTable.addHighlighter(new ColorHighlighter(revisionDeltaHighlighterPredicate, new Color(255, 204, 0), Color.BLACK, new Color(255, 204, 0), Color.BLACK)); HighlightPredicate lastDeployedHighlighterPredicate = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { if (adapter.column == dashboardTable.getColumnViewIndex(LAST_DEPLOYED_COLUMN_NAME)) { Calendar checkAfter = Calendar.getInstance(); checkAfter.add(Calendar.MINUTE, -2); Object value = dashboardTable.getValueAt(adapter.row, adapter.column); if (value != null && value instanceof Calendar && ((Calendar) value).after(checkAfter)) { return true; } } return false; } }; dashboardTable.addHighlighter(new ColorHighlighter(lastDeployedHighlighterPredicate, new Color(240, 230, 140), Color.BLACK, new Color(240, 230, 140), Color.BLACK)); }
From source file:com.mirth.connect.client.ui.DashboardPanel.java
/** * Makes the status table with all current server information. *//* w ww. j av a2 s . c o m*/ public void makeStatusTable() { List<String> columns = new ArrayList<String>(); for (DashboardColumnPlugin plugin : LoadedExtensions.getInstance().getDashboardColumnPlugins().values()) { if (plugin.isDisplayFirst()) { columns.add(plugin.getColumnHeader()); } } columns.addAll(Arrays.asList(defaultColumns)); for (DashboardColumnPlugin plugin : LoadedExtensions.getInstance().getDashboardColumnPlugins().values()) { if (!plugin.isDisplayFirst()) { columns.add(plugin.getColumnHeader()); } } DashboardTreeTableModel model = new DashboardTreeTableModel(); model.setColumnIdentifiers(columns); model.setNodeFactory(new DefaultDashboardTableNodeFactory()); for (DashboardTablePlugin plugin : LoadedExtensions.getInstance().getDashboardTablePlugins().values()) { dashboardTable = plugin.getTable(); if (dashboardTable != null) { break; } } defaultVisibleColumns.addAll(columns); if (dashboardTable == null) { dashboardTable = new MirthTreeTable("dashboardPanel", defaultVisibleColumns); } dashboardTable.setColumnFactory(new DashboardTableColumnFactory()); dashboardTable.setTreeTableModel(model); dashboardTable.setDoubleBuffered(true); dashboardTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); dashboardTable.setHorizontalScrollEnabled(true); dashboardTable.packTable(UIConstants.COL_MARGIN); dashboardTable.setRowHeight(UIConstants.ROW_HEIGHT); dashboardTable.setOpaque(true); dashboardTable.setRowSelectionAllowed(true); dashboardTable.setSortable(true); dashboardTable.putClientProperty("JTree.lineStyle", "Horizontal"); dashboardTable.setAutoCreateColumnsFromModel(false); dashboardTable.setShowGrid(true, true); dashboardTable.restoreColumnPreferences(); dashboardTable.setMirthColumnControlEnabled(true); dashboardTable.setTreeCellRenderer(new DefaultTreeCellRenderer() { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { JLabel label = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); TreePath path = dashboardTable.getPathForRow(row); if (path != null) { AbstractDashboardTableNode node = ((AbstractDashboardTableNode) path.getLastPathComponent()); if (node.isGroupNode()) { setIcon(UIConstants.ICON_GROUP); } else { DashboardStatus status = node.getDashboardStatus(); if (status.getStatusType() == StatusType.CHANNEL) { setIcon(UIConstants.ICON_CHANNEL); } else { setIcon(UIConstants.ICON_CONNECTOR); } } } return label; } }); dashboardTable.setLeafIcon(UIConstants.ICON_CONNECTOR); dashboardTable.setOpenIcon(UIConstants.ICON_CHANNEL); dashboardTable.setClosedIcon(UIConstants.ICON_CHANNEL); dashboardTableScrollPane.setViewportView(dashboardTable); dashboardTable.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent event) { checkSelectionAndPopupMenu(event); } @Override public void mouseReleased(MouseEvent event) { checkSelectionAndPopupMenu(event); } @Override public void mouseClicked(MouseEvent event) { int clickedRow = dashboardTable.rowAtPoint(new Point(event.getX(), event.getY())); if (clickedRow == -1) { return; } TreePath path = dashboardTable.getPathForRow(clickedRow); if (path != null && ((AbstractDashboardTableNode) path.getLastPathComponent()).isGroupNode()) { return; } if (event.getClickCount() >= 2 && dashboardTable.getSelectedRowCount() == 1 && dashboardTable.getSelectedRow() == clickedRow) { parent.doShowMessages(); } } }); dashboardTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent event) { /* * MIRTH-3199: Only update the panel plugin if the selection is finished. This does * mean that the logs aren't updated live when adding to or removing from a * currently adjusting selection, but it's much more efficient when it comes to the * number of requests being done from the client. Plus, it actually will still * update while a selection is adjusting if the refresh interval on the dashboard * elapses. We can change this so that plugins are updated during a selection * adjustment, but it would first require a major rewrite of the connection log / * status column plugin. */ updatePopupMenu(!event.getValueIsAdjusting()); } }); }
From source file:com.emental.mindraider.ui.outline.OutlineJPanel.java
/** * Set selected tree node.// w w w . jav a 2 s. co m * * @param conceptUri */ public void setSelectedTreeNodeConcept(String conceptUri) { logger.debug("=-> setSelectedTreeNodeConcept"); // try to load concept with this URI if (conceptUri != null && MindRaiderVocabulary.isConceptUri(conceptUri) && MindRaider.profile.getActiveOutlineUri() != null && !conceptUri.equals( NoteCustodian.getTrashConceptUri(MindRaider.profile.getActiveOutlineUri().toString()))) { try { // select particular concept in the table - find it yourself int rows = treeTable.tree.getRowCount(); TreePath treePath; OutlineNode node; for (int i = 0; i < rows; i++) { if (i > 0) { treePath = treeTable.tree.getPathForRow(i); // logger.debug("Tree path: "+treePath); node = (OutlineNode) treePath.getLastPathComponent(); if (conceptUri.equals(node.getUri())) { // logger.debug("Bingo: "+conceptUri); treeTable.tree.makeVisible(treePath); treeTable.tree.getSelectionModel().setSelectionPath(treePath); break; } } } } catch (Exception e) { logger.debug("Unable to load Concept for selected graph node: " + conceptUri, e); } } }
From source file:de.codesourcery.jasm16.ide.ui.views.WorkspaceExplorer.java
private JPanel createPanel() { treeModel = createTreeModel();//from w w w . j a v a2s . 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:gdt.jgui.entity.index.JIndexPanel.java
/** * Get the context menu./*from w ww.ja v a2 s . co m*/ * @return the context menu. */ @Override public JMenu getContextMenu() { menu = new JMenu("Context"); menu.addMenuListener(new MenuListener() { @Override public void menuSelected(MenuEvent e) { //System.out.println("IndexPanel:getConextMenu:menu selected"); menu.removeAll(); JMenuItem expandItem = new JMenuItem("Expand"); expandItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { expandAll(tree, new TreePath(rootNode), true); } }); menu.add(expandItem); JMenuItem collapseItem = new JMenuItem("Collapse"); collapseItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { expandAll(tree, new TreePath(rootNode), false); } }); menu.add(collapseItem); final TreePath[] tpa = tree.getSelectionPaths(); if (tpa != null && tpa.length > 0) { menu.addSeparator(); JMenuItem copyItem = new JMenuItem("Copy"); copyItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cut = false; console.clipboard.clear(); DefaultMutableTreeNode node; String locator$; for (TreePath tp : tpa) { node = (DefaultMutableTreeNode) tp.getLastPathComponent(); locator$ = (String) node.getUserObject(); if (locator$ != null) console.clipboard.putString(locator$); } } }); menu.add(copyItem); JMenuItem cutItem = new JMenuItem("Cut"); cutItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cut = true; console.clipboard.clear(); DefaultMutableTreeNode node; String locator$; for (TreePath tp : tpa) { node = (DefaultMutableTreeNode) tp.getLastPathComponent(); locator$ = (String) node.getUserObject(); if (locator$ != null) console.clipboard.putString(locator$); } } }); menu.add(cutItem); JMenuItem deleteItem = new JMenuItem("Delete"); deleteItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int response = JOptionPane.showConfirmDialog(console.getContentPanel(), "Delete ?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (response == JOptionPane.YES_OPTION) { try { DefaultMutableTreeNode node; String locator$; String nodeKey$; for (TreePath tp : tpa) { node = (DefaultMutableTreeNode) tp.getLastPathComponent(); locator$ = (String) node.getUserObject(); nodeKey$ = Locator.getProperty(locator$, NODE_KEY); index.removeElementItem("index.title", nodeKey$); index.removeElementItem("index.jlocator", nodeKey$); } Entigrator entigrator = console.getEntigrator(entihome$); entigrator.save(index); JConsoleHandler.execute(console, getLocator()); } catch (Exception ee) { LOGGER.info(ee.toString()); } } } }); menu.add(deleteItem); } } @Override public void menuDeselected(MenuEvent e) { } @Override public void menuCanceled(MenuEvent e) { } }); return menu; }
From source file:com.nbt.TreeFrame.java
private void createActions() { newAction = new NBTAction("New", "New", "New", KeyEvent.VK_N) { {/* w w w . j a v a 2 s .c o m*/ putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('N', Event.CTRL_MASK)); } @Override public void actionPerformed(ActionEvent e) { updateTreeTable(new CompoundTag("")); } }; browseAction = new NBTAction("Browse...", "Open", "Browse...", KeyEvent.VK_O) { { putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('O', Event.CTRL_MASK)); } @Override public void actionPerformed(ActionEvent e) { JFileChooser fc = createFileChooser(); switch (fc.showOpenDialog(TreeFrame.this)) { case JFileChooser.APPROVE_OPTION: File file = fc.getSelectedFile(); Preferences prefs = getPreferences(); prefs.put(KEY_FILE, file.getAbsolutePath()); doImport(file); break; } } }; saveAction = new NBTAction("Save", "Save", "Save", KeyEvent.VK_S) { { putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('S', Event.CTRL_MASK)); } @Override public void actionPerformed(ActionEvent e) { String path = textFile.getText(); File file = new File(path); if (file.canWrite()) { doExport(file); } else { saveAsAction.actionPerformed(e); } } }; saveAsAction = new NBTAction("Save As...", "SaveAs", "Save As...", KeyEvent.VK_UNDEFINED) { public void actionPerformed(ActionEvent e) { JFileChooser fc = createFileChooser(); switch (fc.showSaveDialog(TreeFrame.this)) { case JFileChooser.APPROVE_OPTION: File file = fc.getSelectedFile(); Preferences prefs = getPreferences(); prefs.put(KEY_FILE, file.getAbsolutePath()); doExport(file); break; } } }; refreshAction = new NBTAction("Refresh", "Refresh", "Refresh", KeyEvent.VK_F5) { { putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("F5")); } public void actionPerformed(ActionEvent e) { String path = textFile.getText(); File file = new File(path); if (file.canRead()) doImport(file); else showErrorDialog("The file could not be read."); } }; exitAction = new NBTAction("Exit", "Exit", KeyEvent.VK_ESCAPE) { @Override public void actionPerformed(ActionEvent e) { // TODO: this should check to see if any changes have been made // before exiting System.exit(0); } }; cutAction = new DefaultEditorKit.CutAction() { { String name = "Cut"; putValue(NAME, name); putValue(SHORT_DESCRIPTION, name); putValue(MNEMONIC_KEY, KeyEvent.VK_X); putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('X', Event.CTRL_MASK)); ImageFactory factory = new ImageFactory(); try { putValue(SMALL_ICON, new ImageIcon(factory.readGeneralImage(name, NBTAction.smallIconSize))); } catch (IOException e) { e.printStackTrace(); } try { putValue(LARGE_ICON_KEY, new ImageIcon(factory.readGeneralImage(name, NBTAction.largeIconSize))); } catch (IOException e) { e.printStackTrace(); } } }; copyAction = new DefaultEditorKit.CopyAction() { { String name = "Copy"; putValue(NAME, name); putValue(SHORT_DESCRIPTION, name); putValue(MNEMONIC_KEY, KeyEvent.VK_C); putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('C', Event.CTRL_MASK)); ImageFactory factory = new ImageFactory(); try { putValue(SMALL_ICON, new ImageIcon(factory.readGeneralImage(name, NBTAction.smallIconSize))); } catch (IOException e) { e.printStackTrace(); } try { putValue(LARGE_ICON_KEY, new ImageIcon(factory.readGeneralImage(name, NBTAction.largeIconSize))); } catch (IOException e) { e.printStackTrace(); } } }; pasteAction = new DefaultEditorKit.CutAction() { { String name = "Paste"; putValue(NAME, name); putValue(SHORT_DESCRIPTION, name); putValue(MNEMONIC_KEY, KeyEvent.VK_V); putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('V', Event.CTRL_MASK)); ImageFactory factory = new ImageFactory(); try { putValue(SMALL_ICON, new ImageIcon(factory.readGeneralImage(name, NBTAction.smallIconSize))); } catch (IOException e) { e.printStackTrace(); } try { putValue(LARGE_ICON_KEY, new ImageIcon(factory.readGeneralImage(name, NBTAction.largeIconSize))); } catch (IOException e) { e.printStackTrace(); } } }; deleteAction = new NBTAction("Delete", "Delete", "Delete", KeyEvent.VK_DELETE) { { putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("DELETE")); } public void actionPerformed(ActionEvent e) { int row = treeTable.getSelectedRow(); TreePath path = treeTable.getPathForRow(row); Object last = path.getLastPathComponent(); if (last instanceof NBTFileBranch) { NBTFileBranch branch = (NBTFileBranch) last; File file = branch.getFile(); String name = file.getName(); String message = "Are you sure you want to delete " + name + "?"; String title = "Continue?"; int option = JOptionPane.showConfirmDialog(TreeFrame.this, message, title, JOptionPane.OK_CANCEL_OPTION); switch (option) { case JOptionPane.CANCEL_OPTION: return; } if (!FileUtils.deleteQuietly(file)) { showErrorDialog(name + " could not be deleted."); return; } } TreePath parentPath = path.getParentPath(); Object parentLast = parentPath.getLastPathComponent(); NBTTreeTableModel model = treeTable.getTreeTableModel(); int index = model.getIndexOfChild(parentLast, last); if (parentLast instanceof Mutable<?>) { Mutable<?> mutable = (Mutable<?>) parentLast; if (last instanceof ByteWrapper) { ByteWrapper wrapper = (ByteWrapper) last; index = wrapper.getIndex(); } mutable.remove(index); } else { System.err.println(last.getClass()); return; } updateTreeTable(); treeTable.expandPath(parentPath); scrollTo(parentLast); treeTable.setRowSelectionInterval(row, row); } }; openAction = new NBTAction("Open...", "Open...", KeyEvent.VK_T) { { putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('T', Event.CTRL_MASK)); final int diamondPickaxe = 278; SpriteRecord record = NBTTreeTable.register.getRecord(diamondPickaxe); BufferedImage image = record.getImage(); setSmallIcon(image); int width = 24, height = 24; Dimension size = new Dimension(width, height); Map<RenderingHints.Key, ?> hints = Thumbnail.createRenderingHints(Thumbnail.QUALITY); BufferedImage largeImage = Thumbnail.createThumbnail(image, size, hints); setLargeIcon(largeImage); } public void actionPerformed(ActionEvent e) { TreePath path = treeTable.getPath(); if (path == null) return; Object last = path.getLastPathComponent(); if (last instanceof Region) { Region region = (Region) last; createAndShowTileCanvas(new TileCanvas.TileWorld(region)); return; } else if (last instanceof World) { World world = (World) last; createAndShowTileCanvas(world); return; } if (last instanceof NBTFileBranch) { NBTFileBranch fileBranch = (NBTFileBranch) last; File file = fileBranch.getFile(); try { open(file); } catch (IOException ex) { ex.printStackTrace(); showErrorDialog(ex.getMessage()); } } } private void open(File file) throws IOException { if (Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); if (desktop.isSupported(Desktop.Action.OPEN)) { desktop.open(file); } } } }; addByteAction = new NBTAction("Add Byte", NBTConstants.TYPE_BYTE, "Add Byte", KeyEvent.VK_1) { { putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('1', Event.CTRL_MASK)); } public void actionPerformed(ActionEvent e) { addTag(new ByteTag("new byte", (byte) 0)); } }; addShortAction = new NBTAction("Add Short", NBTConstants.TYPE_SHORT, "Add Short", KeyEvent.VK_2) { { putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('2', Event.CTRL_MASK)); } public void actionPerformed(ActionEvent e) { addTag(new ShortTag("new short", (short) 0)); } }; addIntAction = new NBTAction("Add Integer", NBTConstants.TYPE_INT, "Add Integer", KeyEvent.VK_3) { { putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('3', Event.CTRL_MASK)); } public void actionPerformed(ActionEvent e) { addTag(new IntTag("new int", 0)); } }; addLongAction = new NBTAction("Add Long", NBTConstants.TYPE_LONG, "Add Long", KeyEvent.VK_4) { { putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('4', Event.CTRL_MASK)); } public void actionPerformed(ActionEvent e) { addTag(new LongTag("new long", 0)); } }; addFloatAction = new NBTAction("Add Float", NBTConstants.TYPE_FLOAT, "Add Float", KeyEvent.VK_5) { { putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('5', Event.CTRL_MASK)); } public void actionPerformed(ActionEvent e) { addTag(new FloatTag("new float", 0)); } }; addDoubleAction = new NBTAction("Add Double", NBTConstants.TYPE_DOUBLE, "Add Double", KeyEvent.VK_6) { { putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('6', Event.CTRL_MASK)); } public void actionPerformed(ActionEvent e) { addTag(new DoubleTag("new double", 0)); } }; addByteArrayAction = new NBTAction("Add Byte Array", NBTConstants.TYPE_BYTE_ARRAY, "Add Byte Array", KeyEvent.VK_7) { { putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('7', Event.CTRL_MASK)); } public void actionPerformed(ActionEvent e) { addTag(new ByteArrayTag("new byte array")); } }; addStringAction = new NBTAction("Add String", NBTConstants.TYPE_STRING, "Add String", KeyEvent.VK_8) { { putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('8', Event.CTRL_MASK)); } public void actionPerformed(ActionEvent e) { addTag(new StringTag("new string", "...")); } }; addListAction = new NBTAction("Add List Tag", NBTConstants.TYPE_LIST, "Add List Tag", KeyEvent.VK_9) { { putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('9', Event.CTRL_MASK)); } public void actionPerformed(ActionEvent e) { Class<? extends Tag> type = queryType(); if (type != null) addTag(new ListTag("new list", null, type)); } private Class<? extends Tag> queryType() { Object[] items = { NBTConstants.TYPE_BYTE, NBTConstants.TYPE_SHORT, NBTConstants.TYPE_INT, NBTConstants.TYPE_LONG, NBTConstants.TYPE_FLOAT, NBTConstants.TYPE_DOUBLE, NBTConstants.TYPE_BYTE_ARRAY, NBTConstants.TYPE_STRING, NBTConstants.TYPE_LIST, NBTConstants.TYPE_COMPOUND }; JComboBox comboBox = new JComboBox(new DefaultComboBoxModel(items)); comboBox.setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value instanceof Integer) { Integer i = (Integer) value; Class<? extends Tag> c = NBTUtils.getTypeClass(i); String name = NBTUtils.getTypeName(c); setText(name); } return this; } }); Object[] message = { new JLabel("Please select a type."), comboBox }; String title = "Title goes here"; int result = JOptionPane.showOptionDialog(TreeFrame.this, message, title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); switch (result) { case JOptionPane.OK_OPTION: ComboBoxModel model = comboBox.getModel(); Object item = model.getSelectedItem(); if (item instanceof Integer) { Integer i = (Integer) item; return NBTUtils.getTypeClass(i); } } return null; } }; addCompoundAction = new NBTAction("Add Compound Tag", NBTConstants.TYPE_COMPOUND, "Add Compound Tag", KeyEvent.VK_0) { { putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('0', Event.CTRL_MASK)); } public void actionPerformed(ActionEvent e) { addTag(new CompoundTag()); } }; String name = "About " + TITLE; helpAction = new NBTAction(name, "Help", name, KeyEvent.VK_F1) { { putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("F1")); } public void actionPerformed(ActionEvent e) { Object[] message = { new JLabel(TITLE + " " + VERSION), new JLabel("\u00A9 Copyright Taggart Spilman 2011. All rights reserved."), new Hyperlink("<html><a href=\"#\">NamedBinaryTag.com</a></html>", "http://www.namedbinarytag.com"), new Hyperlink("<html><a href=\"#\">Contact</a></html>", "mailto:tagadvance@gmail.com"), new JLabel(" "), new Hyperlink("<html><a href=\"#\">JNBT was written by Graham Edgecombe</a></html>", "http://jnbt.sf.net"), new Hyperlink("<html><a href=\"#\">Available open-source under the BSD license</a></html>", "http://jnbt.sourceforge.net/LICENSE.TXT"), new JLabel(" "), new JLabel("This product includes software developed by"), new Hyperlink("<html><a href=\"#\">The Apache Software Foundation</a>.</html>", "http://www.apache.org"), new JLabel(" "), new JLabel("Default texture pack:"), new Hyperlink("<html><a href=\"#\">SOLID COLOUR. SOLID STYLE.</a></html>", "http://www.minecraftforum.net/topic/72253-solid-colour-solid-style/"), new JLabel("Bundled with the permission of Trigger_Proximity."), }; String title = "About"; JOptionPane.showMessageDialog(TreeFrame.this, message, title, JOptionPane.INFORMATION_MESSAGE); } }; }
From source file:net.sf.jabref.groups.GroupSelector.java
private void definePopup() { // These key bindings are just to have the shortcuts displayed // in the popup menu. The actual keystroke processing is in // BasePanel (entryTable.addKeyListener(...)). groupsContextMenu.add(editGroupPopupAction); groupsContextMenu.add(addGroupPopupAction); groupsContextMenu.add(addSubgroupPopupAction); groupsContextMenu.addSeparator();//from www . j av a2 s . c o m groupsContextMenu.add(removeGroupAndSubgroupsPopupAction); groupsContextMenu.add(removeGroupKeepSubgroupsPopupAction); groupsContextMenu.add(removeSubgroupsPopupAction); groupsContextMenu.addSeparator(); groupsContextMenu.add(expandSubtreePopupAction); groupsContextMenu.add(collapseSubtreePopupAction); groupsContextMenu.addSeparator(); groupsContextMenu.add(moveSubmenu); sortSubmenu.add(sortDirectSubgroupsPopupAction); sortSubmenu.add(sortAllSubgroupsPopupAction); groupsContextMenu.add(sortSubmenu); moveSubmenu.add(moveNodeUpPopupAction); moveSubmenu.add(moveNodeDownPopupAction); moveSubmenu.add(moveNodeLeftPopupAction); moveSubmenu.add(moveNodeRightPopupAction); groupsContextMenu.addSeparator(); groupsContextMenu.add(addToGroup); groupsContextMenu.add(moveToGroup); groupsContextMenu.add(removeFromGroup); groupsTree.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { showPopup(e); } } @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { showPopup(e); } } @Override public void mouseClicked(MouseEvent e) { TreePath path = groupsTree.getPathForLocation(e.getPoint().x, e.getPoint().y); if (path == null) { return; } GroupTreeNode node = (GroupTreeNode) path.getLastPathComponent(); // the root node is "AllEntries" and cannot be edited if (node.isRoot()) { return; } if ((e.getClickCount() == 2) && (e.getButton() == MouseEvent.BUTTON1)) { // edit editGroupAction.actionPerformed(null); // dummy event } else if ((e.getClickCount() == 1) && (e.getButton() == MouseEvent.BUTTON1)) { annotationEvent(node); } } }); // be sure to remove a possible border highlight when the popup menu // disappears groupsContextMenu.addPopupMenuListener(new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { // nothing to do } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { groupsTree.setHighlightBorderCell(null); } @Override public void popupMenuCanceled(PopupMenuEvent e) { groupsTree.setHighlightBorderCell(null); } }); }
From source file:LocationSensitiveDemo.java
public LocationSensitiveDemo() { super("Location Sensitive Drag and Drop Demo"); treeModel = getDefaultTreeModel();/* w ww . j ava2 s. c om*/ tree = new JTree(treeModel); tree.setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4)); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); tree.setDropMode(DropMode.ON); namesPath = tree.getPathForRow(2); tree.expandRow(2); tree.expandRow(1); tree.setRowHeight(0); tree.setTransferHandler(new TransferHandler() { public boolean canImport(TransferHandler.TransferSupport info) { // for the demo, we'll only support drops (not clipboard paste) if (!info.isDrop()) { return false; } String item = (String) indicateCombo.getSelectedItem(); if (item.equals("Always")) { info.setShowDropLocation(true); } else if (item.equals("Never")) { info.setShowDropLocation(false); } // we only import Strings if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) { return false; } // fetch the drop location JTree.DropLocation dl = (JTree.DropLocation) info.getDropLocation(); TreePath path = dl.getPath(); // we don't support invalid paths or descendants of the names folder if (path == null || namesPath.isDescendant(path)) { return false; } return true; } public boolean importData(TransferHandler.TransferSupport info) { // if we can't handle the import, say so if (!canImport(info)) { return false; } // fetch the drop location JTree.DropLocation dl = (JTree.DropLocation) info.getDropLocation(); // fetch the path and child index from the drop location TreePath path = dl.getPath(); int childIndex = dl.getChildIndex(); // fetch the data and bail if this fails String data; try { data = (String) info.getTransferable().getTransferData(DataFlavor.stringFlavor); } catch (UnsupportedFlavorException e) { return false; } catch (IOException e) { return false; } // if child index is -1, the drop was on top of the path, so we'll // treat it as inserting at the end of that path's list of children if (childIndex == -1) { childIndex = tree.getModel().getChildCount(path.getLastPathComponent()); } // create a new node to represent the data and insert it into the model DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(data); DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) path.getLastPathComponent(); treeModel.insertNodeInto(newNode, parentNode, childIndex); // make the new node visible and scroll so that it's visible tree.makeVisible(path.pathByAddingChild(newNode)); tree.scrollRectToVisible(tree.getPathBounds(path.pathByAddingChild(newNode))); // demo stuff - remove for blog model.removeAllElements(); model.insertElementAt("String " + (++count), 0); // end demo stuff return true; } }); JList dragFrom = new JList(model); dragFrom.setFocusable(false); dragFrom.setPrototypeCellValue("String 0123456789"); model.insertElementAt("String " + count, 0); dragFrom.setDragEnabled(true); dragFrom.setBorder(BorderFactory.createLoweredBevelBorder()); JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS)); JPanel wrap = new JPanel(); wrap.add(new JLabel("Drag from here:")); wrap.add(dragFrom); p.add(Box.createHorizontalStrut(4)); p.add(Box.createGlue()); p.add(wrap); p.add(Box.createGlue()); p.add(Box.createHorizontalStrut(4)); getContentPane().add(p, BorderLayout.NORTH); getContentPane().add(new JScrollPane(tree), BorderLayout.CENTER); indicateCombo = new JComboBox(new String[] { "Default", "Always", "Never" }); indicateCombo.setSelectedItem("INSERT"); p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS)); wrap = new JPanel(); wrap.add(new JLabel("Show drop location:")); wrap.add(indicateCombo); p.add(Box.createHorizontalStrut(4)); p.add(Box.createGlue()); p.add(wrap); p.add(Box.createGlue()); p.add(Box.createHorizontalStrut(4)); getContentPane().add(p, BorderLayout.SOUTH); getContentPane().setPreferredSize(new Dimension(400, 450)); }
From source file:edu.ku.brc.af.tasks.subpane.formeditor.ViewSetSelectorPanel.java
/** * /* www. j a v a 2 s. c om*/ */ protected void treeSelected() { TreePath treePath = tree.getSelectionModel().getSelectionPath(); if (treePath == null) { selectedRow = null; selectedCell = null; return; } DefaultMutableTreeNode node = (DefaultMutableTreeNode) treePath.getLastPathComponent(); Object nodeObj = node.getUserObject(); if (nodeObj instanceof FormRow) { if (nodeObj == selectedRow) { return; } selectedRow = (FormRow) nodeObj; selectedCell = null; } else if (nodeObj instanceof FormCell) { if (nodeObj == selectedCell) { return; } selectedCell = (FormCell) nodeObj; DefaultMutableTreeNode rowNode = (DefaultMutableTreeNode) node.getParent(); selectedRow = (FormRow) rowNode.getUserObject(); } else { selectedRow = null; selectedCell = null; } if (treePath != null) { updateUIControls(); if (treePath.getPathCount() == 1) { panel.loadView("ViewDefProps", null); //$NON-NLS-1$ panel.setData(selectedViewDef); return; } if (selectedCell != null) { int col = 0; for (FormCellIFace fc : selectedRow.getCells()) { if (fc == nodeObj) { break; } col++; } showPropertiesPanel((FormCell) nodeObj, formViewDef.getClassName(), (formViewDef.getRows().size() * 2) - 1, formViewDef.getRowDefItem().getNumItems(), selectedRow.getRowNumber(), (selectedRow.getCells().size() * 2) - 1, formViewDef.getColumnDefItem().getNumItems(), col); } } }
From source file:com.t3.client.ui.T3Frame.java
private JComponent createTokenTreePanel() { final JTree tree = new JTree(); tokenPanelTreeModel = new TokenPanelTreeModel(tree); tree.setModel(tokenPanelTreeModel);//w w w .java 2 s . c om tree.setCellRenderer(new TokenPanelTreeCellRenderer()); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); tree.addMouseListener(new MouseAdapter() { // TODO: Make this a handler class, not an aic @Override public void mousePressed(MouseEvent e) { // tree.setSelectionPath(tree.getPathForLocation(e.getX(), e.getY())); TreePath path = tree.getPathForLocation(e.getX(), e.getY()); if (path == null) { return; } Object row = path.getLastPathComponent(); int rowIndex = tree.getRowForLocation(e.getX(), e.getY()); if (SwingUtilities.isLeftMouseButton(e)) { if (!SwingUtil.isShiftDown(e)) { tree.clearSelection(); } tree.addSelectionInterval(rowIndex, rowIndex); if (row instanceof Token) { if (e.getClickCount() == 2) { Token token = (Token) row; getCurrentZoneRenderer().clearSelectedTokens(); getCurrentZoneRenderer().centerOn(new ZonePoint(token.getX(), token.getY())); // Pick an appropriate tool getToolbox().setSelectedTool(token.isToken() ? PointerTool.class : StampTool.class); getCurrentZoneRenderer().setActiveLayer(token.getLayer()); getCurrentZoneRenderer().selectToken(token.getId()); getCurrentZoneRenderer().requestFocusInWindow(); } } } if (SwingUtilities.isRightMouseButton(e)) { if (!isRowSelected(tree.getSelectionRows(), rowIndex) && !SwingUtil.isShiftDown(e)) { tree.clearSelection(); tree.addSelectionInterval(rowIndex, rowIndex); } final int x = e.getX(); final int y = e.getY(); EventQueue.invokeLater(new Runnable() { @Override public void run() { Token firstToken = null; Set<GUID> selectedTokenSet = new HashSet<GUID>(); for (TreePath path : tree.getSelectionPaths()) { if (path.getLastPathComponent() instanceof Token) { Token token = (Token) path.getLastPathComponent(); if (firstToken == null) { firstToken = token; } if (AppUtil.playerOwns(token)) { selectedTokenSet.add(token.getId()); } } } if (!selectedTokenSet.isEmpty()) { try { if (firstToken.isStamp()) { new StampPopupMenu(selectedTokenSet, x, y, getCurrentZoneRenderer(), firstToken).showPopup(tree); } else { new TokenPopupMenu(selectedTokenSet, x, y, getCurrentZoneRenderer(), firstToken).showPopup(tree); } } catch (IllegalComponentStateException icse) { log.info(tree.toString(), icse); } } } }); } } }); TabletopTool.getEventDispatcher().addListener(new AppEventListener() { @Override public void handleAppEvent(AppEvent event) { tokenPanelTreeModel.setZone((Zone) event.getNewValue()); } }, TabletopTool.ZoneEvent.Activated); return tree; }