Skip to content

Software Development at Program Tom LTD

Place for coding, programming, development and software in general.

Menu
  • Blog
  • PDF Booklets
  • Dev Utils & Content
  • Java Spring Boot Or Web Apps
  • English
    • български
    • English
    • Español
    • Português
    • हिन्दी
    • Русский
    • Deutsch
    • Français
    • Italiano
    • العربية
  • About Us
  • Flutter Apps
Menu
Flutter, JavaScript, Java - How to copy text into the clipboard - Example code

Flutter, JS, Java – How to copy text to the clipboard – Example code

Posted on May 27, 2024 by Toma Velev

The Clipboard is a minimal and independent integration point between all apps in any Operating System to copy text. Having copy functionality saves time of the user to select the desired text. Below you have examples of how to copy text to the clipboard in Flutter, Java Desktop (using AWT), and JavaScript.

Flutter

In Flutter, you can use the `flutter/services.dart` package to interact with the clipboard:

import ‘package:flutter/material.dart’;
import ‘package:flutter/services.dart’;

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text(‘Flutter Clipboard Example’),
),
body: Center(
child: ElevatedButton(
onPressed: () {
Clipboard.setData(ClipboardData(text: “Hello, Clipboard!”));
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(‘Copied to Clipboard’)),
);
},
child: Text(‘Copy Text’),
),
),
),
);
}
}

Web/JavaScript

On the web there are multiple ways to archive copy to clipboard. The more modern API is the Clipbboard: https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API.

<!DOCTYPE html>
<html>
<head>
  <title>Clipboard Example</title>
</head>
<body>
  <button onclick="copyToClipboard()">Copy Text</button>
  <script>
    function copyToClipboard() {
      const text = "Hello, Clipboard!";
      navigator.clipboard.writeText(text).then(() => {
        alert('Copied to Clipboard');
      }).catch(err => {
        console.error('Failed to copy text: ', err);
      });
    }
  </script>
</body>
</html>

There are still old browsers out there that do not support the newer APIs: https://caniuse.com/?search=clipboard. To resolve this – you may use older commands with a temporary object:

var textArea = document.createElement(“textarea”);
textArea.value = $0; document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand(‘copy’);
var msg = successful ? ‘successful’ : ‘unsuccessful’;
console.log(‘Fallback: Copying text command was ‘ + msg);
} catch (err) {
console.error(‘Fallback: Oops, unable to copy’, err);
}
document.body.removeChild(textArea);

Java

I’ve personally used – in Vaadin Web apps – the executeJs API and copy to clipboard using JavaScript. But, generally – Java on the Front-End is in decline. Applet (and adove Flash) technologies are gone. Today you must publish your apps to the app stores. On all platforms – you must comply and adapt to security and privacy policies and permissions. Java just didn’t evolve to the modern UI. 

Using Java’s AWT package, you can interact with the system clipboard.

import java.awt.datatransfer.*;
import java.awt.Toolkit;

public class ClipboardDemo {

public static void main(String[] args) {
String text = “Hello, Clipboard!”;

// Get the system clipboard
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

// Create a StringSelection with the text
StringSelection selection = new StringSelection(text);

// Set the clipboard contents
clipboard.setContents(selection, null);

System.out.println(“Text copied to clipboard: ” + text);
}
}

These examples demonstrate how to copy a simple string (“Hello, Clipboard!”) to the clipboard in Flutter, Java Desktop, and JavaScript. It is small, but also – the most low investment utility to increase user experience. 

  • What are ways to Optimize the backend endpoints in Spring Boot
  • Flutter image flickers
  • Could a Flutter App save a Flag even after uninstall
  • Could iOS flutter app logs be viewed while running in release mode – started after previous closed state
  • 6 Addictive Mobile Game Ideas Inspired by Flappy Bird’s Simplicity

Categories

  • Apps (20)
  • ChatGPT (19)
  • Choosing a Framework (38)
  • Flutter (206)
  • Graphical User Interface (13)
  • Marketing (114)
  • Software Development (270)
  • Spring (43)
  • StartUp (21)
  • Uncategorized (4)
  • Uncategorized (15)
  • Vaadin (14)

Tags

Algorithms (9) crypto (29) flutterdev (39) General (86) Java (7) QR & Bar Codes (3) Software Dev Choices (33) Spring Boot (1) standards (1) Theme (3) User Authentication & Authorization (9) User Experience (10) Utilities (19) WordPress (11)

Product categories

  • All Technologies (83)
    • Flutter Apps (23)
    • GPT (4)
    • Java (38)
    • Native Android (3)
    • PHP (9)
    • Spring (Boot) / Quarkus (35)
    • Utils (15)
    • Vaadin 24+ (27)
    • Vaadin 8 (1)
  • Apps (18)
    • Employees DB (1)
    • Notes (6)
    • Personal Budget (1)
    • Recipes Book (1)
    • Stuff Organizer (1)
    • To-Do (2)
  • PDF Books (3)
  • Source Code Generators (8)

Recent Posts

  • What are ways to Optimize the backend endpoints in Spring Boot
  • Flutter image flickers
  • Could a Flutter App save a Flag even after uninstall
  • Could iOS flutter app logs be viewed while running in release mode – started after previous closed state
  • 6 Addictive Mobile Game Ideas Inspired by Flappy Bird’s Simplicity

Post Categories

  • Apps (20)
  • ChatGPT (19)
  • Choosing a Framework (38)
  • Flutter (206)
  • Graphical User Interface (13)
  • Marketing (114)
  • Software Development (270)
  • Spring (43)
  • StartUp (21)
  • Uncategorized (4)
  • Uncategorized (15)
  • Vaadin (14)