javafx.scene.input.DataFormat Java Examples

The following examples show how to use javafx.scene.input.DataFormat. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SupportInfoPane.java    From OpenLabeler with Apache License 2.0 6 votes vote down vote up
public SupportInfoPane() {
    FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/SupportInfoPane.fxml"));
    loader.setRoot(this);
    loader.setController(this);

    try {
        loader.load();
    }
    catch (Exception ex) {
        LOG.log(Level.SEVERE, "Unable to load FXML", ex);
    }

    ButtonType copyToClipboard = new ButtonType(bundle.getString("label.copyToClipboard"), ButtonBar.ButtonData.APPLY);
    getButtonTypes().addAll(copyToClipboard, ButtonType.CLOSE);

    final Button btn = (Button) lookupButton(copyToClipboard);
    btn.addEventFilter(ActionEvent.ACTION, event -> {
        final ClipboardContent content = new ClipboardContent();
        content.put(DataFormat.PLAIN_TEXT, text.getText());
        Clipboard.getSystemClipboard().setContent(content);
        event.consume();
    });
}
 
Example #2
Source File: OpenLabelerController.java    From OpenLabeler with Apache License 2.0 6 votes vote down vote up
private void toClipboard(ObjectModel model) {
    Clipboard clipboard = Clipboard.getSystemClipboard();
    Map<DataFormat, Object> content = new HashMap();
    try {
        Marshaller marshaller = jaxbContext.createMarshaller();
        StringWriter writer = new StringWriter();
        // output pretty printed
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        marshaller.marshal(model, writer);
        content.put(DATA_FORMAT_JAXB, writer.toString());
        content.put(DataFormat.PLAIN_TEXT, writer.toString());
        clipboard.setContent(content);
    }
    catch (Exception ex) {
        LOG.log(Level.WARNING, "Unable to put content to clipboard", ex);
    }
}
 
Example #3
Source File: ClipboardActions.java    From RichTextFX with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Transfers the currently selected text to the clipboard,
 * leaving the current selection.
 */
default void copy() {
    IndexRange selection = getSelection();
    if(selection.getLength() > 0) {
        ClipboardContent content = new ClipboardContent();

        content.putString(getSelectedText());

        getStyleCodecs().ifPresent(codecs -> {
            Codec<StyledDocument<PS, SEG, S>> codec = ReadOnlyStyledDocument.codec(codecs._1, codecs._2, getSegOps());
            DataFormat format = dataFormat(codec.getName());
            StyledDocument<PS, SEG, S> doc = subDocument(selection.getStart(), selection.getEnd());
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            try {
                codec.encode(dos, doc);
                content.put(format, os.toByteArray());
            } catch (IOException e) {
                System.err.println("Codec error: Exception in encoding '" + codec.getName() + "':");
                e.printStackTrace();
            }
        });

        Clipboard.getSystemClipboard().setContent(content);
    }
}
 
Example #4
Source File: LyricsTextArea.java    From Quelea with GNU General Public License v3.0 6 votes vote down vote up
public LyricsTextArea() {
    textArea = new InlineCssTextArea();
    ContextMenu contextMenu = new ContextMenu();
    Clipboard systemClipboard = Clipboard.getSystemClipboard();
    MenuItem paste = new MenuItem(LabelGrabber.INSTANCE.getLabel("paste.label"));
    contextMenu.setOnShown(e -> {
        paste.setDisable(!systemClipboard.hasContent(DataFormat.PLAIN_TEXT));
    });

    paste.setOnAction(e -> {
        String clipboardText = systemClipboard.getString();
        textArea.insertText(textArea.getCaretPosition(), clipboardText);
    });

    contextMenu.getItems().add(paste);
    textArea.setContextMenu(contextMenu);
    textArea.textProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
        Platform.runLater(this::refreshStyle);
    });

    textArea.setStyle("-fx-font-family: monospace; -fx-font-size: 10pt;");
    textArea.setUndoManager(UndoManagerFactory.zeroHistorySingleChangeUM(textArea.richChanges()));
    getChildren().add(new VirtualizedScrollPane<>(textArea));
    textArea.getStyleClass().add("text-area");
}
 
Example #5
Source File: PasteFileAction.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
@Override
@FxThread
protected void execute(@Nullable ActionEvent event) {
    super.execute(event);

    var clipboard = Clipboard.getSystemClipboard();
    if (clipboard == null) {
        return;
    }

    List<File> files = unsafeCast(clipboard.getContent(DataFormat.FILES));
    if (files == null || files.isEmpty()) {
        return;
    }

    var currentFile = getElement().getFile();
    var isCut = "cut".equals(clipboard.getContent(EditorUtil.JAVA_PARAM));

    if (isCut) {
        files.forEach(file -> moveFile(currentFile, file.toPath()));
    } else {
        files.forEach(file -> copyFile(currentFile, file.toPath()));
    }

    clipboard.clear();
}
 
Example #6
Source File: ResourcePropertyEditorControl.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
/**
 * Handle drag over.
 */
@FxThread
private void dragOver(@NotNull DragEvent dragEvent) {

    var dragboard = dragEvent.getDragboard();
    var files = ClassUtils.<List<File>>unsafeCast(dragboard.getContent(DataFormat.FILES));

    if (files == null || files.size() != 1) {
        return;
    }

    var file = files.get(0);
    if (!canAccept(file)) {
        return;
    }

    var transferModes = dragboard.getTransferModes();
    var isCopy = transferModes.contains(TransferMode.COPY);

    dragEvent.acceptTransferModes(isCopy ? TransferMode.COPY : TransferMode.MOVE);
    dragEvent.consume();
}
 
Example #7
Source File: ResourcePropertyEditorControl.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
/**
 * Handle dropped files to editor.
 */
@FxThread
private void dragDropped(@NotNull DragEvent dragEvent) {

    var dragboard = dragEvent.getDragboard();
    var files = ClassUtils.<List<File>>unsafeCast(dragboard.getContent(DataFormat.FILES));

    if (files == null || files.size() != 1) {
        return;
    }

    var file = files.get(0);
    if (!canAccept(file)) {
        return;
    }

    handleFile(file);
}
 
Example #8
Source File: SamplePage.java    From javamoney-examples with Apache License 2.0 5 votes vote down vote up
public void initView() {
	try {
		// check if 3d sample and on supported platform
		loadCode();
		// create code view
		WebView webView = getWebView();
		webView.setPrefWidth(300);
		engine.loadContent(htmlCode);
		ToolBar codeToolBar = new ToolBar();
		codeToolBar.setId("code-tool-bar");
		Button copyCodeButton = new Button("Copy Source");
		copyCodeButton.setOnAction(new EventHandler<ActionEvent>() {
			public void handle(ActionEvent actionEvent) {
				Map<DataFormat, Object> clipboardContent = new HashMap<DataFormat, Object>();
				clipboardContent.put(DataFormat.PLAIN_TEXT, rawCode);
				clipboardContent.put(DataFormat.HTML, htmlCode);
				Clipboard.getSystemClipboard().setContent(clipboardContent);
			}
		});
		codeToolBar.getItems().addAll(copyCodeButton);
		setTop(codeToolBar);
		setCenter(webView);
	} catch (Exception e) {
		e.printStackTrace();
		setCenter(new Text("Failed to create sample because of ["
				+ e.getMessage() + "]"));
	}
}
 
Example #9
Source File: ClipboardActions.java    From RichTextFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
static DataFormat dataFormat(String name) {
    DataFormat format = DataFormat.lookupMimeType(name);
    if(format != null) {
        return format;
    } else {
        return new DataFormat(name);
    }
}
 
Example #10
Source File: ClipboardActions.java    From RichTextFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Inserts the content from the clipboard into this text-editing area,
 * replacing the current selection. If there is no selection, the content
 * from the clipboard is inserted at the current caret position.
 */
default void paste() {
    Clipboard clipboard = Clipboard.getSystemClipboard();

    if(getStyleCodecs().isPresent()) {
        Tuple2<Codec<PS>, Codec<StyledSegment<SEG, S>>> codecs = getStyleCodecs().get();
        Codec<StyledDocument<PS, SEG, S>> codec = ReadOnlyStyledDocument.codec(codecs._1, codecs._2, getSegOps());
        DataFormat format = dataFormat(codec.getName());
        if(clipboard.hasContent(format)) {
            byte[] bytes = (byte[]) clipboard.getContent(format);
            ByteArrayInputStream is = new ByteArrayInputStream(bytes);
            DataInputStream dis = new DataInputStream(is);
            StyledDocument<PS, SEG, S> doc = null;
            try {
                doc = codec.decode(dis);
            } catch (IOException e) {
                System.err.println("Codec error: Failed to decode '" + codec.getName() + "':");
                e.printStackTrace();
            }
            if(doc != null) {
                replaceSelection(doc);
                return;
            }
        }
    }

    if (clipboard.hasString()) {
        String text = clipboard.getString();
        if (text != null) {
            replaceSelection(text);
        }
    }
}
 
Example #11
Source File: SelectionTableTest.java    From pdfsam with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
@Category(NoHeadless.class)
public void copy() {
    WaitForAsyncUtils.waitForAsyncFx(2000, () -> Clipboard.getSystemClipboard().clear());
    rightClickOn("temp.pdf");
    clickOn(DefaultI18nContext.getInstance().i18n("Copy to clipboard"));
    WaitForAsyncUtils.waitForAsyncFx(2000, () -> assertFalse(
            StringUtils.isEmpty(Clipboard.getSystemClipboard().getContent(DataFormat.PLAIN_TEXT).toString())));
}
 
Example #12
Source File: ClipboardHelper.java    From openchemlib-js with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static List<DataFormat> getAcceptedFormats(Clipboard clipboard)
{
    Set<DataFormat> formats = clipboard.getContentTypes();
    List<DataFormat> res = new ArrayList<DataFormat>();
    for (DataFormat dataFormat : MoleculeDataFormats.DATA_FORMATS) {
        for (DataFormat f : formats) {
            if (f.equals(dataFormat)) {
                res.add(f);
                break;
            }
        }
    }
    return res;
}
 
Example #13
Source File: ProjectFileTreeView.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private TreeCell<File> createCell(TreeView<File> treeView) {
	FileTreeCell treeCell = new FileTreeCell();
	treeCell.setOnDragDetected(event -> {
		TreeItem<File> draggedItem = treeCell.getTreeItem();
		Dragboard db = treeCell.startDragAndDrop(TransferMode.COPY);

		ClipboardContent content = new ClipboardContent();
		content.putString(draggedItem.getValue().getAbsolutePath());
		content.put(DataFormat.FILES, Collections.singletonList(draggedItem.getValue()));
		db.setContent(content);

		event.consume();
	});
	return treeCell;
}
 
Example #14
Source File: ThreadElement.java    From jstackfx with Apache License 2.0 5 votes vote down vote up
protected void defineContextMenu(final Text text) {
    final MenuItem copy = new MenuItem("Copy");
    copy.setOnAction(event -> {
        Clipboard.getSystemClipboard().setContent(Collections.singletonMap(DataFormat.PLAIN_TEXT, text.getText()));
    });
    final ContextMenu menu = new ContextMenu(copy);

    text.setOnContextMenuRequested(event -> {
        menu.show(text, event.getScreenX(), event.getScreenY());
    });
}
 
Example #15
Source File: SearchBox.java    From mdict-java with GNU General Public License v3.0 5 votes vote down vote up
protected void handleDrop(DragEvent event) {
    Dragboard db = event.getDragboard();
    if(db.hasContent(DataFormat.PLAIN_TEXT)) {
    	String val = (String) db.getContent(DataFormat.PLAIN_TEXT);
    	((TextField)event.getSource()).setText(val);
    	event.consume();
    }
}
 
Example #16
Source File: SearchBox.java    From mdict-java with GNU General Public License v3.0 5 votes vote down vote up
protected void startDrag(MouseEvent event) {
	TextField textBox = ((TextField)event.getSource());
	if(!"".equals(textBox.getSelectedText()) && textBox.getText().equals(textBox.getSelectedText())) {
        Dragboard db = textBox.startDragAndDrop(TransferMode.MOVE);
        snapshotter.setText(textBox.getText());
        db.setDragView(snapshotter.snapshot(null, null));
        ClipboardContent cc = new ClipboardContent();
        cc.put(DataFormat.PLAIN_TEXT, textBox.getSelectedText());
        db.setContent(cc);
        event.consume();
	}
}
 
Example #17
Source File: GroupResource.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean copy(Map<DataFormat, Object> content) {
    @SuppressWarnings("unchecked")
    List<File> files = (List<File>) content.get(DataFormat.FILES);
    if (files == null) {
        files = new ArrayList<>();
        content.put(DataFormat.FILES, files);
    }
    files.add(group.getPath().toFile());
    return true;
}
 
Example #18
Source File: MainFm.java    From tools-ocr with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void copyText(){
    String text = textArea.getSelectedText();
    if (StrUtil.isBlank(text)){
        text = textArea.getText();
    }
    if (StrUtil.isBlank(text)){
        return;
    }
    Map<DataFormat, Object> data = new HashMap<>();
    data.put(DataFormat.PLAIN_TEXT, text);
    Clipboard.getSystemClipboard().setContent(data);
}
 
Example #19
Source File: UIMenuItem.java    From tcMenu with Apache License 2.0 5 votes vote down vote up
public boolean handlePaste() {
    TextField focusedTF = getFocusedTextField();
    if(focusedTF == null) return false;

    Clipboard systemClipboard = Clipboard.getSystemClipboard();
    if (!systemClipboard.hasContent(DataFormat.PLAIN_TEXT)) {
        return true;
    }

    String clipboardText = systemClipboard.getString();

    IndexRange range = focusedTF.getSelection();

    String origText = focusedTF.getText();

    int endPos;
    String updatedText;
    String firstPart = origText.substring(0, range.getStart());
    String lastPart = origText.substring(range.getEnd());

    updatedText = firstPart + clipboardText + lastPart;

    if (range.getStart() == range.getEnd()) {
        endPos = range.getEnd() + clipboardText.length();
    } else {
        endPos = range.getStart() + clipboardText.length();
    }

    focusedTF.setText(updatedText);
    focusedTF.positionCaret(endPos);
    return true;
}
 
Example #20
Source File: GroupEntryResource.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean copy(Map<DataFormat, Object> content) {
    @SuppressWarnings("unchecked")
    List<File> files = (List<File>) content.get(DataFormat.FILES);
    if (files == null) {
        files = new ArrayList<>();
        content.put(DataFormat.FILES, files);
    }
    files.add(entry.getFilePath().toFile());

    return true;
}
 
Example #21
Source File: ResourceView.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
private void copy(ObservableList<TreeItem<Resource>> selectedItems) {
    Clipboard clipboard = Clipboard.getSystemClipboard();
    Map<DataFormat, Object> content = new HashMap<>();
    for (TreeItem<Resource> treeItem : selectedItems) {
        Resource resource = treeItem.getValue();
        if (resource != null) {
            if (!resource.copy(content)) {
                FXUIUtils.showMessageDialog(null, "Clipboard operation failed", "Unhandled resource selection",
                        AlertType.ERROR);
            }
        }
    }
    clipboard.setContent(content);
    clipboardOperation = Operation.COPY;
}
 
Example #22
Source File: FileResource.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean copy(Map<DataFormat, Object> content) {
    @SuppressWarnings("unchecked")
    List<File> files = (List<File>) content.get(DataFormat.FILES);
    if (files == null) {
        files = new ArrayList<>();
        content.put(DataFormat.FILES, files);
    }
    files.add(path.toFile());
    return true;
}
 
Example #23
Source File: FolderResource.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean copy(Map<DataFormat, Object> content) {
    @SuppressWarnings("unchecked")
    List<File> files = (List<File>) content.get(DataFormat.FILES);
    if (files == null) {
        files = new ArrayList<>();
        content.put(DataFormat.FILES, files);
    }
    files.add(path.toFile());
    return true;
}
 
Example #24
Source File: ProjectGroupResource.java    From marathonv5 with Apache License 2.0 4 votes vote down vote up
@Override
public boolean copy(Map<DataFormat, Object> content) {
    // TODO Auto-generated method stub
    return false;
}
 
Example #25
Source File: DummyResource.java    From marathonv5 with Apache License 2.0 4 votes vote down vote up
@Override
public boolean copy(Map<DataFormat, Object> content) {
    return false;
}
 
Example #26
Source File: RunnerActivityController.java    From curly with Apache License 2.0 4 votes vote down vote up
@FXML
void copyClicked(ActionEvent event) {
    Map<DataFormat, Object> reportFormats = new HashMap<>();
    reportFormats.put(DataFormat.HTML, getReportHtml());
    Clipboard.getSystemClipboard().setContent(reportFormats);
}
 
Example #27
Source File: UIMenuItem.java    From tcMenu with Apache License 2.0 4 votes vote down vote up
public boolean canPaste() {
    Clipboard systemClipboard = Clipboard.getSystemClipboard();
    return systemClipboard.hasContent(DataFormat.PLAIN_TEXT);
}
 
Example #28
Source File: ResourceView.java    From sis with Apache License 2.0 4 votes vote down vote up
public ResourceView() {
    pane.setStyle("-fx-background-color: linear-gradient(to bottom right, #aeb7c4, #fafafa);");
    final VBox dragTarget = new VBox();

    root.setExpanded(true);
    final TreeView<Label> resources = new TreeView<>(root);
    resources.setStyle("-fx-background-color: rgba(77, 201, 68, 0.4);");
    resources.setShowRoot(false);

    resources.setOnDragOver(event -> {
        if (event.getGestureSource() != dragTarget && event.getDragboard().hasFiles()) {
            event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
        }
        event.consume();
    });
    resources.setOnDragDropped(event -> {
        Dragboard db = event.getDragboard();
        boolean success = false;

        File firstFile = db.getFiles().get(0);
        if (firstFile.isDirectory()) {
            openDirectory(firstFile);
            success = true;
        } else {
            if (db.hasFiles()) {
                success = true;
            }
            List<?> fileList = (List<?>) db.getContent(DataFormat.FILES); // To open multiple files in one drop.
            for (Object item : fileList) {
                File f = (File) item;
                openFile(f);
            }
        }
        event.setDropCompleted(success);
        event.consume();
    });

    // Link to the temporary varaible see above. This is a temporary part.
    temporarySauv = root.getChildren();
    temporarySauv.addListener((ListChangeListener.Change<? extends TreeItem<Label>> c) -> {
        c.next();
        if (c.wasRemoved()) {
            temp.addAll(c.getRemoved());
        }
    });

    pane.getItems().add(resources);
}
 
Example #29
Source File: WebViewContextMenuTest.java    From oim-fx with MIT License 4 votes vote down vote up
public void paste() {
	final Clipboard clipboard = Clipboard.getSystemClipboard();
	String content = (String) clipboard.getContent(DataFormat.PLAIN_TEXT);
	webView.getEngine().executeScript(String.format("editor.replaceSelection(\"%s\");", content));
}
 
Example #30
Source File: WebViewEventDispatcher.java    From oim-fx with MIT License 4 votes vote down vote up
private void registerEventHandlers() {
	addEventHandler(KeyEvent.ANY,
			event -> {
				processKeyEvent(event);
			});
	addEventHandler(MouseEvent.ANY,
			event -> {
				processMouseEvent(event);
				if (event.isDragDetect() && !page.isDragConfirmed()) {
					// postpone drag recognition:
					// Webkit cannot resolve here is it a drag
					// or selection.
					event.setDragDetect(false);
				}
			});
	addEventHandler(ScrollEvent.SCROLL,
			event -> {
				processScrollEvent(event);
			});
	webView.setOnInputMethodTextChanged(
			event -> {
				processInputMethodEvent(event);
			});

	// Drop target implementation:
	EventHandler<DragEvent> destHandler = event -> {
		try {
			Dragboard db = event.getDragboard();
			LinkedList<String> mimes = new LinkedList<String>();
			LinkedList<String> values = new LinkedList<String>();
			for (DataFormat df : db.getContentTypes()) {
				// TODO: extend to non-string serialized values.
				// Please, look at the native code.
				Object content = db.getContent(df);
				if (content != null) {
					for (String mime : df.getIdentifiers()) {
						mimes.add(mime);
						values.add(content.toString());
					}
				}
			}
			if (!mimes.isEmpty()) {
				int wkDndEventType = getWKDndEventType(event.getEventType());
				int wkDndAction = page.dispatchDragOperation(
						wkDndEventType,
						mimes.toArray(new String[0]), values.toArray(new String[0]),
						(int) event.getX(), (int) event.getY(),
						(int) event.getScreenX(), (int) event.getScreenY(),
						getWKDndAction(db.getTransferModes().toArray(new TransferMode[0])));

				// we cannot accept nothing on drop (we skip FX exception)
				if (!(wkDndEventType == WebPage.DND_DST_DROP && wkDndAction == WK_DND_ACTION_NONE)) {
					event.acceptTransferModes(getFXDndAction(wkDndAction));
				}
				event.consume();
			}
		} catch (SecurityException ex) {
			// Just ignore the exception
			// ex.printStackTrace();
		}
	};
	webView.setOnDragEntered(destHandler);
	webView.setOnDragExited(destHandler);
	webView.setOnDragOver(destHandler);
	webView.setOnDragDropped(destHandler);

	// Drag source implementation:
	webView.setOnDragDetected(event -> {
		if (page.isDragConfirmed()) {
			page.confirmStartDrag();
			event.consume();
		}
	});
	webView.setOnDragDone(event -> {
		page.dispatchDragOperation(
				WebPage.DND_SRC_DROP,
				null, null,
				(int) event.getX(), (int) event.getY(),
				(int) event.getScreenX(), (int) event.getScreenY(),
				getWKDndAction(event.getAcceptedTransferMode()));
		event.consume();
	});

	webView.setInputMethodRequests(getInputMethodClient());
}