我一直在嘗試從剪貼板傳輸圖像(繪圖)到JTextPane或JTextArea。 附加的代碼正確顯示這些窗口中的圖像,但只要我將光標從窗口移開,圖像就會消失。我該如何修復JText中的圖像...?我的代碼中顯然缺少一些東西。我的網絡搜索沒有產生任何有用的東西。我沒有C#這個問題。我非常感謝你的幫助。圖像不留在Java中的JTextPane
private void jTextPaneStructuresMouseClicked(java.awt.event.MouseEvent evt) {
TransferImage.TransferableImage newImage = new TransferImage.TransferableImage(image);
transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.imageFlavor)) {
try {
image = (Image)transferable.getTransferData(DataFlavor.imageFlavor);
Image cpImage = newImage.getTransferData(DataFlavor.imageFlavor);
jTextPaneStructures.getGraphics().drawImage(cpImage, 0, 0, rootPane);
} catch ( UnsupportedFlavorException | IOException ex) {
Logger.getLogger(WeeklyData.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/* This is what TransferImage.TransferableImage refers to */
public class TransferImage
{
static class TransferableImage implements Transferable
{
/* -- image for transfer */
private final Image image;
/* -- constructor */
public TransferableImage(Image image)
{
this.image = image;
{
}
}
@Override
public DataFlavor[] getTransferDataFlavors()
{
return new DataFlavor[]
{
DataFlavor.imageFlavor
};
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor)
{
return flavor == DataFlavor.imageFlavor;
}
@Override
public Image getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
if (isDataFlavorSupported(flavor))
{
return image;
}
else
{
throw new UnsupportedFlavorException(flavor);
}
}
}
我先前的職位的澄清:圖像立即消失,因爲我把光標離開窗口,然後單擊別處。當我再次單擊JTextPane或JTextArea時,它們再次出現。 – Adam