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);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…