search
HomeJavajavaTutorialJava uses the clipboard to implement data exchange between programs

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();

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

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

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);

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);

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();
……
}

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);
}

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);
}

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();
}
}

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


Statement
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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool