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!

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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.

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
