程序应该分析剪贴板中存在的5位数字,从1开始。问题是,在复制文本时,我不回答if (clipboardContent.length () == 5)
程序停止工作。
import java.awt.*;
import java.awt.datatransfer.*;
import java.io.IOException;
public class drob implements FlavorListener {
private static Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
public static void main(String[] args) throws InterruptedException {
clipboard.addFlavorListener(new drob());
// fall asleep for 100 seconds, otherwise the program will immediately end
Thread.sleep(100 * 1000);
}
@Override
public void flavorsChanged(FlavorEvent event) {
try {
String clipboardContent = (String) clipboard.getData(DataFlavor.stringFlavor);
handleClipboardContent(clipboardContent);
} catch (UnsupportedFlavorException | IOException e) {
// TODO handle the error
e.printStackTrace();
}
}
private void handleClipboardContent(String clipboardContent) {
// check if the string satisfies condition
// for example, check that the length of the string is five
if (clipboardContent.length() == 5) {
System.out.println(clipboardContent);
}
}
}
答案 0 :(得分:1)
您没有检查clipboardContent
null
。只需改变:
if (clipboardContent.length() == 5) {...}
为:
if (clipboardContent != null && clipboardContent.length() == 5) {...}