Home Java javaTutorial Java uses the clipboard to implement data exchange between programs

Java uses the clipboard to implement data exchange between programs

Jan 11, 2017 pm 03:25 PM

The example of this article describes the implementation method of Java using the clipboard to exchange data between programs. In graphical systems, the system clipboard is very important. It is difficult to imagine how a graphical operating system without a clipboard function would be used. This example realizes the data exchange between the Java program and the clipboard of the system. When the "Paste" button is clicked, the Java program obtains the data from the system clipboard and displays it in a JTextArea component; when the "Copy" button is clicked After that, the selected text in the text area will be transferred to the system clipboard.

First you must get an instance reference to the system clipboard. The java.awt.Toolkit class provides the getSystemClipboard() method to return a Clipboard instance; and the Toolkit class provides the static method getDefaultToolkit() to return a Toolkit instance. , so there is no need to create a new Toolkit object. The specific implementation code is as follows:

Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
Copy after login

Here the Clipboard class provides getContents() and setContents() methods to implement data exchange.

Transferable getContents(Object requester);
Void setContents(Transferable contents, ClipboardOwner owner);
Copy after login

The getContents() method here obtains a Transferable object from the system clipboard. The parameter requester represents the data applicant. Generally, this is enough. It is the instance object of this class that requires data. If the required data is text, you can call getTransferData(DataFlavor.stringFlavor) of the Transferable object to obtain it. The implementation code is as follows:

Transferable tr = cb.getContents(this);
String s = (String) tr.getTransferData(DataFlavor.stringFlavor);
Copy after login

setContents() method from the program Pass data to the system clipboard, the parameter contents represents the data, and the parameter owner represents the owner of the clipboard.

StringSelection ss = new StringSelection(this.jTextArea1.getText());
cb.setContents(ss,ss);
Copy after login

The StringSelection class in the above statement represents the selected text.
From the above analysis, in fact, the system clipboard stores a collection of Transferable objects, and the data exchange between the program and the system clipboard is the transfer of Transferable objects. Program code:

1. Create a new Project and name it JClipDemo.
2. Create a new Application and name it JClipDemo; name the main window MainFrame and title it JClipDemo.
3. Add a JTextArea component, two JButtons, and a JPanel component to the design window of the MainFrame class, and place the two JButton components on the JPanel component. Add new property Clipboard cb. The specific code is as follows:

public class MainFrame extends JFrame {
private JPanel contentPane;
private BorderLayout borderLayout1 = new BorderLayout();
//创建新的组件
private JTextArea jTextArea1 = new JTextArea();
private JPanel jPanel1 = new JPanel();
private JButton jButton1 = new JButton();
private JButton jButton2 = new JButton();
//剪贴板实例
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
……
}
Copy after login

4. Write the initialization method jbInit() of the MainFrame class, complete the initial property settings of each component, and add event listeners for the button components. The specific code is as follows:

private void jbInit() throws Exception {
//setIconImage(Toolkit.getDefaultToolkit().createImage(MainFrame.class.getResource("[Your Icon]")));
contentPane = (JPanel) this.getContentPane();
contentPane.setLayout(borderLayout1);
this.setSize(new Dimension(396, 203));
this.setTitle("JClipboardDemo");
jButton1.setFont(new java.awt.Font("Dialog", 0, 14));
jButton1.setText("Copy");
jButton1.addActionListener(new java.awt.event.ActionListener() { //添加事件监听器
public void actionPerformed(ActionEvent e) {
jButton1_actionPerformed(e);
}
});
jButton2.setFont(new java.awt.Font("Dialog", 0, 14));
jButton2.setText("Paste");
jButton2.addActionListener(new java.awt.event.ActionListener() {//添加事件监听器
public void actionPerformed(ActionEvent e) {
jButton2_actionPerformed(e);
}
});
contentPane.add(jTextArea1, BorderLayout.CENTER);
contentPane.add(jPanel1, BorderLayout.SOUTH);
jPanel1.add(jButton1, null);
jPanel1.add(jButton2, null);
}
Copy after login

5. Write the event handling method of the "Copy" button to send data to the system clipboard.

void jButton1_actionPerformed(ActionEvent e) {
StringSelection ss = new StringSelection(this.jTextArea1.getText()); //发送选中文本到系统剪贴板
cb.setContents(ss,ss);
}
Copy after login

6. Write the event handling method of the "Paste" button to obtain data from the system clipboard.

void jButton2_actionPerformed(ActionEvent e) {
try{
Transferable tr = cb.getContents(this); //从系统剪贴板得到一个Transferable 对象
if (tr != null){
String s = (String) tr.getTransferData(DataFlavor.stringFlavor); //从Transferable 对象中得到文本数据
if (s!=null)
this.jTextArea1.insert(s,this.jTextArea1.getCaretPosition()); //在JTextArea 组件中的光标所在处插入文本
}
}catch(Exception err){
err.printStackTrace();
}
}
Copy after login

For more related articles on how Java uses the clipboard to exchange data between programs, please pay attention to the PHP Chinese website!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does Java's classloading mechanism work, including different classloaders and their delegation models? How does Java's classloading mechanism work, including different classloaders and their delegation models? Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

See all articles