Example usage for javax.swing DropMode ON

List of usage examples for javax.swing DropMode ON

Introduction

In this page you can find the example usage for javax.swing DropMode ON.

Prototype

DropMode ON

To view the source code for javax.swing DropMode ON.

Click Source Link

Document

The drop location should be tracked in terms of the index of existing items.

Usage

From source file:DropModeON.java

public static void main(String[] args) {
    JPanel north = new JPanel();
    north.add(new JLabel("Drag from here:"));
    JTextField field = new JTextField(10);
    field.setDragEnabled(true);/*from ww  w .j a va2  s.  co  m*/
    north.add(field);

    final DefaultListModel listModel = new DefaultListModel();
    listModel.addElement("first");
    listModel.addElement("second");
    final JList list = new JList(listModel);
    list.setDragEnabled(true);

    list.setTransferHandler(new TransferHandler() {
        public boolean canImport(TransferHandler.TransferSupport support) {
            if (!support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                return false;
            }
            JList.DropLocation dl = (JList.DropLocation) support.getDropLocation();
            if (dl.getIndex() == -1) {
                return false;
            } else {
                return true;
            }
        }

        public boolean importData(TransferHandler.TransferSupport support) {
            if (!canImport(support)) {
                return false;
            }

            Transferable transferable = support.getTransferable();
            String data;
            try {
                data = (String) transferable.getTransferData(DataFlavor.stringFlavor);
            } catch (Exception e) {
                return false;
            }

            JList.DropLocation dl = (JList.DropLocation) support.getDropLocation();
            int index = dl.getIndex();
            if (dl.isInsert()) {
                listModel.add(index, data);
            } else {
                listModel.set(index, data);
            }

            // Scroll to display the element that was dropped
            Rectangle r = list.getCellBounds(index, index);
            list.scrollRectToVisible(r);
            return true;
        }
    });
    JScrollPane center = new JScrollPane();
    center.setViewportView(list);

    list.setDropMode(DropMode.ON);
    JPanel cp = new JPanel();
    cp.setLayout(new BorderLayout());
    cp.add(north, BorderLayout.NORTH);
    cp.add(center, BorderLayout.CENTER);
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(cp);
    frame.pack();
    frame.setVisible(true);
}

From source file:com.igormaznitsa.sciareto.ui.tree.ExplorerTree.java

public ExplorerTree(@Nonnull final Context context) {
      super();//from   w w w .  j a  va2  s  .co  m
      this.projectTree = new DnDTree();
      this.context = context;
      this.projectTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
      this.projectTree.setDropMode(DropMode.ON);

      this.projectTree.setEditable(true);

      ToolTipManager.sharedInstance().registerComponent(this.projectTree);

      this.projectTree.setCellRenderer(new TreeCellRenderer());
      this.projectTree.setModel(new NodeProjectGroup(context, "."));
      this.projectTree.setRootVisible(false);
      this.setViewportView(this.projectTree);

      this.projectTree.addMouseListener(new MouseAdapter() {
          @Override
          public void mouseClicked(@Nonnull final MouseEvent e) {
              if (e.getClickCount() > 1) {
                  final int selRow = projectTree.getRowForLocation(e.getX(), e.getY());
                  final TreePath selPath = projectTree.getPathForLocation(e.getX(), e.getY());
                  if (selRow >= 0) {
                      final NodeFileOrFolder node = (NodeFileOrFolder) selPath.getLastPathComponent();
                      if (node != null && node.isLeaf()) {
                          final File file = node.makeFileForNode();
                          if (file != null && !context.openFileAsTab(file)) {
                              UiUtils.openInSystemViewer(file);
                          }
                      }
                  }
              }
          }

          @Override
          public void mouseReleased(@Nonnull final MouseEvent e) {
              if (e.isPopupTrigger()) {
                  processPopup(e);
              }
          }

          @Override
          public void mousePressed(@Nonnull final MouseEvent e) {
              if (e.isPopupTrigger()) {
                  processPopup(e);
              }
          }

          private void processPopup(@Nonnull final MouseEvent e) {
              final TreePath selPath = projectTree.getPathForLocation(e.getX(), e.getY());
              if (selPath != null) {
                  projectTree.setSelectionPath(selPath);
                  final Object last = selPath.getLastPathComponent();
                  if (last instanceof NodeFileOrFolder) {
                      makePopupMenu((NodeFileOrFolder) last).show(e.getComponent(), e.getX(), e.getY());
                  }
              }
          }

      });
  }

From source file:DropDemo.java

public void actionPerformed(ActionEvent ae) {
    Object val = dropCombo.getSelectedItem();
    if (val == "USE_SELECTION") {
        list.setDropMode(DropMode.USE_SELECTION);
    } else if (val == "ON") {
        list.setDropMode(DropMode.ON);
    } else if (val == "INSERT") {
        list.setDropMode(DropMode.INSERT);
    } else if (val == "ON_OR_INSERT") {
        list.setDropMode(DropMode.ON_OR_INSERT);
    }//from  w  ww  . ja  va  2 s .  com
}

From source file:LocationSensitiveDemo.java

public LocationSensitiveDemo() {
    super("Location Sensitive Drag and Drop Demo");

    treeModel = getDefaultTreeModel();/*from w w w  . j  a v  a 2s  .c  o m*/
    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:ListCutPaste.java

public ListCutPaste() {
    super(new BorderLayout());
    lh = new ListTransferHandler();

    JPanel panel = new JPanel(new GridLayout(1, 3));
    DefaultListModel list1Model = new DefaultListModel();
    list1Model.addElement("alpha");
    list1Model.addElement("beta");
    list1Model.addElement("gamma");
    list1Model.addElement("delta");
    list1Model.addElement("epsilon");
    list1Model.addElement("zeta");
    JList list1 = new JList(list1Model);
    list1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane sp1 = new JScrollPane(list1);
    sp1.setPreferredSize(new Dimension(400, 100));
    list1.setDragEnabled(true);/*from   w  w  w.j a v a 2s.  c  o  m*/
    list1.setTransferHandler(lh);
    list1.setDropMode(DropMode.ON_OR_INSERT);
    setMappings(list1);
    JPanel pan1 = new JPanel(new BorderLayout());
    pan1.add(sp1, BorderLayout.CENTER);
    pan1.setBorder(BorderFactory.createTitledBorder("Greek Alphabet"));
    panel.add(pan1);

    DefaultListModel list2Model = new DefaultListModel();
    list2Model.addElement("uma");
    list2Model.addElement("dois");
    list2Model.addElement("tres");
    list2Model.addElement("quatro");
    list2Model.addElement("cinco");
    list2Model.addElement("seis");
    JList list2 = new JList(list2Model);
    list2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list2.setDragEnabled(true);
    JScrollPane sp2 = new JScrollPane(list2);
    sp2.setPreferredSize(new Dimension(400, 100));
    list2.setTransferHandler(lh);
    list2.setDropMode(DropMode.INSERT);
    setMappings(list2);
    JPanel pan2 = new JPanel(new BorderLayout());
    pan2.add(sp2, BorderLayout.CENTER);
    pan2.setBorder(BorderFactory.createTitledBorder("Portuguese Numbers"));
    panel.add(pan2);

    DefaultListModel list3Model = new DefaultListModel();
    list3Model.addElement("adeen");
    list3Model.addElement("dva");
    list3Model.addElement("tri");
    list3Model.addElement("chyetirye");
    list3Model.addElement("pyat");
    list3Model.addElement("shest");
    JList list3 = new JList(list3Model);
    list3.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list3.setDragEnabled(true);
    JScrollPane sp3 = new JScrollPane(list3);
    sp3.setPreferredSize(new Dimension(400, 100));
    list3.setTransferHandler(lh);
    list3.setDropMode(DropMode.ON);
    setMappings(list3);
    JPanel pan3 = new JPanel(new BorderLayout());
    pan3.add(sp3, BorderLayout.CENTER);
    pan3.setBorder(BorderFactory.createTitledBorder("Russian Numbers"));
    panel.add(pan3);

    setPreferredSize(new Dimension(500, 200));
    add(panel, BorderLayout.CENTER);
}

From source file:edu.harvard.mcz.imagecapture.encoder.UnitTrayLabelBrowser.java

/**
 * This method initializes jTable   //from   w  ww  .j av a2 s . c  om
 *    
 * @return javax.swing.JTable   
 */
private JTable getJTable() {
    if (jTable == null) {
        tableModel = new UnitTrayLabelTableModel();
        jTable = new DragDropJTable(tableModel);
        jTable.setDragEnabled(true);
        jTable.setDropMode(DropMode.ON);
        //tableModel.addUndoableEditListener(new MyUndoableEditListener());
        sorter = new TableRowSorter<UnitTrayLabelTableModel>(tableModel);
        jTable.setRowSorter(sorter);
    }
    return jTable;
}

From source file:com.diversityarrays.kdxplore.field.FieldViewDialog.java

public FieldViewDialog(Window owner, String title, SampleGroupChoice sgcSamples, Trial trial,
        SampleGroupChoice sgcNewMedia, KDSmartDatabase db) throws IOException {
    super(owner, title, ModalityType.MODELESS);

    advanceRetreatControls = Box.createHorizontalBox();
    advanceRetreatControls.add(new JButton(retreatAction));
    advanceRetreatControls.add(new JButton(advanceAction));

    autoAdvanceControls = Box.createHorizontalBox();
    autoAdvanceControls.add(new JButton(autoAdvanceAction));

    autoAdvanceOption.addActionListener(new ActionListener() {
        @Override/*from www  .  j  av a 2  s .c  o  m*/
        public void actionPerformed(ActionEvent e) {
            updateMovementControls();
        }
    });

    this.database = db;
    this.sampleGroupChoiceForSamples = sgcSamples;
    this.sampleGroupChoiceForNewMedia = sgcNewMedia;

    NumberSpinner fontSpinner = new NumberSpinner(new SpinnerNumberModel(), "0.00");

    this.fieldViewPanel = FieldViewPanel.create(database, trial, SeparatorVisibilityOption.VISIBLE, null,
            Box.createHorizontalGlue(), new JButton(showInfoAction), Box.createHorizontalGlue(),
            new JLabel("Font Size:"), fontSpinner, Box.createHorizontalGlue(), advanceRetreatControls,
            autoAdvanceOption, autoAdvanceControls);

    initialiseAction(advanceAction, "ic_object_advance_black.png", "Auto-Advance");

    this.xyProvider = fieldViewPanel.getXYprovider();
    this.traitMap = fieldViewPanel.getTraitMap();

    fieldLayoutTable = fieldViewPanel.getFieldLayoutTable();

    JScrollPane scrollPane = fieldViewPanel.getFieldTableScrollPane();
    scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    fieldLayoutTable.setTransferHandler(flth);
    fieldLayoutTable.setDropMode(DropMode.ON);

    fieldLayoutTable.addMouseListener(new MouseAdapter() {
        JPopupMenu popupMenu;

        @Override
        public void mouseClicked(MouseEvent e) {
            if (!SwingUtilities.isRightMouseButton(e) || 1 != e.getClickCount()) {
                return;
            }
            Point pt = e.getPoint();
            int row = fieldLayoutTable.rowAtPoint(pt);
            if (row >= 0) {
                int col = fieldLayoutTable.columnAtPoint(pt);
                if (col >= 0) {
                    Plot plot = fieldViewPanel.getPlotAt(col, row);
                    if (plot != null) {
                        if (popupMenu == null) {
                            popupMenu = new JPopupMenu("View Attachments");
                        }
                        popupMenu.removeAll();

                        Set<File> set = plot.getMediaFiles();
                        if (Check.isEmpty(set)) {
                            popupMenu.add(new JMenuItem("No Attachments available"));
                        } else {
                            for (File file : set) {
                                Action a = new AbstractAction(file.getName()) {
                                    @Override
                                    public void actionPerformed(ActionEvent e) {
                                        try {
                                            Desktop.getDesktop().browse(file.toURI());
                                        } catch (IOException e1) {
                                            MsgBox.warn(FieldViewDialog.this, e1, file.getName());
                                        }
                                    }
                                };
                                popupMenu.add(new JMenuItem(a));
                            }
                        }
                        popupMenu.show(fieldLayoutTable, pt.x, pt.y);
                    }
                }
            }
        }

    });
    Font font = fieldLayoutTable.getFont();
    float fontSize = font.getSize2D();

    fontSizeModel = new SpinnerNumberModel(fontSize, fontSize, 50.0, 1.0);
    fontSpinner.setModel(fontSizeModel);
    fontSizeModel.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            float fsize = fontSizeModel.getNumber().floatValue();
            System.out.println("Using fontSize=" + fsize);
            Font font = fieldLayoutTable.getFont().deriveFont(fsize);
            fieldLayoutTable.setFont(font);
            FontMetrics fm = fieldLayoutTable.getFontMetrics(font);
            int lineHeight = fm.getMaxAscent() + fm.getMaxDescent();
            fieldLayoutTable.setRowHeight(4 * lineHeight);

            //                GuiUtil.initialiseTableColumnWidths(fieldLayoutTable, false);

            fieldLayoutTable.repaint();
        }
    });

    fieldLayoutTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    fieldLayoutTable.setResizable(true, true);
    fieldLayoutTable.getTableColumnResizer().setResizeAllColumns(true);

    advanceAction.setEnabled(false);
    fieldLayoutTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                handlePlotSelection();
            }
        }
    });
    TableColumnModel columnModel = fieldLayoutTable.getColumnModel();
    columnModel.addColumnModelListener(new TableColumnModelListener() {
        @Override
        public void columnSelectionChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                handlePlotSelection();
            }
        }

        @Override
        public void columnRemoved(TableColumnModelEvent e) {
        }

        @Override
        public void columnMoved(TableColumnModelEvent e) {
        }

        @Override
        public void columnMarginChanged(ChangeEvent e) {
        }

        @Override
        public void columnAdded(TableColumnModelEvent e) {
        }
    });

    PropertyChangeListener listener = new PropertyChangeListener() {
        // Use a timer and redisplay other columns when delay is GT 100 ms

        Timer timer = new Timer(true);
        TimerTask timerTask;
        long lastActive;
        boolean busy = false;
        private int eventColumnWidth;
        private TableColumn eventColumn;

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if (busy) {
                return;
            }

            if (evt.getSource() instanceof TableColumn && "width".equals(evt.getPropertyName())) {

                eventColumn = (TableColumn) evt.getSource();
                eventColumnWidth = eventColumn.getWidth();

                lastActive = System.currentTimeMillis();
                if (timerTask == null) {
                    timerTask = new TimerTask() {
                        @Override
                        public void run() {
                            if (System.currentTimeMillis() - lastActive > 200) {
                                timerTask.cancel();
                                timerTask = null;

                                busy = true;
                                try {
                                    for (Enumeration<TableColumn> en = columnModel.getColumns(); en
                                            .hasMoreElements();) {
                                        TableColumn tc = en.nextElement();
                                        if (tc != eventColumn) {
                                            tc.setWidth(eventColumnWidth);
                                        }
                                    }
                                } finally {
                                    busy = false;
                                }
                            }
                        }
                    };
                    timer.scheduleAtFixedRate(timerTask, 100, 150);
                }
            }
        }
    };
    for (Enumeration<TableColumn> en = columnModel.getColumns(); en.hasMoreElements();) {
        TableColumn tc = en.nextElement();
        tc.addPropertyChangeListener(listener);
    }

    Map<Integer, Plot> plotById = new HashMap<>();
    for (Plot plot : fieldViewPanel.getFieldLayout()) {
        plotById.put(plot.getPlotId(), plot);
    }

    TrialItemVisitor<Sample> sampleVisitor = new TrialItemVisitor<Sample>() {
        @Override
        public void setExpectedItemCount(int count) {
        }

        @Override
        public boolean consumeItem(Sample sample) throws IOException {

            Plot plot = plotById.get(sample.getPlotId());
            if (plot == null) {
                throw new IOException("Missing plot for plotId=" + sample.getPlotId() + " sampleIdent="
                        + Util.createUniqueSampleKey(sample));
            }
            plot.addSample(sample);

            SampleCounts counts = countsByTraitId.get(sample.getTraitId());
            if (counts == null) {
                counts = new SampleCounts();
                countsByTraitId.put(sample.getTraitId(), counts);
            }
            if (sample.hasBeenScored()) {
                ++counts.scored;
            } else {
                ++counts.unscored;
            }
            return true;
        }
    };
    database.visitSamplesForTrial(sampleGroupChoiceForSamples, trial.getTrialId(),
            SampleOrder.ALL_BY_PLOT_ID_THEN_TRAIT_ID_THEN_INSTANCE_NUMBER_ORDER_THEN_SPECIMEN_NUMBER,
            sampleVisitor);

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    this.trial = trial;

    KDClientUtils.initAction(ImageId.SETTINGS_24, showInfoAction, "Trial Summary");

    Action clear = new AbstractAction("Clear") {
        @Override
        public void actionPerformed(ActionEvent e) {
            infoTextArea.setText("");
        }
    };
    JPanel bottom = new JPanel(new BorderLayout());
    bottom.add(GuiUtil.createLabelSeparator("Plot Details", new JButton(clear)), BorderLayout.NORTH);
    bottom.add(new JScrollPane(infoTextArea), BorderLayout.CENTER);
    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, fieldViewPanel,
            new JScrollPane(infoTextArea));
    splitPane.setResizeWeight(0.0);
    splitPane.setOneTouchExpandable(true);

    setContentPane(splitPane);

    updateMovementControls();
    pack();
}

From source file:com.mirth.connect.client.ui.ChannelPanel.java

private void initComponents() {
    splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    splitPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
    splitPane.setOneTouchExpandable(true);

    topPanel = new JPanel();

    List<String> columns = new ArrayList<String>();

    for (ChannelColumnPlugin plugin : LoadedExtensions.getInstance().getChannelColumnPlugins().values()) {
        if (plugin.isDisplayFirst()) {
            columns.add(plugin.getColumnHeader());
        }/*from www  . ja v  a2s  . c  o  m*/
    }

    columns.addAll(Arrays.asList(DEFAULT_COLUMNS));

    for (ChannelColumnPlugin plugin : LoadedExtensions.getInstance().getChannelColumnPlugins().values()) {
        if (!plugin.isDisplayFirst()) {
            columns.add(plugin.getColumnHeader());
        }
    }

    channelTable = new MirthTreeTable("channelPanel", new LinkedHashSet<String>(columns));

    channelTable.setColumnFactory(new ChannelTableColumnFactory());

    ChannelTreeTableModel model = new ChannelTreeTableModel();
    model.setColumnIdentifiers(columns);
    model.setNodeFactory(new DefaultChannelTableNodeFactory());
    channelTable.setTreeTableModel(model);

    channelTable.setDoubleBuffered(true);
    channelTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    channelTable.getTreeSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    channelTable.setHorizontalScrollEnabled(true);
    channelTable.packTable(UIConstants.COL_MARGIN);
    channelTable.setRowHeight(UIConstants.ROW_HEIGHT);
    channelTable.setOpaque(true);
    channelTable.setRowSelectionAllowed(true);
    channelTable.setSortable(true);
    channelTable.putClientProperty("JTree.lineStyle", "Horizontal");
    channelTable.setAutoCreateColumnsFromModel(false);
    channelTable.setShowGrid(true, true);
    channelTable.restoreColumnPreferences();
    channelTable.setMirthColumnControlEnabled(true);

    channelTable.setDragEnabled(true);
    channelTable.setDropMode(DropMode.ON);
    channelTable.setTransferHandler(new ChannelTableTransferHandler() {
        @Override
        public boolean canImport(TransferSupport support) {
            // Don't allow files to be imported when the save task is enabled 
            if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor) && isSaveEnabled()) {
                return false;
            }
            return super.canImport(support);
        }

        @Override
        public void importFile(final File file, final boolean showAlerts) {
            try {
                SwingUtilities.invokeAndWait(new Runnable() {
                    @Override
                    public void run() {
                        String fileString = StringUtils.trim(parent.readFileToString(file));

                        try {
                            // If the table is in channel view, don't allow groups to be imported
                            ChannelGroup group = ObjectXMLSerializer.getInstance().deserialize(fileString,
                                    ChannelGroup.class);
                            if (group != null && !((ChannelTreeTableModel) channelTable.getTreeTableModel())
                                    .isGroupModeEnabled()) {
                                return;
                            }
                        } catch (Exception e) {
                        }

                        if (showAlerts && !parent.promptObjectMigration(fileString, "channel or group")) {
                            return;
                        }

                        try {
                            importChannel(
                                    ObjectXMLSerializer.getInstance().deserialize(fileString, Channel.class),
                                    showAlerts);
                        } catch (Exception e) {
                            try {
                                importGroup(ObjectXMLSerializer.getInstance().deserialize(fileString,
                                        ChannelGroup.class), showAlerts, !showAlerts);
                            } catch (Exception e2) {
                                if (showAlerts) {
                                    parent.alertThrowable(parent, e,
                                            "Invalid channel or group file:\n" + e.getMessage());
                                }
                            }
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public boolean canMoveChannels(List<Channel> channels, int row) {
            if (row >= 0) {
                TreePath path = channelTable.getPathForRow(row);
                if (path != null) {
                    AbstractChannelTableNode node = (AbstractChannelTableNode) path.getLastPathComponent();

                    if (node.isGroupNode()) {
                        Set<String> currentChannelIds = new HashSet<String>();
                        for (Enumeration<? extends MutableTreeTableNode> channelNodes = node
                                .children(); channelNodes.hasMoreElements();) {
                            currentChannelIds.add(((AbstractChannelTableNode) channelNodes.nextElement())
                                    .getChannelStatus().getChannel().getId());
                        }

                        for (Iterator<Channel> it = channels.iterator(); it.hasNext();) {
                            if (currentChannelIds.contains(it.next().getId())) {
                                it.remove();
                            }
                        }

                        return !channels.isEmpty();
                    }
                }
            }

            return false;
        }

        @Override
        public boolean moveChannels(List<Channel> channels, int row) {
            if (row >= 0) {
                TreePath path = channelTable.getPathForRow(row);
                if (path != null) {
                    AbstractChannelTableNode node = (AbstractChannelTableNode) path.getLastPathComponent();

                    if (node.isGroupNode()) {
                        Set<String> currentChannelIds = new HashSet<String>();
                        for (Enumeration<? extends MutableTreeTableNode> channelNodes = node
                                .children(); channelNodes.hasMoreElements();) {
                            currentChannelIds.add(((AbstractChannelTableNode) channelNodes.nextElement())
                                    .getChannelStatus().getChannel().getId());
                        }

                        for (Iterator<Channel> it = channels.iterator(); it.hasNext();) {
                            if (currentChannelIds.contains(it.next().getId())) {
                                it.remove();
                            }
                        }

                        if (!channels.isEmpty()) {
                            ListSelectionListener[] listeners = ((DefaultListSelectionModel) channelTable
                                    .getSelectionModel()).getListSelectionListeners();
                            for (ListSelectionListener listener : listeners) {
                                channelTable.getSelectionModel().removeListSelectionListener(listener);
                            }

                            try {
                                ChannelTreeTableModel model = (ChannelTreeTableModel) channelTable
                                        .getTreeTableModel();
                                Set<String> channelIds = new HashSet<String>();
                                for (Channel channel : channels) {
                                    model.addChannelToGroup(node, channel.getId());
                                    channelIds.add(channel.getId());
                                }

                                List<TreePath> selectionPaths = new ArrayList<TreePath>();
                                for (Enumeration<? extends MutableTreeTableNode> channelNodes = node
                                        .children(); channelNodes.hasMoreElements();) {
                                    AbstractChannelTableNode channelNode = (AbstractChannelTableNode) channelNodes
                                            .nextElement();
                                    if (channelIds
                                            .contains(channelNode.getChannelStatus().getChannel().getId())) {
                                        selectionPaths.add(new TreePath(
                                                new Object[] { model.getRoot(), node, channelNode }));
                                    }
                                }

                                parent.setSaveEnabled(true);
                                channelTable.expandPath(new TreePath(
                                        new Object[] { channelTable.getTreeTableModel().getRoot(), node }));
                                channelTable.getTreeSelectionModel().setSelectionPaths(
                                        selectionPaths.toArray(new TreePath[selectionPaths.size()]));
                                return true;
                            } finally {
                                for (ListSelectionListener listener : listeners) {
                                    channelTable.getSelectionModel().addListSelectionListener(listener);
                                }
                            }
                        }
                    }
                }
            }

            return false;
        }
    });

    channelTable.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 = channelTable.getPathForRow(row);
            if (path != null && ((AbstractChannelTableNode) path.getLastPathComponent()).isGroupNode()) {
                setIcon(UIConstants.ICON_GROUP);
            }

            return label;
        }
    });
    channelTable.setLeafIcon(UIConstants.ICON_CHANNEL);
    channelTable.setOpenIcon(UIConstants.ICON_GROUP);
    channelTable.setClosedIcon(UIConstants.ICON_GROUP);

    channelTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent evt) {
            channelListSelected(evt);
        }
    });

    // listen for trigger button and double click to edit channel.
    channelTable.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent evt) {
            checkSelectionAndPopupMenu(evt);
        }

        @Override
        public void mouseReleased(MouseEvent evt) {
            checkSelectionAndPopupMenu(evt);
        }

        @Override
        public void mouseClicked(MouseEvent evt) {
            int row = channelTable.rowAtPoint(new Point(evt.getX(), evt.getY()));
            if (row == -1) {
                return;
            }

            if (evt.getClickCount() >= 2 && channelTable.getSelectedRowCount() == 1
                    && channelTable.getSelectedRow() == row) {
                AbstractChannelTableNode node = (AbstractChannelTableNode) channelTable.getPathForRow(row)
                        .getLastPathComponent();
                if (node.isGroupNode()) {
                    doEditGroupDetails();
                } else {
                    doEditChannel();
                }
            }
        }
    });

    // Key Listener trigger for DEL
    channelTable.addKeyListener(new KeyListener() {
        @Override
        public void keyPressed(KeyEvent evt) {
            if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
                if (channelTable.getSelectedModelRows().length == 0) {
                    return;
                }

                boolean allGroups = true;
                boolean allChannels = true;
                for (int row : channelTable.getSelectedModelRows()) {
                    AbstractChannelTableNode node = (AbstractChannelTableNode) channelTable.getPathForRow(row)
                            .getLastPathComponent();
                    if (node.isGroupNode()) {
                        allChannels = false;
                    } else {
                        allGroups = false;
                    }
                }

                if (allChannels) {
                    doDeleteChannel();
                } else if (allGroups) {
                    doDeleteGroup();
                }
            }
        }

        @Override
        public void keyReleased(KeyEvent evt) {
        }

        @Override
        public void keyTyped(KeyEvent evt) {
        }
    });

    // MIRTH-2301
    // Since we are using addHighlighter here instead of using setHighlighters, we need to remove the old ones first.
    channelTable.setHighlighters();

    // Set highlighter.
    if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) {
        Highlighter highlighter = HighlighterFactory.createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR,
                UIConstants.BACKGROUND_COLOR);
        channelTable.addHighlighter(highlighter);
    }

    HighlightPredicate revisionDeltaHighlighterPredicate = new HighlightPredicate() {
        @Override
        public boolean isHighlighted(Component renderer, ComponentAdapter adapter) {
            if (adapter.column == channelTable.convertColumnIndexToView(
                    channelTable.getColumnExt(DEPLOYED_REVISION_DELTA_COLUMN_NAME).getModelIndex())) {
                if (channelTable.getValueAt(adapter.row, adapter.column) != null
                        && ((Integer) channelTable.getValueAt(adapter.row, adapter.column)).intValue() > 0) {
                    return true;
                }

                if (channelStatuses != null) {
                    String channelId = (String) channelTable.getModel()
                            .getValueAt(channelTable.convertRowIndexToModel(adapter.row), ID_COLUMN_NUMBER);
                    ChannelStatus status = channelStatuses.get(channelId);
                    if (status != null && status.isCodeTemplatesChanged()) {
                        return true;
                    }
                }
            }
            return false;
        }
    };
    channelTable.addHighlighter(new ColorHighlighter(revisionDeltaHighlighterPredicate, new Color(255, 204, 0),
            Color.BLACK, new Color(255, 204, 0), Color.BLACK));

    HighlightPredicate lastDeployedHighlighterPredicate = new HighlightPredicate() {
        @Override
        public boolean isHighlighted(Component renderer, ComponentAdapter adapter) {
            if (adapter.column == channelTable.convertColumnIndexToView(
                    channelTable.getColumnExt(LAST_DEPLOYED_COLUMN_NAME).getModelIndex())) {
                Calendar checkAfter = Calendar.getInstance();
                checkAfter.add(Calendar.MINUTE, -2);

                if (channelTable.getValueAt(adapter.row, adapter.column) != null
                        && ((Calendar) channelTable.getValueAt(adapter.row, adapter.column))
                                .after(checkAfter)) {
                    return true;
                }
            }
            return false;
        }
    };
    channelTable.addHighlighter(new ColorHighlighter(lastDeployedHighlighterPredicate, new Color(240, 230, 140),
            Color.BLACK, new Color(240, 230, 140), Color.BLACK));

    channelScrollPane = new JScrollPane(channelTable);
    channelScrollPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));

    filterPanel = new JPanel();
    filterPanel.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(164, 164, 164)));

    tagsFilterButton = new IconButton();
    tagsFilterButton
            .setIcon(new ImageIcon(getClass().getResource("/com/mirth/connect/client/ui/images/wrench.png")));
    tagsFilterButton.setToolTipText("Show Channel Filter");
    tagsFilterButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            tagsFilterButtonActionPerformed();
        }
    });

    tagsLabel = new JLabel();

    ButtonGroup tableModeButtonGroup = new ButtonGroup();

    tableModeGroupsButton = new IconToggleButton(UIConstants.ICON_GROUP);
    tableModeGroupsButton.setToolTipText("Groups");
    tableModeGroupsButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            if (!switchTableMode(true)) {
                tableModeChannelsButton.setSelected(true);
            }
        }
    });
    tableModeButtonGroup.add(tableModeGroupsButton);

    tableModeChannelsButton = new IconToggleButton(UIConstants.ICON_CHANNEL);
    tableModeChannelsButton.setToolTipText("Channels");
    tableModeChannelsButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            if (!switchTableMode(false)) {
                tableModeGroupsButton.setSelected(true);
            }
        }
    });
    tableModeButtonGroup.add(tableModeChannelsButton);

    tabPane = new JTabbedPane();

    splitPane.setTopComponent(topPanel);
    splitPane.setBottomComponent(tabPane);
}

From source file:org.pentaho.reporting.libraries.designtime.swing.table.ArrayCellEditorDialog.java

protected void init() {
    setTitle(Messages.getInstance().getString("ArrayCellEditorDialog.Title"));

    tableModel = new ArrayTableModel();

    table = new PropertyTable();
    table.setModel(tableModel);/*from   w  w w.j av  a 2 s  .c om*/

    paletteListModel = new ArrayTableModel();
    paletteListModel.setEditable(false);

    paletteList = new PropertyTable();
    paletteList.setModel(paletteListModel);
    paletteList.setDragEnabled(true);
    paletteList.setTransferHandler(new ListTransferHandler());
    paletteList.setDropMode(DropMode.ON);
    paletteList.addMouseListener(new DoubleClickHandler(paletteList.getSelectionModel()));

    contentPane = new JPanel();
    contentPane.setLayout(new BorderLayout());
    super.init();
}

From source file:org.ut.biolab.medsavant.client.view.component.GeneSelectionPanel.java

public GeneSelectionPanel(boolean dragSource, boolean dragTarget) {
    super(new Object[0][0], COLUMN_NAMES, COLUMN_CLASSES, new int[0]);
    setFontSize(10);//from ww w  . jav a 2  s  . com
    geneSetFlavor = new DataFlavor(Set.class, "GeneSet");

    getTable().setDragEnabled(dragSource || dragTarget);
    getTable().setDropMode(DropMode.ON);

    exportEnabled = dragSource;
    importEnabled = dragTarget;

    if (dragSource || dragTarget) {
        getTable().setTransferHandler(new GeneSetTransferHandler());
        getTable().setFillsViewportHeight(true);
    }
}