-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathImageTransferFrame.java
More file actions
92 lines (83 loc) · 2.51 KB
/
Copy pathImageTransferFrame.java
File metadata and controls
92 lines (83 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package imageTransfer;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.*;
/**
* This frame has an image label and buttons for copying and pasting an image.
*/
class ImageTransferFrame extends JFrame
{
private JLabel label;
private Image image;
private static final int IMAGE_WIDTH = 300;
private static final int IMAGE_HEIGHT = 300;
public ImageTransferFrame()
{
label = new JLabel();
image = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT);
g.setColor(Color.RED);
g.fillOval(IMAGE_WIDTH / 4, IMAGE_WIDTH / 4, IMAGE_WIDTH / 2, IMAGE_HEIGHT / 2);
label.setIcon(new ImageIcon(image));
add(new JScrollPane(label), BorderLayout.CENTER);
JPanel panel = new JPanel();
JButton copyButton = new JButton("Copy");
panel.add(copyButton);
copyButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
copy();
}
});
JButton pasteButton = new JButton("Paste");
panel.add(pasteButton);
pasteButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
paste();
}
});
add(panel, BorderLayout.SOUTH);
pack();
}
/**
* Copies the current image to the system clipboard.
*/
private void copy()
{
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
ImageTransferable selection = new ImageTransferable(image);
clipboard.setContents(selection, null);
}
/**
* Pastes the image from the system clipboard into the image label.
*/
private void paste()
{
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
DataFlavor flavor = DataFlavor.imageFlavor;
if (clipboard.isDataFlavorAvailable(flavor))
{
try
{
image = (Image) clipboard.getData(flavor);
label.setIcon(new ImageIcon(image));
}
catch (UnsupportedFlavorException exception)
{
JOptionPane.showMessageDialog(this, exception);
}
catch (IOException exception)
{
JOptionPane.showMessageDialog(this, exception);
}
}
}
}