【发布时间】:2011-11-05 04:13:05
【问题描述】:
我正在编写一个小型 Java 程序,它应该运行一个将图像复制到系统剪贴板的外部程序(即 Windows 7“截图工具”),等待它完成,将图像从剪贴板保存到磁盘并将 URL(可以从中访问图像)复制到剪贴板。简而言之,它应该:
- 运行外部工具并等待它
- 从剪贴板复制图像
- 将字符串复制到剪贴板
这个,我的程序完全可以做到。但是,我想使用 Swing/AWT 来呈现用户界面。我使用的是系统托盘图标,但为简单起见,它也可以是框架中的 JButton。单击按钮时,应执行上述过程。第一次完成时,它会正常工作。图像被复制,粘贴到磁盘,字符串被复制到剪贴板。然后,第二次单击按钮时,就好像我的程序没有意识到剪贴板已更新,因为它仍然从第一次看到自己的字符串。只有在此之后,我的剪贴板处理类才会失去所有权,实际上,该过程的每一次尝试都会失败。
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main {
private static BufferedImage image; //the image from clipboard to be saved
public static void main(String[] args) throws InterruptedException, IOException {
new GUI();
}
public static void run(String filename) throws IOException, InterruptedException {
CBHandler cbh = new CBHandler();
//run tool, tool will copy an image to system clipboard
Process p = Runtime.getRuntime().exec("C:\\Windows\\system32\\SnippingTool.exe");
p.waitFor();
//copy image from clipboard
image = cbh.getClipboard();
if(image == null) {
System.out.println("No image found in clipboard.");
return;
}
//save image to disk...
//copy file link to clipboard
String link = "http://somedomain.com/" + filename;
cbh.setClipboard(link);
}
}
class CBHandler implements ClipboardOwner {
public BufferedImage getClipboard() {
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
try {
if(t.isDataFlavorSupported(DataFlavor.imageFlavor))
return (BufferedImage) t.getTransferData(DataFlavor.imageFlavor);
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
public void setClipboard(String str) {
StringSelection strsel = new StringSelection(str);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(strsel, this);
}
@Override
public void lostOwnership(Clipboard arg0, Transferable arg1) {
System.out.println("Lost ownership!");
}
}
class GUI extends JFrame {
public GUI() {
JButton button = new JButton("Run");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try {
Main.run("saveFile.png");
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
add(button);
pack();
setVisible(true);
}
}
如果您尝试运行它,请注意在第二次运行时,lostOwnership 方法仅在尝试复制图像后调用。我猜这是我的问题的根源,我不知道它为什么会发生,除了它只在被 Swing 事件触发时发生。任何解决此问题的帮助表示赞赏。
【问题讨论】:
标签: java image swing awt clipboard