在更改剪贴板内容时调用方法 [英] calling a method when content of clipboard is changed

查看:115
本文介绍了在更改剪贴板内容时调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个应该显示剪贴板内容的桌面应用程序(如果它是一个字符串)。我已经完成了一个构造函数,并且它运行良好,现在我只想在文本被复制到操作系统中的剪贴板时调用类似的方法。我是新手,所以任何帮助将不胜感激!有事告诉我,我应该以某种方式使用中断...

I'm trying to make a little desktop app that should show the contents of the clipboard (if it is a string). I have done a constructor that does that and it works well, now I just want to make a call to a similar method whenever a text is copied into the clipboard in the OS. I'm quite new to this so any help would be appreciated! Something tells me I should use interrupts in some way...

package pasty;

import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class PastyFrame implements KeyListener {

    String currentClipboardString;
    JLabel clipboardLabel = new JLabel();

    public PastyFrame() {
        JFrame frame = new JFrame();
        frame.setVisible(true);

        try {
            currentClipboardString = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
        } catch (UnsupportedFlavorException | IOException ex) {
            Logger.getLogger(PastyFrame.class.getName()).log(Level.SEVERE, null, ex);

            currentClipboardString = "";
        }
        if (currentClipboardString.isEmpty()) {
            currentClipboardString = "The clipboard is empty";
        }
        frame.setSize(400, 100);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setLayout(new FlowLayout());


        clipboardLabel.setText(currentClipboardString);
        frame.add(clipboardLabel);
}


推荐答案

你可以打电话给剪贴板。 addFlavorListener 从操作系统侦听剪贴板更新:

You can call Clipboard.addFlavorListener to listen for clipboard updates from the OS:

Toolkit.getDefaultToolkit().getSystemClipboard().addFlavorListener(new FlavorListener() { 
   @Override 
   public void flavorsChanged(FlavorEvent e) {

      System.out.println("ClipBoard UPDATED: " + e.getSource() + " " + e.toString());
   } 
}); 






一些附注:


  • 要启动您的应用程序,请考虑使用初始主题

  • 调用 JFrame.pack 进行设置框架大小。

  • 主要绑定优先于 KeyListeners ,用于在Swing中映射 KeyEvents

  • For launching your application, consider using initial threads.
  • Call JFrame.pack to set the frame size.
  • Key Bindings are preferred over KeyListeners for mapping KeyEvents in Swing.

这篇关于在更改剪贴板内容时调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆