Example usage for javax.swing TransferHandler COPY

List of usage examples for javax.swing TransferHandler COPY

Introduction

In this page you can find the example usage for javax.swing TransferHandler COPY.

Prototype

int COPY

To view the source code for javax.swing TransferHandler COPY.

Click Source Link

Document

An int representing a "copy" transfer action.

Usage

From source file:MainClass.java

public MainClass() {
    Container cp = new Box(BoxLayout.X_AXIS);
    setContentPane(cp);//from   w  w  w  . j a v  a  2  s.  c  o  m
    JPanel firstPanel = new JPanel();
    propertyComboBox = new JComboBox();
    propertyComboBox.addItem("text");
    propertyComboBox.addItem("font");
    propertyComboBox.addItem("background");
    propertyComboBox.addItem("foreground");
    firstPanel.add(propertyComboBox);
    cp.add(firstPanel);
    cp.add(Box.createGlue());

    tf = new JTextField("Hello");
    tf.setForeground(Color.RED);
    tf.setDragEnabled(true);
    cp.add(tf);

    cp.add(Box.createGlue());

    l = new JLabel("Hello");
    l.setBackground(Color.YELLOW);
    cp.add(l);

    cp.add(Box.createGlue());

    JSlider stryder = new JSlider(SwingConstants.VERTICAL);
    stryder.setMinimum(10);
    stryder.setValue(14);
    stryder.setMaximum(72);
    stryder.setMajorTickSpacing(10);
    stryder.setPaintTicks(true);

    cp.add(stryder);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(500, 300);

    setMyTransferHandlers((String) propertyComboBox.getSelectedItem());

    MouseListener myDragListener = new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            JComponent c = (JComponent) e.getSource();
            TransferHandler handler = c.getTransferHandler();
            handler.exportAsDrag(c, e, TransferHandler.COPY);
        }
    };
    l.addMouseListener(myDragListener);

    propertyComboBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ce) {
            JComboBox bx = (JComboBox) ce.getSource();
            String prop = (String) bx.getSelectedItem();
            setMyTransferHandlers(prop);
        }
    });

    tf.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            JTextField jtf = (JTextField) evt.getSource();
            String fontName = jtf.getText();
            Font font = new Font(fontName, Font.BOLD, 18);
            tf.setFont(font);
        }
    });

    stryder.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent evt) {
            JSlider sl = (JSlider) evt.getSource();
            Font oldf = tf.getFont();
            Font newf = oldf.deriveFont((float) sl.getValue());
            tf.setFont(newf);
        }
    });
}

From source file:dnd.ChooseDropActionDemo.java

public ChooseDropActionDemo() {
    super("ChooseDropActionDemo");

    for (int i = 15; i >= 0; i--) {
        from.add(0, "Source item " + i);
    }/*from w  w w .  j a  va  2s  .  co  m*/

    for (int i = 2; i >= 0; i--) {
        copy.add(0, "Target item " + i);
        move.add(0, "Target item " + i);
    }

    JPanel p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
    dragFrom = new JList(from);
    dragFrom.setTransferHandler(new FromTransferHandler());
    dragFrom.setPrototypeCellValue("List Item WWWWWW");
    dragFrom.setDragEnabled(true);
    dragFrom.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JLabel label = new JLabel("Drag from here:");
    label.setAlignmentX(0f);
    p.add(label);
    JScrollPane sp = new JScrollPane(dragFrom);
    sp.setAlignmentX(0f);
    p.add(sp);
    add(p, BorderLayout.WEST);

    JList moveTo = new JList(move);
    moveTo.setTransferHandler(new ToTransferHandler(TransferHandler.COPY));
    moveTo.setDropMode(DropMode.INSERT);
    JList copyTo = new JList(copy);
    copyTo.setTransferHandler(new ToTransferHandler(TransferHandler.MOVE));
    copyTo.setDropMode(DropMode.INSERT);

    p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
    label = new JLabel("Drop to COPY to here:");
    label.setAlignmentX(0f);
    p.add(label);
    sp = new JScrollPane(moveTo);
    sp.setAlignmentX(0f);
    p.add(sp);
    label = new JLabel("Drop to MOVE to here:");
    label.setAlignmentX(0f);
    p.add(label);
    sp = new JScrollPane(copyTo);
    sp.setAlignmentX(0f);
    p.add(sp);
    p.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 0));
    add(p, BorderLayout.CENTER);

    ((JPanel) getContentPane()).setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));

    getContentPane().setPreferredSize(new Dimension(320, 315));
}

From source file:ChooseDropActionDemo.java

public ChooseDropActionDemo() {
    super("ChooseDropActionDemo");

    for (int i = 15; i >= 0; i--) {
        from.add(0, "Source item " + i);
    }// w  w w  .j  ava 2 s. c  o m

    for (int i = 2; i >= 0; i--) {
        copy.add(0, "Target item " + i);
        move.add(0, "Target item " + i);
    }

    JPanel p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
    dragFrom = new JList(from);
    dragFrom.setTransferHandler(new FromTransferHandler());
    dragFrom.setPrototypeCellValue("List Item WWWWWW");
    dragFrom.setDragEnabled(true);
    dragFrom.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JLabel label = new JLabel("Drag from here:");
    label.setAlignmentX(0f);
    p.add(label);
    JScrollPane sp = new JScrollPane(dragFrom);
    sp.setAlignmentX(0f);
    p.add(sp);
    add(p, BorderLayout.WEST);

    JList moveTo = new JList(move);
    moveTo.setTransferHandler(new ToTransferHandler(TransferHandler.COPY));
    moveTo.setDropMode(DropMode.INSERT);
    JList copyTo = new JList(copy);
    copyTo.setTransferHandler(new ToTransferHandler(TransferHandler.MOVE));
    copyTo.setDropMode(DropMode.INSERT);

    p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
    label = new JLabel("Drop to COPY to here:");
    ;
    label.setAlignmentX(0f);
    p.add(label);
    sp = new JScrollPane(moveTo);
    sp.setAlignmentX(0f);
    p.add(sp);
    label = new JLabel("Drop to MOVE to here:");
    label.setAlignmentX(0f);
    p.add(label);
    sp = new JScrollPane(copyTo);
    sp.setAlignmentX(0f);
    p.add(sp);
    p.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 0));
    add(p, BorderLayout.CENTER);

    ((JPanel) getContentPane()).setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));

    getContentPane().setPreferredSize(new Dimension(320, 315));
}

From source file:Transfer.java

public Transfer() {

    // Establish the GUI
    Container cp = new Box(BoxLayout.X_AXIS);
    setContentPane(cp);/*from   ww  w.  j  ava2s. com*/
    JPanel firstPanel = new JPanel();
    propertyComboBox = new JComboBox();
    propertyComboBox.addItem("text");
    propertyComboBox.addItem("font");
    propertyComboBox.addItem("background");
    propertyComboBox.addItem("foreground");
    firstPanel.add(propertyComboBox);
    cp.add(firstPanel);
    cp.add(Box.createGlue());

    tf = new JTextField("Hello");
    tf.setForeground(Color.RED);
    tf.setDragEnabled(true);
    cp.add(tf);

    cp.add(Box.createGlue());

    l = new JLabel("Hello");
    l.setBackground(Color.YELLOW);
    cp.add(l);

    cp.add(Box.createGlue());

    JSlider stryder = new JSlider(SwingConstants.VERTICAL);
    stryder.setMinimum(10);
    stryder.setValue(14);
    stryder.setMaximum(72);
    stryder.setMajorTickSpacing(10);
    stryder.setPaintTicks(true);

    cp.add(stryder);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(500, 300);

    // Add Listeners and Converters
    setMyTransferHandlers((String) propertyComboBox.getSelectedItem());

    // Mousing in the Label starts a Drag.
    MouseListener myDragListener = new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            JComponent c = (JComponent) e.getSource();
            TransferHandler handler = c.getTransferHandler();
            handler.exportAsDrag(c, e, TransferHandler.COPY);
        }
    };
    l.addMouseListener(myDragListener);

    // Selecting in the ComboBox makes that the property that is xfered.
    propertyComboBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ce) {
            JComboBox bx = (JComboBox) ce.getSource();
            String prop = (String) bx.getSelectedItem();
            setMyTransferHandlers(prop);
        }
    });

    // Typing a word and pressing enter in the TextField tries
    // to set that as the font name.
    tf.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            JTextField jtf = (JTextField) evt.getSource();
            String fontName = jtf.getText();
            Font font = new Font(fontName, Font.BOLD, 18);
            tf.setFont(font);
        }
    });

    // Setting the Slider sets that font into the textfield.
    stryder.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent evt) {
            JSlider sl = (JSlider) evt.getSource();
            Font oldf = tf.getFont();
            Font newf = oldf.deriveFont((float) sl.getValue());
            tf.setFont(newf);
        }
    });

}

From source file:com.projity.pm.graphic.spreadsheet.common.transfer.NodeListTransferHandler.java

protected Transferable createTransferable(JComponent c, int action) {
    SpreadSheet spreadSheet = getSpreadSheet(c);
    if (spreadSheet == null)
        return null;
    ArrayList nodes = (ArrayList) spreadSheet.getSelectedNodes().clone();

    ArrayList fields = spreadSheet.getSelectedFields();
    boolean nodeSelection = (fields == null);
    if (fields == null)
        fields = spreadSheet.getSelectableFields();
    if (action == TransferHandler.COPY) {
        if (nodeSelection) {
            SpreadSheet.SpreadSheetAction a = getNodeListCopyAction().getSpreadSheetAction();
            a.execute(nodes);//  ww w .jav  a2  s  .c  o m
        }
        return new NodeListTransferable(nodes, fields, spreadSheet, spreadSheet.getSelectedRows(),
                spreadSheet.getSelectedColumns(), nodeSelection);
    } else if (action == TransferHandler.MOVE) {//cut
        if (nodeSelection) {
            SpreadSheet.SpreadSheetAction a = ((nodeSelection) ? getNodeListCutAction()
                    : getNodeListCopyAction()).getSpreadSheetAction();

            for (Iterator i = nodes.iterator(); i.hasNext();) {
                Node node = (Node) i.next();
                final boolean[] okForAll = new boolean[] { false };
                if (!transformSubprojectBranches(node, spreadSheet.getCache().getModel().getDataFactory(),
                        new Predicate() {
                            public boolean evaluate(Object arg0) {
                                if (okForAll[0])
                                    return true;
                                Node parent = (Node) arg0;
                                boolean r = Alert.okCancel(Messages.getString("Message.subprojectCut"));
                                if (r)
                                    okForAll[0] = true;
                                return r;
                            }

                        }))
                    return null;
            }

            a.execute(nodes);
        }
        return new NodeListTransferable(nodes, fields, spreadSheet, spreadSheet.getSelectedRows(),
                spreadSheet.getSelectedColumns(), nodeSelection);
    } else
        return null;
}

From source file:org.schreibubi.JCombinations.ui.GridChartPanel.java

/**
 * Copy to clipboard//from   w  ww  .  j ava  2s  .  c  o m
 */
public void copyToClipboard() {
    TransferHandler t = getTransferHandler();
    if (t != null)
        t.exportToClipboard(this, Toolkit.getDefaultToolkit().getSystemClipboard(), TransferHandler.COPY);
}

From source file:DragPictureDemo2.java

public void mouseDragged(MouseEvent e) {
    //Don't bother to drag if the component displays no image.
    if (image == null)
        return;/*from  w  w w  .j a v  a  2s.c om*/

    if (firstMouseEvent != null) {
        e.consume();

        //If they are holding down the control key, COPY rather than MOVE
        int ctrlMask = InputEvent.CTRL_DOWN_MASK;
        int action = ((e.getModifiersEx() & ctrlMask) == ctrlMask) ? TransferHandler.COPY
                : TransferHandler.MOVE;

        int dx = Math.abs(e.getX() - firstMouseEvent.getX());
        int dy = Math.abs(e.getY() - firstMouseEvent.getY());
        //Arbitrarily define a 5-pixel shift as the
        //official beginning of a drag.
        if (dx > 5 || dy > 5) {
            //This is a drag, not a click.
            JComponent c = (JComponent) e.getSource();
            TransferHandler handler = c.getTransferHandler();
            //Tell the transfer handler to initiate the drag.
            handler.exportAsDrag(c, firstMouseEvent, action);
            firstMouseEvent = null;
        }
    }
}

From source file:org.fseek.simon.swing.filetree.dnd.FileTransferHandler.java

@Override
public boolean importData(TransferSupport support) {
    Transferable transferable = support.getTransferable();
    // didnt find other solution to get importData known about the action from copy/paste - clipboard
    if (transferable instanceof TransferableProxy) {
        try {/* w  w w .ja va  2  s.  c o  m*/
            TransferableProxy fileTrans = (TransferableProxy) transferable;
            Field privateStringField = TransferableProxy.class.getDeclaredField("transferable");
            privateStringField.setAccessible(true);
            FileTransferable fieldValue = (FileTransferable) privateStringField.get(fileTrans);
            return importData(support, fieldValue.getAction());
        } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
                | SecurityException ex) {
            Logger.getLogger(FileTransferHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    //TODO: Java doesn't support cut operations via Clipboard, so we have to assume COPY if the source is the Clipboard
    int dropAction = TransferHandler.COPY;
    if (support.isDrop()) {
        dropAction = support.getDropAction();
    }
    return importData(support, dropAction);
}

From source file:org.nuclos.client.explorer.ExplorerNode.java

/**
 * @param tree the tree where the action is about to take place.
 * @return the list of possible <code>TreeNodeAction</code>s for this node.
 * These may be shown in the node's context menu.
 * Separators are shown in the menus for <code>null</code> entries.
 *///  w  w  w  . j  a  v a  2 s. co m
public List<TreeNodeAction> getTreeNodeActions(JTree tree) {
    final List<TreeNodeAction> result = new LinkedList<TreeNodeAction>();

    result.add(new RefreshAction(tree));
    final ShowInOwnTabAction actShowInOwnTab = new ShowInOwnTabAction(tree);
    actShowInOwnTab.setEnabled(!this.getTreeNode().needsParent());
    result.add(actShowInOwnTab);

    result.addAll(getExpandCollapseActions(tree));

    final TreeNodeAction exploreractCopy = new ChainedTreeNodeAction(ACTIONCOMMAND_COPY,
            getSpringLocaleDelegate().getMessage("ExplorerNode.4", "Kopieren"), TransferHandler.getCopyAction(),
            tree);
    result.add(exploreractCopy);

    final TreeNodeAction exploreractPaste = new ChainedTreeNodeAction(ACTIONCOMMAND_PASTE,
            getSpringLocaleDelegate().getMessage("ExplorerNode.2", "Einf\u00fcgen"),
            TransferHandler.getPasteAction(), tree);
    result.add(exploreractPaste);

    // enable "copy" action according to the tree's TransferHandler:
    final boolean bCopyEnabled = (tree.getTransferHandler().getSourceActions(tree) & TransferHandler.COPY) != 0;
    exploreractCopy.setEnabled(bCopyEnabled);

    // enable "paste" action according to the tree's TransferHandler:
    // This is hard because TransferHandler.canImport is not called every time the selection changes.
    // Workaround: call canImport anyway to reduce bad paste actions:
    final DataFlavor[] aflavors = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(this)
            .getTransferDataFlavors();
    final boolean bPasteEnabled = tree.getTransferHandler().canImport(tree, aflavors);
    exploreractPaste.setEnabled(bPasteEnabled);

    return result;
}

From source file:org.photovault.swingui.PhotoCollectionThumbView.java

protected void handleDnDDragEvent(MouseEvent e) {
    //Don't bother to drag if no photo is selected
    if (selection.isEmpty()) {
        return;//w w  w  .jav a  2 s .  c o  m
    }

    if (firstMouseEvent != null) {
        log.debug("considering drag");
        e.consume();

        //If they are holding down the control key, COPY rather than MOVE
        int ctrlMask = InputEvent.CTRL_DOWN_MASK;
        int action = e.isControlDown() ? TransferHandler.COPY : TransferHandler.MOVE;

        int dx = Math.abs(e.getX() - firstMouseEvent.getX());
        int dy = Math.abs(e.getY() - firstMouseEvent.getY());
        //Arbitrarily define a 5-pixel shift as the
        //official beginning of a drag.
        if (dx > 5 || dy > 5) {
            log.debug("Start a drag");
            //This is a drag, not a click.
            JComponent c = (JComponent) e.getSource();
            //Tell the transfer handler to initiate the drag.
            TransferHandler handler = c.getTransferHandler();
            handler.exportAsDrag(c, firstMouseEvent, action);
            firstMouseEvent = null;
        }
    }
}