List of usage examples for java.awt.datatransfer DataFlavor stringFlavor
DataFlavor stringFlavor
To view the source code for java.awt.datatransfer DataFlavor stringFlavor.
Click Source Link
representationClass = java.lang.String mimeType = "application/x-java-serialized-object"
From source file:FillViewportHeightDemo.java
public FillViewportHeightDemo() { super("Empty Table DnD Demo"); tableModel = getDefaultTableModel(); table = new JTable(tableModel); table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); table.setDropMode(DropMode.INSERT_ROWS); table.setTransferHandler(new TransferHandler() { public boolean canImport(TransferSupport support) { // for the demo, we'll only support drops (not clipboard paste) if (!support.isDrop()) { return false; }//from ww w .j ava2 s.com // we only import Strings if (!support.isDataFlavorSupported(DataFlavor.stringFlavor)) { return false; } return true; } public boolean importData(TransferSupport support) { // if we can't handle the import, say so if (!canImport(support)) { return false; } // fetch the drop location JTable.DropLocation dl = (JTable.DropLocation) support.getDropLocation(); int row = dl.getRow(); // fetch the data and bail if this fails String data; try { data = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor); } catch (UnsupportedFlavorException e) { return false; } catch (IOException e) { return false; } String[] rowData = data.split(","); tableModel.insertRow(row, rowData); Rectangle rect = table.getCellRect(row, 0, false); if (rect != null) { table.scrollRectToVisible(rect); } // demo stuff - remove for blog model.removeAllElements(); model.insertElementAt(getNextString(count++), 0); // end demo stuff return true; } }); JList dragFrom = new JList(model); dragFrom.setFocusable(false); dragFrom.setPrototypeCellValue(getNextString(100)); model.insertElementAt(getNextString(count++), 0); dragFrom.setDragEnabled(true); dragFrom.setBorder(BorderFactory.createLoweredBevelBorder()); dragFrom.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { if (SwingUtilities.isLeftMouseButton(me) && me.getClickCount() % 2 == 0) { String text = (String) model.getElementAt(0); String[] rowData = text.split(","); tableModel.insertRow(table.getRowCount(), rowData); model.removeAllElements(); model.insertElementAt(getNextString(count++), 0); } } }); 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); JScrollPane sp = new JScrollPane(table); getContentPane().add(sp, BorderLayout.CENTER); fillBox = new JCheckBoxMenuItem("Fill Viewport Height"); fillBox.addActionListener(this); JMenuBar mb = new JMenuBar(); JMenu options = new JMenu("Options"); mb.add(options); setJMenuBar(mb); JMenuItem clear = new JMenuItem("Reset"); clear.addActionListener(this); options.add(clear); options.add(fillBox); getContentPane().setPreferredSize(new Dimension(260, 180)); }
From source file:SerialTransferTest.java
public DataFlavor[] getTransferDataFlavors() { DataFlavor[] flavors = new DataFlavor[2]; Class<?> type = obj.getClass(); String mimeType = "application/x-java-serialized-object;class=" + type.getName(); try {/*from w w w . ja va2 s . c o m*/ flavors[0] = new DataFlavor(mimeType); flavors[1] = DataFlavor.stringFlavor; return flavors; } catch (ClassNotFoundException e) { return new DataFlavor[0]; } }
From source file:SerialTransferTest.java
public boolean isDataFlavorSupported(DataFlavor flavor) { return DataFlavor.stringFlavor.equals(flavor) || "application".equals(flavor.getPrimaryType()) && "x-java-serialized-object".equals(flavor.getSubType()) && flavor.getRepresentationClass().isAssignableFrom(obj.getClass()); }
From source file:dnd.BasicDnD.java
public BasicDnD() { super(new BorderLayout()); JPanel leftPanel = createVerticalBoxPanel(); JPanel rightPanel = createVerticalBoxPanel(); //Create a table model. DefaultTableModel tm = new DefaultTableModel(); tm.addColumn("Column 0"); tm.addColumn("Column 1"); tm.addColumn("Column 2"); tm.addColumn("Column 3"); tm.addRow(new String[] { "Table 00", "Table 01", "Table 02", "Table 03" }); tm.addRow(new String[] { "Table 10", "Table 11", "Table 12", "Table 13" }); tm.addRow(new String[] { "Table 20", "Table 21", "Table 22", "Table 23" }); tm.addRow(new String[] { "Table 30", "Table 31", "Table 32", "Table 33" }); //LEFT COLUMN //Use the table model to create a table. table = new JTable(tm); leftPanel.add(createPanelForComponent(table, "JTable")); //Create a color chooser. colorChooser = new JColorChooser(); leftPanel.add(createPanelForComponent(colorChooser, "JColorChooser")); //RIGHT COLUMN //Create a textfield. textField = new JTextField(30); textField.setText("Favorite foods:\nPizza, Moussaka, Pot roast"); rightPanel.add(createPanelForComponent(textField, "JTextField")); //Create a scrolled text area. textArea = new JTextArea(5, 30); textArea.setText("Favorite shows:\nBuffy, Alias, Angel"); JScrollPane scrollPane = new JScrollPane(textArea); rightPanel.add(createPanelForComponent(scrollPane, "JTextArea")); //Create a list model and a list. DefaultListModel listModel = new DefaultListModel(); listModel.addElement("Martha Washington"); listModel.addElement("Abigail Adams"); listModel.addElement("Martha Randolph"); listModel.addElement("Dolley Madison"); listModel.addElement("Elizabeth Monroe"); listModel.addElement("Louisa Adams"); listModel.addElement("Emily Donelson"); list = new JList(listModel); list.setVisibleRowCount(-1);/* w ww . j av a 2 s. c om*/ list.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); list.setTransferHandler(new TransferHandler() { public boolean canImport(TransferHandler.TransferSupport info) { // we only import Strings if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) { return false; } JList.DropLocation dl = (JList.DropLocation) info.getDropLocation(); if (dl.getIndex() == -1) { return false; } return true; } public boolean importData(TransferHandler.TransferSupport info) { if (!info.isDrop()) { return false; } // Check for String flavor if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) { displayDropLocation("List doesn't accept a drop of this type."); return false; } JList.DropLocation dl = (JList.DropLocation) info.getDropLocation(); DefaultListModel listModel = (DefaultListModel) list.getModel(); int index = dl.getIndex(); boolean insert = dl.isInsert(); // Get the current string under the drop. String value = (String) listModel.getElementAt(index); // Get the string that is being dropped. Transferable t = info.getTransferable(); String data; try { data = (String) t.getTransferData(DataFlavor.stringFlavor); } catch (Exception e) { return false; } // Display a dialog with the drop information. String dropValue = "\"" + data + "\" dropped "; if (dl.isInsert()) { if (dl.getIndex() == 0) { displayDropLocation(dropValue + "at beginning of list"); } else if (dl.getIndex() >= list.getModel().getSize()) { displayDropLocation(dropValue + "at end of list"); } else { String value1 = (String) list.getModel().getElementAt(dl.getIndex() - 1); String value2 = (String) list.getModel().getElementAt(dl.getIndex()); displayDropLocation(dropValue + "between \"" + value1 + "\" and \"" + value2 + "\""); } } else { displayDropLocation(dropValue + "on top of " + "\"" + value + "\""); } /** This is commented out for the basicdemo.html tutorial page. ** If you add this code snippet back and delete the ** "return false;" line, the list will accept drops ** of type string. // Perform the actual import. if (insert) { listModel.add(index, data); } else { listModel.set(index, data); } return true; */ return false; } public int getSourceActions(JComponent c) { return COPY; } protected Transferable createTransferable(JComponent c) { JList list = (JList) c; Object[] values = list.getSelectedValues(); StringBuffer buff = new StringBuffer(); for (int i = 0; i < values.length; i++) { Object val = values[i]; buff.append(val == null ? "" : val.toString()); if (i != values.length - 1) { buff.append("\n"); } } return new StringSelection(buff.toString()); } }); list.setDropMode(DropMode.ON_OR_INSERT); JScrollPane listView = new JScrollPane(list); listView.setPreferredSize(new Dimension(300, 100)); rightPanel.add(createPanelForComponent(listView, "JList")); //Create a tree. DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Mia Familia"); DefaultMutableTreeNode sharon = new DefaultMutableTreeNode("Sharon"); rootNode.add(sharon); DefaultMutableTreeNode maya = new DefaultMutableTreeNode("Maya"); sharon.add(maya); DefaultMutableTreeNode anya = new DefaultMutableTreeNode("Anya"); sharon.add(anya); sharon.add(new DefaultMutableTreeNode("Bongo")); maya.add(new DefaultMutableTreeNode("Muffin")); anya.add(new DefaultMutableTreeNode("Winky")); DefaultTreeModel model = new DefaultTreeModel(rootNode); tree = new JTree(model); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); JScrollPane treeView = new JScrollPane(tree); treeView.setPreferredSize(new Dimension(300, 100)); rightPanel.add(createPanelForComponent(treeView, "JTree")); //Create the toggle button. toggleDnD = new JCheckBox("Turn on Drag and Drop"); toggleDnD.setActionCommand("toggleDnD"); toggleDnD.addActionListener(this); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel); splitPane.setOneTouchExpandable(true); add(splitPane, BorderLayout.CENTER); add(toggleDnD, BorderLayout.PAGE_END); setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); }
From source file:JLabelDragSource.java
public Object getTransferData(DataFlavor fl) { if (!isDataFlavorSupported(fl)) { return null; }//from w w w.j av a 2 s . c o m if (fl.equals(DataFlavor.stringFlavor)) { // String - return the text as a String return label.getText() + " (DataFlavor.stringFlavor)"; } else if (fl.equals(jLabelFlavor)) { // The JLabel itself - just return the label. return label; } else { // Plain text - return an InputStream try { String targetText = label.getText() + " (plain text flavor)"; int length = targetText.length(); ByteArrayOutputStream os = new ByteArrayOutputStream(); OutputStreamWriter w = new OutputStreamWriter(os); w.write(targetText, 0, length); w.flush(); byte[] bytes = os.toByteArray(); w.close(); return new ByteArrayInputStream(bytes); } catch (IOException e) { return null; } } }
From source file:net.pandoragames.far.ui.swing.component.UndoHistoryPopupMenu.java
private void init(SwingConfig config, ComponentRepository componentRepository) { // COPY// w w w.j a va 2 s . co m JMenuItem copy = new JMenuItem(config.getLocalizer().localize("label.copy")); copy.setAccelerator(KeyStroke.getKeyStroke("control C")); copy.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String selection = textComponent.getSelectedText(); if (selection != null) { StringSelection textTransfer = new StringSelection(selection); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(textTransfer, null); } } }); this.add(copy); // PASTE JMenuItem paste = new JMenuItem(config.getLocalizer().localize("label.paste")); paste.setAccelerator(KeyStroke.getKeyStroke("control V")); paste.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { Transferable transfer = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); try { if (transfer != null && transfer.isDataFlavorSupported(DataFlavor.stringFlavor)) { String text = (String) transfer.getTransferData(DataFlavor.stringFlavor); String selected = textComponent.getSelectedText(); if (selected == null) { int insertAt = textComponent.getCaretPosition(); textComponent.getDocument().insertString(insertAt, text, null); } else { int start = textComponent.getSelectionStart(); int end = textComponent.getSelectionEnd(); textComponent.getDocument().remove(start, end - start); textComponent.getDocument().insertString(start, text, null); } } } catch (UnsupportedFlavorException e) { LogFactory.getLog(this.getClass()).error("UnsupportedFlavorException reading from clipboard", e); } catch (IOException iox) { LogFactory.getLog(this.getClass()).error("IOException reading from clipboard", iox); } catch (BadLocationException blx) { LogFactory.getLog(this.getClass()).error("BadLocationException reading from clipboard", blx); } } }); this.add(paste); // UNDO Action undoAction = textComponent.getActionMap().get(UndoHistory.ACTION_KEY_UNDO); if (undoAction != null) { undoAction.putValue(Action.NAME, config.getLocalizer().localize("label.undo")); this.add(undoAction); } // REDO Action redoAction = textComponent.getActionMap().get(UndoHistory.ACTION_KEY_REDO); if (redoAction != null) { redoAction.putValue(Action.NAME, config.getLocalizer().localize("label.redo")); this.add(redoAction); } // PREVIOUS Action prevAction = textComponent.getActionMap().get(UndoHistory.ACTION_KEY_PREVIOUS); if (prevAction != null) { prevAction.putValue(Action.NAME, config.getLocalizer().localize("label.previous")); this.add(prevAction); } // NEXT Action nextAction = textComponent.getActionMap().get(UndoHistory.ACTION_KEY_NEXT); if (nextAction != null) { nextAction.putValue(Action.NAME, config.getLocalizer().localize("label.next")); this.add(nextAction); } }
From source file:Dropper.java
/** * Do the actual import./*from w w w . j a v a 2s . c o m*/ * * @see javax.swing.TransferHandler#importData(javax.swing.JComponent, * java.awt.datatransfer.Transferable) */ public boolean importData(JComponent comp, Transferable t) { DataFlavor[] flavors = t.getTransferDataFlavors(); System.out.println("Trying to import:" + t); System.out.println("... which has " + flavors.length + " flavors."); for (int i = 0; i < flavors.length; i++) { DataFlavor flavor = flavors[i]; try { if (flavor.equals(DataFlavor.javaFileListFlavor)) { System.out.println("importData: FileListFlavor"); List l = (List) t.getTransferData(DataFlavor.javaFileListFlavor); Iterator iter = l.iterator(); while (iter.hasNext()) { File file = (File) iter.next(); System.out.println("GOT FILE: " + file.getCanonicalPath()); // Now do something with the file... } return true; } else if (flavor.equals(DataFlavor.stringFlavor)) { System.out.println("importData: String Flavor"); String fileOrURL = (String) t.getTransferData(flavor); System.out.println("GOT STRING: " + fileOrURL); try { URL url = new URL(fileOrURL); System.out.println("Valid URL: " + url.toString()); // Do something with the contents... return true; } catch (MalformedURLException ex) { System.err.println("Not a valid URL"); return false; } // now do something with the String. } else { System.out.println("importData rejected: " + flavor); // Don't return; try next flavor. } } catch (IOException ex) { System.err.println("IOError getting data: " + ex); } catch (UnsupportedFlavorException e) { System.err.println("Unsupported Flavor: " + e); } } // If you get here, I didn't like the flavor. Toolkit.getDefaultToolkit().beep(); return false; }
From source file:SerialTransferTest.java
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { if (!isDataFlavorSupported(flavor)) throw new UnsupportedFlavorException(flavor); if (DataFlavor.stringFlavor.equals(flavor)) return obj.toString(); return obj;//w w w.j a va2s.co m }
From source file:com.projity.pm.graphic.spreadsheet.common.transfer.NodeListTransferable.java
public NodeListTransferable(ArrayList nodeList, ArrayList fields, SpreadSheet spreadSheet, int[] rows, int[] cols, boolean nodeSelection) { this.nodeSelection = nodeSelection; try {// ww w . j a v a 2 s .c o m nodeListDataFlavor = new DataFlavor(NODE_LIST_MIME_TYPE); } catch (ClassNotFoundException e) { } if (nodeSelection) { flavors = new DataFlavor[] { nodeListDataFlavor, DataFlavor.stringFlavor, DataFlavor.getTextPlainUnicodeFlavor() }; //TODO isRepresentationClassReader(||InputStream)||isFlavorTextType+flavor.getReaderForText() this.nodeList = nodeList; this.fields = fields; } else { flavors = new DataFlavor[] { DataFlavor.stringFlavor, DataFlavor.getTextPlainUnicodeFlavor() }; //TODO isRepresentationClassReader(||InputStream)||isFlavorTextType+flavor.getReaderForText() //sdata=nodeListToString(nodeList,spreadSheet,fields); } flavorSet = new HashSet(); //Collections.addAll(flavorSet,flavors); //jdk 1.5 //for (int i=0;i<flavors.length;i++) flavorSet.add(flavors[i]); CollectionUtils.addAll(flavorSet, flavors); //replaced JDK 1.5 code with this call this.spreadsheet = spreadSheet; this.rows = rows; this.cols = cols; }
From source file:com.hp.alm.ali.idea.ui.editor.field.HTMLAreaField.java
public static void enableCapability(final JTextPane desc, Project project, String value, boolean editable, boolean navigation) { value = removeSmallFont(value);// www .j ava 2 s .c o m HTMLEditorKit kit = new HTMLLetterWrappingEditorKit(); desc.setEditorKit(kit); desc.setDocument(kit.createDefaultDocument()); if (!editable && navigation) { value = NavigationDecorator.explodeHtml(project, value); } desc.setText(value); if (!editable) { desc.setCaret(new NonAdjustingCaret()); } desc.addCaretListener(new BodyLimitCaretListener(desc)); if (editable) { String element = checkElements(desc.getDocument().getDefaultRootElement()); if (element != null) { desc.setToolTipText("Found unsupported element '" + element + "', editing is disabled."); editable = false; } } desc.setEditable(editable); if (editable && SpellCheckerManager.isAvailable() && ApplicationManager.getApplication().getComponent(AliConfiguration.class).spellChecker) { desc.getDocument().addDocumentListener(new SpellCheckDocumentListener(project, desc)); } Font font = UIManager.getFont("Label.font"); String bodyRule = "body { font-family: " + font.getFamily() + "; " + "font-size: " + font.getSize() + "pt; }"; ((HTMLDocument) desc.getDocument()).getStyleSheet().addRule(bodyRule); // AGM uses plain "p" to create lines, we need to avoid excessive spacing this by default creates String paragraphRule = "p { margin-top: 0px; }"; ((HTMLDocument) desc.getDocument()).getStyleSheet().addRule(paragraphRule); Keymap keymap = KeymapManager.getInstance().getActiveKeymap(); new AnAction() { public void actionPerformed(AnActionEvent e) { // following is needed to make copy work in the IDE try { StringSelection selection = new StringSelection(desc.getText(desc.getSelectionStart(), desc.getSelectionEnd() - desc.getSelectionStart())); CopyPasteManager.getInstance().setContents(selection); } catch (Exception ex) { // no clipboard, so what } } }.registerCustomShortcutSet(new CustomShortcutSet(keymap.getShortcuts(IdeActions.ACTION_COPY)), desc); new AnAction() { public void actionPerformed(AnActionEvent e) { // avoid pasting non-supported HTML markup by always converting to plain text Transferable contents = CopyPasteManager.getInstance().getContents(); try { desc.getActionMap().get(DefaultEditorKit.cutAction).actionPerformed(null); desc.getDocument().insertString(desc.getSelectionStart(), (String) contents.getTransferData(DataFlavor.stringFlavor), null); } catch (Exception ex) { // no clipboard, so what } } }.registerCustomShortcutSet(new CustomShortcutSet(keymap.getShortcuts(IdeActions.ACTION_PASTE)), desc); installNavigationShortCuts(desc); }