Java,剪贴板代码不起作用,
Java, the clipboard code does not work,
程序应分析剪贴板中是否存在以 1 开头的 5 位数字。问题是复制文本时我没有回答 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);
}
}
}
您没有为 null
检查 clipboardContent
。只需更改:
if (clipboardContent.length() == 5) {...}
至:
if (clipboardContent != null && clipboardContent.length() == 5) {...}
程序应分析剪贴板中是否存在以 1 开头的 5 位数字。问题是复制文本时我没有回答 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);
}
}
}
您没有为 null
检查 clipboardContent
。只需更改:
if (clipboardContent.length() == 5) {...}
至:
if (clipboardContent != null && clipboardContent.length() == 5) {...}