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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles