public GAGenerationTreePanel(GAObjectMonitor monitor, String parentNodeTitle) { super(); selectedChildrenPaths = new Vector(); generationNumber = 1; saveNumber = 0; generations = new DefaultMutableTreeNode(parentNodeTitle); gaMonitor = monitor; setLayout(new BorderLayout()); tree = new JTree(generations); tree.setShowsRootHandles(true); tree.setRootVisible(true); tree.putClientProperty("JTree.lineStyle", "Angled"); // Add Action Listeners MyTreeSelectionListener listener = new MyTreeSelectionListener(monitor.getSelectionInfoPanel()); MyTreeClickListener mlistener = new MyTreeClickListener(); tree.addTreeSelectionListener(listener); tree.addMouseListener(mlistener); // Add Scroll Plane scrollPane = new JScrollPane(tree); add(scrollPane, BorderLayout.CENTER); // Add Menu Bar Functionality createMenuBar(); add(menuBar, BorderLayout.NORTH); }
public ReplicatedTreeView(ReplicatedTree tree, Object title) throws Exception { this.tree = tree; tree.addReplicatedTreeListener(this); addNotify(); setTitle("ReplicatedTreeDemo: mbr=" + title); tree_model = new DefaultTreeModel(root); jtree = new JTree(tree_model); jtree.setDoubleBuffered(true); jtree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); JScrollPane scroll_pane = new JScrollPane(jtree); populateTree(); getContentPane().add(scroll_pane, BorderLayout.CENTER); addWindowListener(this); table_model.setColumnIdentifiers(new String[] {"Name", "Value"}); table_model.addTableModelListener(this); setTableColumnWidths(); tablePanel = new JPanel(); tablePanel.setLayout(new BorderLayout()); tablePanel.add(table.getTableHeader(), BorderLayout.NORTH); tablePanel.add(table, BorderLayout.CENTER); getContentPane().add(tablePanel, BorderLayout.SOUTH); jtree.addTreeSelectionListener(this); // REVISIT MouseListener ml = new MouseAdapter() { public void mouseClicked(MouseEvent e) { int selRow = jtree.getRowForLocation(e.getX(), e.getY()); TreePath selPath = jtree.getPathForLocation(e.getX(), e.getY()); if (selRow != -1) { selected_node = makeFQN(selPath.getPath()); jtree.setSelectionPath(selPath); if (e.getModifiers() == java.awt.event.InputEvent.BUTTON3_MASK) { operationsPopup.show(e.getComponent(), e.getX(), e.getY()); } } } }; jtree.addMouseListener(ml); createMenus(); setLocation(50, 50); setSize( getInsets().left + getInsets().right + 485, getInsets().top + getInsets().bottom + 367); init(); setVisible(true); }
/** * Constructor. * * @param tree a JTree */ public CheckTreeManager(JTree tree) { this.tree = tree; selectionModel = new CheckTreeSelectionModel(tree.getModel()); tree.setCellRenderer(new CheckTreeCellRenderer(tree.getCellRenderer(), selectionModel)); tree.addMouseListener(this); tree.addMouseMotionListener(this); selectionModel.addTreeSelectionListener(this); }
private JPanel createToolPanel() { configurationOverrideCombo.setModel(configurationOverrideModel); final int preferredHeight = configurationOverrideCombo.getPreferredSize().height; configurationOverrideCombo.setPreferredSize(new Dimension(250, preferredHeight)); configurationOverrideCombo.setMaximumSize(new Dimension(350, preferredHeight)); treeModel = new ResultTreeModel(); resultsTree = new Tree(treeModel); resultsTree.setRootVisible(false); final TreeSelectionListener treeSelectionListener = new ToolWindowSelectionListener(); resultsTree.addTreeSelectionListener(treeSelectionListener); final MouseListener treeMouseListener = new ToolWindowMouseListener(); resultsTree.addMouseListener(treeMouseListener); resultsTree.setCellRenderer(new ResultTreeRenderer()); progressLabel = new JLabel(" "); progressBar = new JProgressBar(JProgressBar.HORIZONTAL); progressBar.setMinimum(0); final Dimension progressBarSize = new Dimension(100, progressBar.getPreferredSize().height); progressBar.setMinimumSize(progressBarSize); progressBar.setPreferredSize(progressBarSize); progressBar.setMaximumSize(progressBarSize); progressPanel = new JToolBar(JToolBar.HORIZONTAL); progressPanel.add(Box.createHorizontalStrut(4)); progressPanel.add(new JLabel(CheckStyleBundle.message("plugin.toolwindow.override"))); progressPanel.add(Box.createHorizontalStrut(4)); progressPanel.add(configurationOverrideCombo); progressPanel.add(Box.createHorizontalStrut(4)); progressPanel.addSeparator(); progressPanel.add(Box.createHorizontalStrut(4)); progressPanel.add(progressLabel); progressPanel.add(Box.createHorizontalGlue()); progressPanel.setFloatable(false); progressPanel.setBackground(UIManager.getColor("Panel.background")); progressPanel.setBorder(null); final JPanel toolPanel = new JPanel(new BorderLayout()); toolPanel.add(new JBScrollPane(resultsTree), BorderLayout.CENTER); toolPanel.add(progressPanel, BorderLayout.NORTH); ToolTipManager.sharedInstance().registerComponent(resultsTree); return toolPanel; }
/** Constructor. */ public DatasetTreeView() { // the catalog tree tree = new JTree() { public JToolTip createToolTip() { return new MultilineTooltip(); } }; tree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode(null, false))); tree.setCellRenderer(new MyTreeCellRenderer()); tree.addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent e) { int selRow = tree.getRowForLocation(e.getX(), e.getY()); if (selRow != -1) { TreeNode node = (TreeNode) tree.getLastSelectedPathComponent(); if (node instanceof VariableNode) { VariableIF v = ((VariableNode) node).var; firePropertyChangeEvent(new PropertyChangeEvent(this, "Selection", null, v)); } } if ((selRow != -1) && (e.getClickCount() == 2)) { // acceptSelected(); } } }); tree.putClientProperty("JTree.lineStyle", "Angled"); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.setToggleClickCount(1); ToolTipManager.sharedInstance().registerComponent(tree); // layout setLayout(new BorderLayout()); add(new JScrollPane(tree), BorderLayout.CENTER); }
public void show(List<Rule> rules) { if (original != null) config.restoreState(original); dialog = new JDialog(owner, true); dialog.setTitle(messages.getString("guiConfigWindowTitle")); Collections.sort(rules, new CategoryComparator()); // close dialog when user presses Escape key: final KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); final ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(@SuppressWarnings("unused") ActionEvent actionEvent) { dialog.setVisible(false); } }; final JRootPane rootPane = dialog.getRootPane(); rootPane.registerKeyboardAction(actionListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); // JPanel final JPanel checkBoxPanel = new JPanel(); checkBoxPanel.setLayout(new GridBagLayout()); GridBagConstraints cons = new GridBagConstraints(); cons.anchor = GridBagConstraints.NORTHWEST; cons.gridx = 0; cons.weightx = 1.0; cons.weighty = 1.0; cons.fill = GridBagConstraints.BOTH; DefaultMutableTreeNode rootNode = createTree(rules); DefaultTreeModel treeModel = new DefaultTreeModel(rootNode); treeModel.addTreeModelListener( new TreeModelListener() { @Override public void treeNodesChanged(TreeModelEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getTreePath().getLastPathComponent(); int index = e.getChildIndices()[0]; node = (DefaultMutableTreeNode) (node.getChildAt(index)); if (node instanceof RuleNode) { RuleNode o = (RuleNode) node; if (o.getRule().isDefaultOff()) { if (o.isEnabled()) { config.getEnabledRuleIds().add(o.getRule().getId()); } else { config.getEnabledRuleIds().remove(o.getRule().getId()); } } else { if (o.isEnabled()) { config.getDisabledRuleIds().remove(o.getRule().getId()); } else { config.getDisabledRuleIds().add(o.getRule().getId()); } } } if (node instanceof CategoryNode) { CategoryNode o = (CategoryNode) node; if (o.isEnabled()) { config.getDisabledCategoryNames().remove(o.getCategory().getName()); } else { config.getDisabledCategoryNames().add(o.getCategory().getName()); } } } @Override public void treeNodesInserted(TreeModelEvent e) {} @Override public void treeNodesRemoved(TreeModelEvent e) {} @Override public void treeStructureChanged(TreeModelEvent e) {} }); configTree = new JTree(treeModel); configTree.setRootVisible(false); configTree.setEditable(false); configTree.setCellRenderer(new CheckBoxTreeCellRenderer()); TreeListener.install(configTree); checkBoxPanel.add(configTree, cons); MouseAdapter ma = new MouseAdapter() { private void handlePopupEvent(MouseEvent e) { final JTree tree = (JTree) e.getSource(); TreePath path = tree.getPathForLocation(e.getX(), e.getY()); if (path == null) { return; } DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); TreePath[] paths = tree.getSelectionPaths(); boolean isSelected = false; if (paths != null) { for (TreePath selectionPath : paths) { if (selectionPath.equals(path)) { isSelected = true; } } } if (!isSelected) { tree.setSelectionPath(path); } if (node.isLeaf()) { JPopupMenu popup = new JPopupMenu(); final JMenuItem aboutRuleMenuItem = new JMenuItem(messages.getString("guiAboutRuleMenu")); aboutRuleMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { RuleNode node = (RuleNode) tree.getSelectionPath().getLastPathComponent(); Rule rule = node.getRule(); Language lang = config.getLanguage(); if (lang == null) { lang = Language.getLanguageForLocale(Locale.getDefault()); } Tools.showRuleInfoDialog( tree, messages.getString("guiAboutRuleTitle"), rule.getDescription(), rule, messages, lang.getShortNameWithCountryAndVariant()); } }); popup.add(aboutRuleMenuItem); popup.show(tree, e.getX(), e.getY()); } } @Override public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { handlePopupEvent(e); } } @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { handlePopupEvent(e); } } }; configTree.addMouseListener(ma); final JPanel treeButtonPanel = new JPanel(); cons = new GridBagConstraints(); cons.gridx = 0; cons.gridy = 0; final JButton expandAllButton = new JButton(messages.getString("guiExpandAll")); treeButtonPanel.add(expandAllButton, cons); expandAllButton.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { TreeNode root = (TreeNode) configTree.getModel().getRoot(); TreePath parent = new TreePath(root); for (Enumeration categ = root.children(); categ.hasMoreElements(); ) { TreeNode n = (TreeNode) categ.nextElement(); TreePath child = parent.pathByAddingChild(n); configTree.expandPath(child); } } }); cons.gridx = 1; cons.gridy = 0; final JButton collapseAllbutton = new JButton(messages.getString("guiCollapseAll")); treeButtonPanel.add(collapseAllbutton, cons); collapseAllbutton.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { TreeNode root = (TreeNode) configTree.getModel().getRoot(); TreePath parent = new TreePath(root); for (Enumeration categ = root.children(); categ.hasMoreElements(); ) { TreeNode n = (TreeNode) categ.nextElement(); TreePath child = parent.pathByAddingChild(n); configTree.collapsePath(child); } } }); final JPanel motherTonguePanel = new JPanel(); motherTonguePanel.add(new JLabel(messages.getString("guiMotherTongue")), cons); motherTongueBox = new JComboBox(getPossibleMotherTongues()); if (config.getMotherTongue() != null) { motherTongueBox.setSelectedItem(config.getMotherTongue().getTranslatedName(messages)); } motherTongueBox.addItemListener( new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { Language motherTongue; if (motherTongueBox.getSelectedItem() instanceof String) { motherTongue = getLanguageForLocalizedName(motherTongueBox.getSelectedItem().toString()); } else { motherTongue = (Language) motherTongueBox.getSelectedItem(); } config.setMotherTongue(motherTongue); } } }); motherTonguePanel.add(motherTongueBox, cons); final JPanel portPanel = new JPanel(); portPanel.setLayout(new GridBagLayout()); // TODO: why is this now left-aligned?!?! cons = new GridBagConstraints(); cons.insets = new Insets(0, 4, 0, 0); cons.gridx = 0; cons.gridy = 0; cons.anchor = GridBagConstraints.WEST; cons.fill = GridBagConstraints.NONE; cons.weightx = 0.0f; if (!insideOOo) { serverCheckbox = new JCheckBox(Tools.getLabel(messages.getString("guiRunOnPort"))); serverCheckbox.setMnemonic(Tools.getMnemonic(messages.getString("guiRunOnPort"))); serverCheckbox.setSelected(config.getRunServer()); portPanel.add(serverCheckbox, cons); serverCheckbox.addActionListener( new ActionListener() { @Override public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) { serverPortField.setEnabled(serverCheckbox.isSelected()); serverSettingsCheckbox.setEnabled(serverCheckbox.isSelected()); } }); serverCheckbox.addItemListener( new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { config.setRunServer(serverCheckbox.isSelected()); } }); serverPortField = new JTextField(Integer.toString(config.getServerPort())); serverPortField.setEnabled(serverCheckbox.isSelected()); serverSettingsCheckbox = new JCheckBox(Tools.getLabel(messages.getString("useGUIConfig"))); // TODO: without this the box is just a few pixels small, but why??: serverPortField.setMinimumSize(new Dimension(100, 25)); cons.gridx = 1; portPanel.add(serverPortField, cons); serverPortField .getDocument() .addDocumentListener( new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { changedUpdate(e); } @Override public void removeUpdate(DocumentEvent e) { changedUpdate(e); } @Override public void changedUpdate(DocumentEvent e) { try { int serverPort = Integer.parseInt(serverPortField.getText()); if (serverPort > -1 && serverPort < 65536) { serverPortField.setForeground(null); config.setServerPort(serverPort); } else { serverPortField.setForeground(Color.RED); } } catch (NumberFormatException ex) { serverPortField.setForeground(Color.RED); } } }); cons.gridx = 0; cons.gridy = 10; serverSettingsCheckbox.setMnemonic(Tools.getMnemonic(messages.getString("useGUIConfig"))); serverSettingsCheckbox.setSelected(config.getUseGUIConfig()); serverSettingsCheckbox.setEnabled(config.getRunServer()); serverSettingsCheckbox.addItemListener( new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { config.setUseGUIConfig(serverSettingsCheckbox.isSelected()); } }); portPanel.add(serverSettingsCheckbox, cons); } final JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridBagLayout()); okButton = new JButton(Tools.getLabel(messages.getString("guiOKButton"))); okButton.setMnemonic(Tools.getMnemonic(messages.getString("guiOKButton"))); okButton.addActionListener(this); cancelButton = new JButton(Tools.getLabel(messages.getString("guiCancelButton"))); cancelButton.setMnemonic(Tools.getMnemonic(messages.getString("guiCancelButton"))); cancelButton.addActionListener(this); cons = new GridBagConstraints(); cons.insets = new Insets(0, 4, 0, 0); buttonPanel.add(okButton, cons); buttonPanel.add(cancelButton, cons); final Container contentPane = dialog.getContentPane(); contentPane.setLayout(new GridBagLayout()); cons = new GridBagConstraints(); cons.insets = new Insets(4, 4, 4, 4); cons.gridx = 0; cons.gridy = 0; cons.weightx = 10.0f; cons.weighty = 10.0f; cons.fill = GridBagConstraints.BOTH; contentPane.add(new JScrollPane(checkBoxPanel), cons); cons.gridx = 0; cons.gridy = 1; cons.weightx = 0.0f; cons.weighty = 0.0f; cons.fill = GridBagConstraints.NONE; cons.anchor = GridBagConstraints.LINE_END; contentPane.add(treeButtonPanel, cons); cons.gridx = 0; cons.gridy = 2; cons.weightx = 0.0f; cons.weighty = 0.0f; cons.fill = GridBagConstraints.NONE; cons.anchor = GridBagConstraints.WEST; contentPane.add(motherTonguePanel, cons); cons.gridx = 0; cons.gridy = 3; cons.weightx = 0.0f; cons.weighty = 0.0f; cons.fill = GridBagConstraints.NONE; cons.anchor = GridBagConstraints.WEST; contentPane.add(portPanel, cons); cons.gridx = 0; cons.gridy = 4; cons.weightx = 0.0f; cons.weighty = 0.0f; cons.fill = GridBagConstraints.NONE; cons.anchor = GridBagConstraints.EAST; contentPane.add(buttonPanel, cons); dialog.pack(); dialog.setSize(500, 500); // center on screen: final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); final Dimension frameSize = dialog.getSize(); dialog.setLocation( screenSize.width / 2 - frameSize.width / 2, screenSize.height / 2 - frameSize.height / 2); dialog.setLocationByPlatform(true); dialog.setVisible(true); }
public void addResultClickListener(ResultClickListener listener) { tree.addMouseListener(listener); }
public JTrees() { JFrame frame = new JFrame("JTree Demo"); Container c = frame.getContentPane(); c.setLayout(new BorderLayout()); // Create top node of a tree final DefaultMutableTreeNode top = new DefaultMutableTreeNode("Course"); // Create a subtree UG final DefaultMutableTreeNode UG = new DefaultMutableTreeNode("UG"); top.add(UG); final DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("B.E"); UG.add(a1); final DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("B.C.A"); UG.add(a2); final DefaultMutableTreeNode a3 = new DefaultMutableTreeNode("B.Sc"); UG.add(a3); final DefaultMutableTreeNode a4 = new DefaultMutableTreeNode("B.Com"); UG.add(a4); final DefaultMutableTreeNode a5 = new DefaultMutableTreeNode("B.A"); UG.add(a5); // Create a subtree PG final DefaultMutableTreeNode PG = new DefaultMutableTreeNode("PG"); top.add(PG); final DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("M.E"); PG.add(b1); final DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("M.C.A"); PG.add(b2); final DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("M.Sc"); PG.add(b3); final DefaultMutableTreeNode b4 = new DefaultMutableTreeNode("M.Com"); PG.add(b4); final DefaultMutableTreeNode b5 = new DefaultMutableTreeNode("M.A"); PG.add(b5); // Creating tree final JTree tree = new JTree(top); int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; final JScrollPane jsp = new JScrollPane(tree, v, h); c.add(jsp, BorderLayout.CENTER); final JTextField text = new JTextField("", 20); c.add(text, BorderLayout.SOUTH); tree.addMouseListener( new MouseAdapter() { public void mouseClicked(MouseEvent me) { TreePath tp = tree.getPathForLocation(me.getX(), me.getY()); if (tp != null) text.setText(tp.toString()); else text.setText(""); } }); if (top.children() == b1) { System.out.println("M.E Cource Selected"); } frame.setSize(300, 200); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
private ClientWindow(String name) { setTitle("ClientWindow"); setContentPane(WindowPanel); pack(); clientFacade = ClientFacade.getClientFacadeByClientName(name); NameLabel.setText(clientFacade.getClientName()); productItemMap = clientFacade.getProductList(); FormOrderPanel.setVisible(false); tableModel = new ProductsTableModel(); ProductsTable.setModel(tableModel); root = new DefaultMutableTreeNode("ClientOrders"); generateOrdersTree(); OrdersTree.setModel(new DefaultTreeModel(root)); OrdersTree.addMouseListener( new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { TreePath pathSelected = OrdersTree.getSelectionPath(); if (OrdersTree.isPathSelected(pathSelected) && OrdersTree.getModel().isLeaf(pathSelected.getLastPathComponent())) { ManagerPopupMenu managerPopupMenu = new ManagerPopupMenu(); managerPopupMenu.getJPopupMenu().show(e.getComponent(), e.getX(), e.getY()); } } } }); OrdersTree.setShowsRootHandles(true); OrdersTree.setRootVisible(true); OrdersTree.getSelectionModel() .addTreeSelectionListener( e -> { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) OrdersTree.getLastSelectedPathComponent(); if (selectedNode.isLeaf()) { if (!((String) selectedNode.getUserObject()).equals("ClientOrders")) { List<ProductRow> productRowList = clientFacade.getProductRowsByOrder( clientFacade.getValidDate((String) selectedNode.getUserObject())); productRowList .stream() .forEach( productRow -> ClientWindow.this.tableModel.addRow( productRow.getId(), productRow.getType(), productRow.getPrice(), productRow.getNumber())); ProductsTable.revalidate(); } } }); Font font = new Font("Verdana", Font.PLAIN, 12); jMenuBar = new JMenuBar(); jMenu = new JMenu("Actions"); JMenuItem jCreateProviderOrderItem = new JMenuItem("Создать заказ"); jCreateProviderOrderItem.setFont(font); jCreateProviderOrderItem.addActionListener(e -> openClientOrderForm()); jMenu.add(jCreateProviderOrderItem); jMenu.addSeparator(); JMenuItem jCloseItem = new JMenuItem("Закрыть"); jCloseItem.setFont(font); jCloseItem.addActionListener(e -> close()); jMenu.add(jCloseItem); jMenuBar.add(jMenu); MenuPanel.add(jMenuBar); OrderOkButton.addActionListener(e -> createClientOrder()); OrderCancelButton.addActionListener(e -> closeClientOrderForm()); TypeComboBox.addItemListener(e -> setPriceByType()); AddProductButton.addActionListener( e -> { if (productItemList == null) { productItemList = new HashMap<String, ProductItem>(); } productItemList.put( TypeComboBox.getSelectedItem().toString(), new ProductItem( TypeComboBox.getSelectedItem().toString(), PriceTextField.getText(), AmountTextField.getText())); }); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); BurgerButton.addActionListener(e -> FastFoodTextArea.append(clientFacade.getBurger())); RunServerButton.addActionListener(e -> InfoTextArea.append(clientFacade.runServer())); StopServerButton.addActionListener(e -> InfoTextArea.append(clientFacade.stopServer())); }
private JComponent createMasterView() { myTreeController = new BreakpointItemsTreeController(myRulesEnabled); JTree tree = new BreakpointsCheckboxTree(myProject, myTreeController); new AnAction("BreakpointDialog.GoToSource") { @Override public void actionPerformed(AnActionEvent e) { navigate(); close(OK_EXIT_CODE); } }.registerCustomShortcutSet( new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0)), tree); new AnAction("BreakpointDialog.ShowSource") { @Override public void actionPerformed(AnActionEvent e) { navigate(); } }.registerCustomShortcutSet( ActionManager.getInstance().getAction(IdeActions.ACTION_EDIT_SOURCE).getShortcutSet(), tree); tree.addMouseListener( new MouseAdapter() { @Override public void mouseClicked(MouseEvent event) { if (event.getClickCount() == 2 && UIUtil.isActionClick(event, MouseEvent.MOUSE_CLICKED) && !UIUtil.isSelectionButtonDown(event) && !event.isConsumed()) { navigate(); close(OK_EXIT_CODE); } } }); final DefaultActionGroup breakpointTypes = new DefaultActionGroup(); for (BreakpointPanelProvider provider : myBreakpointsPanelProviders) { breakpointTypes.addAll(provider.getAddBreakpointActions(myProject)); } ToolbarDecorator decorator = ToolbarDecorator.createDecorator(tree) .setAddAction( new AnActionButtonRunnable() { @Override public void run(AnActionButton button) { JBPopupFactory.getInstance() .createActionGroupPopup( null, breakpointTypes, DataManager.getInstance().getDataContext(button.getContextComponent()), JBPopupFactory.ActionSelectionAid.NUMBERING, false) .show(button.getPreferredPopupPoint()); } }) .setRemoveAction( new AnActionButtonRunnable() { @Override public void run(AnActionButton button) { myTreeController.removeSelectedBreakpoints(myProject); } }) .setRemoveActionUpdater( new AnActionButtonUpdater() { @Override public boolean isEnabled(AnActionEvent e) { boolean enabled = false; final ItemWrapper[] items = myMasterController.getSelectedItems(); for (ItemWrapper item : items) { if (item.allowedToRemove()) { enabled = true; } } return enabled; } }); for (ToggleActionButton action : myToggleRuleActions) { decorator.addExtraAction(action); } JPanel decoratedTree = decorator.createPanel(); myTreeController.setTreeView(tree); myDetailController.setTree(tree); myTreeController.buildTree(myBreakpointItems); initSelection(myBreakpointItems); final BreakpointPanelProvider.BreakpointsListener listener = new BreakpointPanelProvider.BreakpointsListener() { @Override public void breakpointsChanged() { collectItems(); myTreeController.rebuildTree(myBreakpointItems); } }; for (BreakpointPanelProvider provider : myBreakpointsPanelProviders) { provider.addListener(listener, myProject, myListenerDisposable); } return decoratedTree; }
public void init() { guangdong.add(foshan); guangdong.add(shantou); guangxi.add(guilin); guangxi.add(nanning); root.add(guangdong); root.add(guangxi); jf = new JFrame("树"); tree = new JTree(root); // 获取JTree对应的TreeModel对象 model = (DefaultTreeModel) tree.getModel(); // 设置JTree可编辑 tree.setEditable(true); MouseListener ml = new MouseAdapter() { // 按下鼠标时候获得被拖动的节点 public void mousePressed(MouseEvent e) { // 如果需要唯一确定某个节点,必须通过TreePath来获取。 TreePath tp = tree.getPathForLocation(e.getX(), e.getY()); if (tp != null) { movePath = tp; } } // 鼠标松开时获得需要拖到哪个父节点 public void mouseReleased(MouseEvent e) { // 根据鼠标松开时的TreePath来获取TreePath TreePath tp = tree.getPathForLocation(e.getX(), e.getY()); if (tp != null && movePath != null) { // 阻止向子节点拖动 if (movePath.isDescendant(tp) && movePath != tp) { JOptionPane.showMessageDialog( jf, "目标节点是被移动节点的子节点,无法移动!", "非法操作", JOptionPane.ERROR_MESSAGE); return; } // 既不是向子节点移动,而且鼠标按下、松开的不是同一个节点 else if (movePath != tp) { System.out.println(tp.getLastPathComponent()); // add方法可以先将原节点从原父节点删除,再添加到新父节点中 ((DefaultMutableTreeNode) tp.getLastPathComponent()) .add((DefaultMutableTreeNode) movePath.getLastPathComponent()); movePath = null; tree.updateUI(); } } } }; tree.addMouseListener(ml); JPanel panel = new JPanel(); addSiblingButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { // 获取选中节点 DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); // 如果节点为空,直接返回 if (selectedNode == null) return; // 获取该选中节点的父节点 DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode.getParent(); // 如果父节点为空,直接返回 if (parent == null) return; // 创建一个新节点 DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("新节点"); // 获取选中节点的选中索引 int selectedIndex = parent.getIndex(selectedNode); // 在选中位置插入新节点 model.insertNodeInto(newNode, parent, selectedIndex + 1); // --------下面代码实现显示新节点(自动展开父节点)------- // 获取从根节点到新节点的所有节点 TreeNode[] nodes = model.getPathToRoot(newNode); // 使用指定的节点数组来创建TreePath TreePath path = new TreePath(nodes); // 显示指定TreePath tree.scrollPathToVisible(path); } }); panel.add(addSiblingButton); addChildButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { // 获取选中节点 DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); // 如果节点为空,直接返回 if (selectedNode == null) return; // 创建一个新节点 DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("新节点"); // 直接通过model来添加新节点,则无需通过调用JTree的updateUI方法 // model.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount()); // 直接通过节点添加新节点,则需要调用tree的updateUI方法 selectedNode.add(newNode); // --------下面代码实现显示新节点(自动展开父节点)------- TreeNode[] nodes = model.getPathToRoot(newNode); TreePath path = new TreePath(nodes); tree.scrollPathToVisible(path); tree.updateUI(); } }); panel.add(addChildButton); deleteButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (selectedNode != null && selectedNode.getParent() != null) { // 删除指定节点 model.removeNodeFromParent(selectedNode); } } }); panel.add(deleteButton); editButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { TreePath selectedPath = tree.getSelectionPath(); if (selectedPath != null) { // 编辑选中节点 tree.startEditingAtPath(selectedPath); } } }); panel.add(editButton); jf.add(new JScrollPane(tree)); jf.add(panel, BorderLayout.SOUTH); jf.pack(); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setVisible(true); }