You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何复制多行文本到剪贴板并逐行粘贴至非Java程序且自动切换输入框

Alright, let's work through this problem. You want to grab multi-line text from your system clipboard, paste each line individually into a non-Java app's text boxes, automatically press Tab to move to the next field after each paste, and repeat the process for additional lines? Got you covered with this practical Java solution using the Robot class for simulating keyboard actions and proper clipboard handling:

Full Code Implementation

Here's the complete code tied to your jButton1 action event (don't forget the necessary imports):

import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
import javax.swing.JOptionPane;

public class YourAppClass { // Replace with your actual class name

    // jButton1 action handler
    private void jButton1ActionPerformed(ActionEvent evt) {
        // Fetch multi-line text from the system clipboard
        String clipboardContent = getTextFromClipboard();
        if (clipboardContent == null || clipboardContent.isBlank()) {
            JOptionPane.showMessageDialog(this, "Clipboard is empty or has no text content!");
            return;
        }

        // Split text into lines (supports both Windows \r\n and Unix \n line endings)
        String[] lines = clipboardContent.split("\\r?\\n");
        if (lines.length == 0) {
            JOptionPane.showMessageDialog(this, "No lines found in the clipboard text!");
            return;
        }

        try {
            Robot robot = new Robot();
            int delay = 600; // Adjust this based on how fast your target app responds

            // Paste each line and switch fields with Tab
            for (int i = 0; i < lines.length; i++) {
                String currentLine = lines[i]; // Keeps original formatting—remove .trim() if you don't want to strip spaces
                copyTextToClipboard(currentLine);

                // Simulate Ctrl+V to paste the line
                robot.keyPress(KeyEvent.VK_CONTROL);
                robot.keyPress(KeyEvent.VK_V);
                robot.keyRelease(KeyEvent.VK_V);
                robot.keyRelease(KeyEvent.VK_CONTROL);
                robot.delay(delay);

                // Press Tab to move to next field (skip after the last line if needed)
                if (i != lines.length - 1) {
                    robot.keyPress(KeyEvent.VK_TAB);
                    robot.keyRelease(KeyEvent.VK_TAB);
                    robot.delay(delay);
                }

                // If you need to handle separate batches (e.g., first 3 lines then another 2), adjust the loop here
                // Example: Break after 3 lines, then run another loop for the next 2
            }

            JOptionPane.showMessageDialog(this, "Pasting finished successfully!");
        } catch (AWTException ex) {
            JOptionPane.showMessageDialog(this, "Error simulating keyboard actions: " + ex.getMessage());
            ex.printStackTrace();
        }
    }

    // Helper method to read text from system clipboard
    private String getTextFromClipboard() {
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable transferable = clipboard.getContents(null);

        if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            try {
                return (String) transferable.getTransferData(DataFlavor.stringFlavor);
            } catch (UnsupportedFlavorException | IOException ex) {
                ex.printStackTrace();
                return null;
            }
        }
        return null;
    }

    // Helper method to copy text to system clipboard
    private void copyTextToClipboard(String text) {
        StringSelection selection = new StringSelection(text);
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(selection, null);
    }
}
Key Tips for Smooth Operation
  • Format Preservation: The code retains your original line formatting by default. If you accidentally added .trim() and don't want to remove leading/trailing spaces, just delete that part.
  • Delay Adjustment: The delay value is critical—if your target app is slow to respond, increase this number (e.g., to 1000 for 1 second). If it's fast, you can lower it to speed things up.
  • Batch Processing: If you need to handle lines in separate groups (like first 3 lines, then another 2), split the loop into two parts. For example:
    // Process first 3 lines
    for (int i = 0; i < Math.min(3, lines.length); i++) {
        // Paste and Tab logic here
    }
    // Process next 2 lines
    for (int i = 3; i < Math.min(5, lines.length); i++) {
        // Paste and Tab logic here
    }
    
  • Window Focus: The Robot class simulates physical keyboard inputs, so make sure the target app's window is active when you run this code. You can add an initial delay (like robot.delay(2000)) if you need time to switch windows manually first.

内容的提问来源于stack exchange,提问作者aditya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:31:56