Search in sources :

Example 46 with UnsupportedFlavorException

use of java.awt.datatransfer.UnsupportedFlavorException in project java-swing-tips by aterai.

the class TableRowTransferHandler method createTransferable.

// protected TableRowTransferHandler() {
// super();
// localObjectFlavor = new ActivationDataFlavor(
// Object[].class, DataFlavor.javaJVMLocalObjectMimeType, "Array of items");
// }
@Override
protected Transferable createTransferable(JComponent c) {
    getRootGlassPane(c).ifPresent(p -> p.setVisible(true));
    source = c;
    JTable table = (JTable) c;
    DefaultTableModel model = (DefaultTableModel) table.getModel();
    // indices = table.getSelectedRows();
    for (int i : table.getSelectedRows()) {
        indices.add(i);
    }
    // return new DataHandler(transferredObjects, FLAVOR.getMimeType());
    return new Transferable() {

        @Override
        public DataFlavor[] getTransferDataFlavors() {
            return new DataFlavor[] { FLAVOR };
        }

        @Override
        public boolean isDataFlavorSupported(DataFlavor flavor) {
            return Objects.equals(FLAVOR, flavor);
        }

        @SuppressWarnings("JdkObsolete")
        @Override
        public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
            if (isDataFlavorSupported(flavor)) {
                return indices.stream().map(model.getDataVector()::get).collect(Collectors.toList());
            } else {
                throw new UnsupportedFlavorException(flavor);
            }
        }
    };
}
Also used : DefaultTableModel(javax.swing.table.DefaultTableModel) Transferable(java.awt.datatransfer.Transferable) UnsupportedFlavorException(java.awt.datatransfer.UnsupportedFlavorException) DataFlavor(java.awt.datatransfer.DataFlavor)

Example 47 with UnsupportedFlavorException

use of java.awt.datatransfer.UnsupportedFlavorException in project java-swing-tips by aterai.

the class TreeTransferHandler method importData.

@Override
public boolean importData(TransferHandler.TransferSupport info) {
    TransferHandler.DropLocation tdl = info.getDropLocation();
    if (!(tdl instanceof JTable.DropLocation)) {
        return false;
    }
    JTable.DropLocation dl = (JTable.DropLocation) tdl;
    JTable target = (JTable) info.getComponent();
    DefaultTableModel model = (DefaultTableModel) target.getModel();
    int max = model.getRowCount();
    int index = dl.getRow();
    index = index >= 0 && index < max ? index : max;
    addIndex = index;
    try {
        List<?> values = (List<?>) info.getTransferable().getTransferData(FLAVOR);
        addCount = values.size();
        Object[] type = new Object[0];
        for (Object o : values) {
            int row = index++;
            model.insertRow(row, ((List<?>) o).toArray(type));
            target.getSelectionModel().addSelectionInterval(row, row);
        }
        return true;
    } catch (UnsupportedFlavorException | IOException ex) {
        return false;
    }
}
Also used : DefaultTableModel(javax.swing.table.DefaultTableModel) IOException(java.io.IOException) UnsupportedFlavorException(java.awt.datatransfer.UnsupportedFlavorException) ArrayList(java.util.ArrayList) List(java.util.List)

Example 48 with UnsupportedFlavorException

use of java.awt.datatransfer.UnsupportedFlavorException in project cayenne by apache.

the class PasteAction method performAction.

/**
 * Performs pasting items from the system buffer
 */
@Override
public void performAction(ActionEvent e) {
    try {
        Object content = Toolkit.getDefaultToolkit().getSystemClipboard().getData(CayenneTransferable.CAYENNE_FLAVOR);
        Object currentObject = getProjectController().getCurrentObject();
        if (content instanceof DataMap) {
            currentObject = getProjectController().getProject().getRootNode();
        }
        if (content != null && currentObject != null) {
            DataChannelDescriptor domain = (DataChannelDescriptor) getProjectController().getProject().getRootNode();
            DataMap map = getProjectController().getCurrentDataMap();
            UndoableEdit undoableEdit;
            if (content instanceof List) {
                undoableEdit = new PasteCompoundUndoableEdit();
                for (Object o : (List) content) {
                    paste(currentObject, o);
                    undoableEdit.addEdit(new PasteUndoableEdit(domain, map, currentObject, o));
                }
            } else {
                paste(currentObject, content);
                undoableEdit = new PasteUndoableEdit(domain, map, currentObject, content);
            }
            application.getUndoManager().addEdit(undoableEdit);
        }
    } catch (UnsupportedFlavorException ufe) {
    // do nothing
    } catch (Exception ex) {
        ErrorDebugDialog.guiException(ex);
    }
}
Also used : DataChannelDescriptor(org.apache.cayenne.configuration.DataChannelDescriptor) PasteUndoableEdit(org.apache.cayenne.modeler.undo.PasteUndoableEdit) PasteUndoableEdit(org.apache.cayenne.modeler.undo.PasteUndoableEdit) UndoableEdit(javax.swing.undo.UndoableEdit) PasteCompoundUndoableEdit(org.apache.cayenne.modeler.undo.PasteCompoundUndoableEdit) PasteCompoundUndoableEdit(org.apache.cayenne.modeler.undo.PasteCompoundUndoableEdit) List(java.util.List) UnsupportedFlavorException(java.awt.datatransfer.UnsupportedFlavorException) UnsupportedFlavorException(java.awt.datatransfer.UnsupportedFlavorException) DataMap(org.apache.cayenne.map.DataMap)

Example 49 with UnsupportedFlavorException

use of java.awt.datatransfer.UnsupportedFlavorException in project jna by java-native-access.

the class AlphaMaskDemo method run.

public void run() {
    // Must find a graphics configuration with a depth of 32 bits
    GraphicsConfiguration gconfig = WindowUtils.getAlphaCompatibleGraphicsConfiguration();
    frame = new JFrame("Alpha Mask Demo");
    alphaWindow = new JWindow(frame, gconfig);
    MouseInputAdapter handler = new MouseInputAdapter() {

        private Point offset;

        public void mousePressed(MouseEvent e) {
            if (SwingUtilities.isLeftMouseButton(e))
                offset = e.getPoint();
        }

        public void mouseReleased(MouseEvent e) {
            offset = null;
            // hit testing; not sure why it gets disabled
            if (System.getProperty("os.name").startsWith("Windows"))
                update(true, true);
        }

        public void mouseDragged(MouseEvent e) {
            if (offset != null) {
                Window w = (Window) e.getSource();
                Point where = e.getPoint();
                where.translate(-offset.x, -offset.y);
                Point loc = w.getLocationOnScreen();
                loc.translate(where.x, where.y);
                w.setLocation(loc.x, loc.y);
            }
        }
    };
    alphaWindow.addMouseListener(handler);
    alphaWindow.addMouseMotionListener(handler);
    JPanel p = new JPanel(new BorderLayout(8, 8));
    p.setBorder(new EmptyBorder(8, 8, 8, 8));
    p.setTransferHandler(new TransferHandler() {

        private static final long serialVersionUID = 1L;

        public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
            List<DataFlavor> list = Arrays.asList(transferFlavors);
            if (list.contains(URL_FLAVOR) || list.contains(URI_LIST_FLAVOR) || list.contains(DataFlavor.imageFlavor) || list.contains(DataFlavor.javaFileListFlavor)) {
                return true;
            }
            if (DataFlavor.selectBestTextFlavor(transferFlavors) != null) {
                return true;
            }
            System.out.println("No acceptable flavor found in " + Arrays.asList(transferFlavors));
            return false;
        }

        public boolean importData(JComponent comp, Transferable t) {
            try {
                if (t.isDataFlavorSupported(URL_FLAVOR)) {
                    URL url = (URL) t.getTransferData(URL_FLAVOR);
                    setImage(Toolkit.getDefaultToolkit().getImage(url));
                    return true;
                }
                if (t.isDataFlavorSupported(URI_LIST_FLAVOR)) {
                    String s = (String) t.getTransferData(URI_LIST_FLAVOR);
                    String[] uris = s.split("[\r\n]");
                    if (uris.length > 0) {
                        URL url = new URL(uris[0]);
                        setImage(Toolkit.getDefaultToolkit().getImage(url));
                        return true;
                    }
                    return false;
                }
                if (t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
                    Image image = (Image) t.getTransferData(DataFlavor.imageFlavor);
                    setImage(image);
                    return true;
                }
                if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                    List<File> files = (List<File>) t.getTransferData(DataFlavor.javaFileListFlavor);
                    File f = files.get(0);
                    URL url = new URL("file://" + f.toURI().toURL().getPath());
                    Image image = Toolkit.getDefaultToolkit().getImage(url);
                    setImage(image);
                    return true;
                }
                DataFlavor flavor = DataFlavor.selectBestTextFlavor(t.getTransferDataFlavors());
                if (flavor != null) {
                    Reader reader = flavor.getReaderForText(t);
                    char[] buf = new char[512];
                    StringBuilder b = new StringBuilder();
                    int count;
                    // encoding wrong
                    while ((count = reader.read(buf)) > 0) {
                        for (int i = 0; i < count; i++) {
                            if (buf[i] != 0)
                                b.append(buf, i, 1);
                        }
                    }
                    String html = b.toString();
                    Pattern p = Pattern.compile("<img.*src=\"([^\\\"\">]+)\"", Pattern.CANON_EQ | Pattern.UNICODE_CASE);
                    Matcher m = p.matcher(html);
                    if (m.find()) {
                        URL url = new URL(m.group(1));
                        System.out.println("Load image from " + url);
                        Image image = Toolkit.getDefaultToolkit().getImage(url);
                        setImage(image);
                        return true;
                    }
                    System.out.println("Can't parse text: " + html);
                    return false;
                }
                System.out.println("No flavor available: " + Arrays.asList(t.getTransferDataFlavors()));
            } catch (UnsupportedFlavorException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Throwable e) {
                e.printStackTrace();
            }
            return false;
        }
    });
    p.add(new JLabel("<html><center>Drop an image with an alpha channel onto this window<br>" + "You may also adjust the overall transparency with the slider</center></html>"), BorderLayout.NORTH);
    final JSlider slider = new JSlider(0, 255, 255);
    slider.addChangeListener(new ChangeListener() {

        public void stateChanged(ChangeEvent e) {
            int value = slider.getValue();
            setAlpha(value / 255f);
        }
    });
    p.add(slider, BorderLayout.SOUTH);
    frame.getContentPane().add(p);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    centerOnScreen(frame);
    frame.setVisible(true);
    p.addMouseListener(new MouseAdapter() {

        public void mousePressed(MouseEvent e) {
            update();
        }
    });
    try {
        URL url = getClass().getResource("tardis.png");
        if (url != null) {
            setImage(Toolkit.getDefaultToolkit().getImage(url));
        }
    } catch (Exception e) {
    }
}
Also used : JPanel(javax.swing.JPanel) Matcher(java.util.regex.Matcher) Reader(java.io.Reader) Image(java.awt.Image) BufferedImage(java.awt.image.BufferedImage) URL(java.net.URL) GraphicsConfiguration(java.awt.GraphicsConfiguration) DataFlavor(java.awt.datatransfer.DataFlavor) BorderLayout(java.awt.BorderLayout) JFrame(javax.swing.JFrame) JSlider(javax.swing.JSlider) List(java.util.List) ChangeListener(javax.swing.event.ChangeListener) EmptyBorder(javax.swing.border.EmptyBorder) Window(java.awt.Window) JWindow(javax.swing.JWindow) Pattern(java.util.regex.Pattern) MouseEvent(java.awt.event.MouseEvent) JWindow(javax.swing.JWindow) JComponent(javax.swing.JComponent) Transferable(java.awt.datatransfer.Transferable) MouseAdapter(java.awt.event.MouseAdapter) JLabel(javax.swing.JLabel) Point(java.awt.Point) IOException(java.io.IOException) UnsupportedFlavorException(java.awt.datatransfer.UnsupportedFlavorException) UnsupportedFlavorException(java.awt.datatransfer.UnsupportedFlavorException) IOException(java.io.IOException) ChangeEvent(javax.swing.event.ChangeEvent) TransferHandler(javax.swing.TransferHandler) File(java.io.File) MouseInputAdapter(javax.swing.event.MouseInputAdapter)

Example 50 with UnsupportedFlavorException

use of java.awt.datatransfer.UnsupportedFlavorException in project android by JetBrains.

the class NlDropListener method captureDraggedComponents.

@Nullable
private InsertType captureDraggedComponents(@NotNull NlDropEvent event, boolean isPreview) {
    clearDraggedComponents();
    ScreenView screenView = myTree.getScreenView();
    if (screenView == null) {
        return null;
    }
    NlModel model = screenView.getModel();
    if (event.isDataFlavorSupported(ItemTransferable.DESIGNER_FLAVOR)) {
        try {
            myTransferItem = (DnDTransferItem) event.getTransferable().getTransferData(ItemTransferable.DESIGNER_FLAVOR);
            InsertType insertType = determineInsertType(event, isPreview);
            if (insertType.isMove()) {
                myDragged.addAll(keepOnlyAncestors(model.getSelectionModel().getSelection()));
            } else {
                Collection<NlComponent> captured = ApplicationManager.getApplication().runWriteAction((Computable<Collection<NlComponent>>) () -> model.createComponents(screenView, myTransferItem, insertType));
                if (captured != null) {
                    myDragged.addAll(keepOnlyAncestors(captured));
                }
            }
            return insertType;
        } catch (IOException | UnsupportedFlavorException exception) {
            Logger.getInstance(NlDropListener.class).warn(exception);
        }
    }
    return null;
}
Also used : ScreenView(com.android.tools.idea.uibuilder.surface.ScreenView) InsertType(com.android.tools.idea.uibuilder.api.InsertType) IOException(java.io.IOException) UnsupportedFlavorException(java.awt.datatransfer.UnsupportedFlavorException) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

UnsupportedFlavorException (java.awt.datatransfer.UnsupportedFlavorException)106 IOException (java.io.IOException)92 Transferable (java.awt.datatransfer.Transferable)55 List (java.util.List)32 DataFlavor (java.awt.datatransfer.DataFlavor)26 File (java.io.File)25 Point (java.awt.Point)18 ArrayList (java.util.ArrayList)15 Clipboard (java.awt.datatransfer.Clipboard)14 JTree (javax.swing.JTree)9 TreePath (javax.swing.tree.TreePath)9 JComponent (javax.swing.JComponent)7 TransferHandler (javax.swing.TransferHandler)7 DropTargetContext (java.awt.dnd.DropTargetContext)6 URL (java.net.URL)5 DefaultTableModel (javax.swing.table.DefaultTableModel)5 Image (java.awt.Image)4 ActionEvent (java.awt.event.ActionEvent)4 MouseEvent (java.awt.event.MouseEvent)4 NodeInterface (com.sldeditor.common.NodeInterface)3