Commit 8bb2c7df authored by Daniel Vogel's avatar Daniel Vogel

transfer demos

parent fb689418
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class ClipboardDemo extends JPanel implements ClipboardOwner {
private JTextArea textArea;
public ClipboardDemo() {
this.setLayout(new FlowLayout());
// Create a text area for copy and paste tests
// Note that by default, text widgets will support keyboard shortcuts
// for copy/paste
textArea = new JTextArea();
textArea.setMinimumSize(new Dimension(300, 150));
textArea.setPreferredSize(textArea.getMinimumSize());
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
this.add(textArea);
textArea.setText("Lorem ipsum dolor sit amet, semper dissentiet concludaturque an has, " +
"case vivendo vix an. Probo tempor laoreet quo ad.");
// Create copy/cut/paste buttons to support manual copying and pasting
JButton copyButton = new JButton("Copy");
JButton cutButton = new JButton("Cut");
JButton pasteButton = new JButton("Paste");
this.add(copyButton);
this.add(cutButton);
this.add(pasteButton);
// Add action listeners to perform the clipboard operations
copyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doCopy();
}
});
cutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doCut();
}
});
pasteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doPaste();
}
});
}
private void doCopy() {
System.out.println(String.format("COPY: `%s`", textArea.getSelectedText()));
// Get the system clipboard
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
// Create a transferable object encapsulating all the info for the copy
Transferable transferObject = new Transferable() {
private String text = textArea.getSelectedText();
// Returns the copy data
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException ,IOException {
System.out.println(" Transferable.getTransferData as " + flavor);
if (flavor.equals(DataFlavor.stringFlavor)) {
return text;
}
throw new UnsupportedFlavorException(flavor);
}
// Returns the set of data formats we can provide
public DataFlavor[] getTransferDataFlavors() {
System.out.println(" Transferable.getTransferDataFlavors");
return new DataFlavor[] { DataFlavor.stringFlavor };
}
// Indicates whether we can provide data in the specified format
public boolean isDataFlavorSupported(DataFlavor flavor) {
System.out.println(" Transferable.isDataFlavorSupported: " + flavor);
return flavor.equals(DataFlavor.stringFlavor);
}
};
// Now set the contents of the clipboard to our transferable object
// NOTE: The second argument "this" tells the system that this
// object would like to be the owner of the clipboard.
// As such, this object must implement the ClipboardOwner interface
System.out.println("COPY: set system clipboard to Transferable");
cb.setContents(transferObject, this);
}
private void doCut() {
System.out.println("CUT");
// cut is just a copy that also removes data from document
doCopy();
textArea.replaceSelection("");
}
private void doPaste() {
System.out.println("PASTE");
// Grab system clipboard
Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
System.out.println(String.format("PASTE: %d available flavours ... ",
systemClipboard.getAvailableDataFlavors().length));
for (DataFlavor f: systemClipboard.getAvailableDataFlavors()) {
System.out.println(" " + f.getHumanPresentableName() + " " + f.toString());
}
// Check if we can get the data as a string
if (systemClipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)) {
System.out.println("PASTE: DataFlavor.stringFlavor available");
try {
// Grab the data, set our text area to the data
String theText = (String)systemClipboard.getData(DataFlavor.stringFlavor);
textArea.replaceSelection(theText);
System.out.println("PASTE: '" + theText + "'");
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("PASTE: DataFlavor.stringFlavor NOT available");
}
}
// Implement the ClipboardOwner interface
public void lostOwnership(Clipboard clipboard, Transferable contents) {
System.out.println("ClipboardOwner: lost clipboard ownership");
}
public static void main(String[] args) {
JFrame f = new JFrame("Clipboard");
f.getContentPane().add(new ClipboardDemo());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.pack();
f.setVisible(true);
}
}
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.io.File;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.event.MouseEvent;
public class DragAndDropDemo extends JPanel {
private JLabel imageLabel;
private Image image;
public DragAndDropDemo() {
setLayout(new GridLayout());
// drag target
imageLabel = new JLabel("", SwingConstants.CENTER);
imageLabel.setBackground(Color.WHITE);
imageLabel.setOpaque(true);
add(imageLabel);
imageLabel.setTransferHandler(new ImageTransferHandler());
// create a drag gesture
DragGesture dg = new DragGesture();
imageLabel.addMouseListener(dg); // For mouseDragged
imageLabel.addMouseMotionListener(dg); // For mouseReleased
}
// create an image transfer handler
private class ImageTransferHandler extends TransferHandler {
protected Transferable createTransferable(JComponent c) {
System.out.println("Creating Transferable");
return new Transferable() {
private Image img = ((ImageIcon)imageLabel.getIcon()).getImage();
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (flavor.equals(DataFlavor.imageFlavor)) {
System.out.println("getTransferData: " + image);
return this.img;
}
throw new UnsupportedFlavorException(flavor);
}
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { DataFlavor.imageFlavor };
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(DataFlavor.imageFlavor);
}
};
}
public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
public boolean importData(JComponent c, Transferable t) {
System.out.print("importData: ");
JLabel label = (JLabel)c;
imageLabel.setBackground(Color.WHITE);
if (t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
System.out.println("imageFlavour");
try {
// Get the data and set our label's image icon to the new image.
// Save a copy of the image so we can support dragging it out
image = (Image)t.getTransferData(DataFlavor.imageFlavor);
label.setIcon(new ImageIcon(image));
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return true;
} else if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
System.out.println("javaFileListFlavour");
try {
// Get the data and set our label's image icon to the new image.
java.util.List<File> files = (java.util.List<File>) t.getTransferData(DataFlavor.javaFileListFlavor);
File f = files.get(0);
System.out.println("filePath: " + f.getAbsolutePath());
ImageIcon iIcon = new ImageIcon(f.getAbsolutePath());
image = iIcon.getImage();
imageLabel.setIcon(iIcon);
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
System.out.println("rejecting");
return false;
}
public boolean canImport(JComponent c, DataFlavor[] transferFlavors) {
for(int i = 0; i < transferFlavors.length; i++) {
DataFlavor df = transferFlavors[i];
if (df.equals(DataFlavor.imageFlavor) ||
df.equals(DataFlavor.javaFileListFlavor)) {
// feedback to show CAN drag into widget
imageLabel.setBackground(Color.GREEN.brighter());
return true;
}
}
// feedback to show CAN'T drag into widget
imageLabel.setBackground(Color.RED.brighter());
return false;
}
protected void exportDone(JComponent c, Transferable data, int action) {
imageLabel.setBackground(Color.WHITE);
System.out.println("exportDone");
}
}
// A simple recognizer for the drag gesture
// The mouseDragged method is called whenever the mouse button is down and
// the mouse is moving. We only want to initiate drag & drop, for each drag
// gesture. As such, we only take action the first time mouseDragged is called,
// resetting whenever the mouse button is released.
private class DragGesture extends MouseInputAdapter {
private boolean armed = true;
public void mouseDragged(MouseEvent e) {
// Enter the conditional only once, at the start of the drag
if (armed) {
System.out.println("Drag starting");
// Initiate drag and drop
JComponent c = (JComponent)e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
armed = false;
}
}
public void mouseReleased(MouseEvent e) {
// Get ready for the next drag
armed = true;
}
}
public static void main(String[] args) {
JFrame f = new JFrame("DragAndDropDemo");
f.setSize(200, 200);
f.getContentPane().add(new DragAndDropDemo());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setVisible(true);
}
}
# super simple makefile
# call it using 'make NAME=name_of_code_file_without_extension'
# (assumes a .java extension)
NAME = "Main"
all:
@echo "Compiling..."
javac *.java
run: all
@echo "Running..."
java $(NAME)
clean:
rm -rf *.class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
/*
* A DragableImage displays an image and handles drag-and-drop data transfer.
*/
class DragableImage extends JComponent {
private Image image;
/* Create a image using either getImageFromFile or getEmptyImage */
private DragableImage(Image image) {
super();
this.image = image;
this.setFocusable(true);
DragGesture dg = new DragGesture();
this.addMouseListener(dg);
this.addMouseMotionListener(dg);
this.addFocusListener(new HighlightWhenFocusedListener());
}
/* Get an empty image (displays nothing) */
public static DragableImage getEmptyImage() {
return new DragableImage(null);
}
/* Get a image from an image file. */
public static DragableImage getImageFromFile(String path) {
if (path == null) {
return new DragableImage(null);
}
java.net.URL imageURL = TransferDemo.class.getResource(path);
if (imageURL == null) {
System.err.println("Resource not found: " + path);
return new DragableImage(null);
} else {
return new DragableImage(new ImageIcon(imageURL, path).getImage());
}
}
public void setImage(Image image) {
this.image = image;
this.repaint();
}
public Image getImage() {
return this.image;
}
protected void paintComponent(Graphics graphics) {
Graphics g = graphics.create();
// Draw in our entire space, even if isOpaque is false.
g.setColor(Color.WHITE);
g.fillRect(0, 0, image == null ? 125 : image.getWidth(this),
image == null ? 125 : image.getHeight(this));
if (image != null) {
// Draw image at its natural size of 125x125.
g.drawImage(image, 0, 0, this);
}
// Add a border, red if image currently has focus
if (this.isFocusOwner()) {
g.setColor(Color.RED);
} else {
g.setColor(Color.BLACK);
}
g.drawRect(0, 0, image == null ? 125 : image.getWidth(this),
image == null ? 125 : image.getHeight(this));
g.dispose();
}
class HighlightWhenFocusedListener implements FocusListener {
public void focusGained(FocusEvent e) {
// Draw the component with a red border
// indicating that it has focus.
DragableImage.this.repaint();
}
public void focusLost(FocusEvent e) {
// Draw the component with a black border
// indicating that it doesn't have focus.
DragableImage.this.repaint();
}
}
/*---------------------- Drag and Drop support ----------------------*/
// MouseInputAdapter implements and provides default methods for
// both MouseListener and MouseMotionListener interfaces.
class DragGesture extends MouseInputAdapter {
private MouseEvent firstMouseEvent = null;
public void mouseClicked(MouseEvent e) {
// Since the user clicked on us, let's get focus!
requestFocusInWindow();
}
public void mousePressed(MouseEvent e) {
// Don't bother to drag if there is no image.
if (DragableImage.this.image == null) return;
firstMouseEvent = e;
// prevent any other listeners from acting on this event
e.consume();
}
public void mouseReleased(MouseEvent e) {
firstMouseEvent = null;
}
public void mouseDragged(MouseEvent e) {
// Don't bother to drag if the component displays no image.
if (DragableImage.this.image == null) return;
if (firstMouseEvent != null) {
// prevent other listeners from acting on this event
e.consume();
int dx = Math.abs(e.getX() - firstMouseEvent.getX());
int dy = Math.abs(e.getY() - firstMouseEvent.getY());
// Arbitrarily define a 5-pixel shift as the
// official beginning of a drag.
if (dx > 5 || dy > 5) {
// This is a drag, not a click.
// If they are holding down the control key, COPY rather than MOVE
int ctrlMask = InputEvent.CTRL_DOWN_MASK;
int action = ((e.getModifiersEx() & ctrlMask) == ctrlMask) ?
TransferHandler.COPY : TransferHandler.MOVE;
// drag transfer setup
JComponent c = (JComponent)e.getSource();
TransferHandler handler = c.getTransferHandler();
// Tell the transfer handler to initiate the drag.
handler.exportAsDrag(c, firstMouseEvent, action);
firstMouseEvent = null;
}
}
}
}
}
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class ImageGridPanel extends JPanel implements ClipboardOwner {
// Show up to 12 images
private DragableImage[] pics = new DragableImage[12];
// Data to load images into some of the 12 images.
private String[] picNames =
new String[] { "angry", "happy", "worried", "laughing" };
// currently selected image index (-1 if none selected)
private int selectedPic = -1;
// Buttons to make Cut/Copy/Paste visible
private JButton cutButton = new JButton("Cut");
private JButton copyButton = new JButton("Copy");
private JButton pasteButton = new JButton("Paste");
public ImageGridPanel() {
super(new BorderLayout());
this.layoutComponent();
this.registerControllers();
}
private void layoutComponent() {
JPanel images = new JPanel(new GridLayout(3, 4));
for (int i = 0; i < this.pics.length; i++) {
if (i < this.picNames.length) {
this.pics[i] = DragableImage.getImageFromFile("images/"
+ picNames[i] + ".jpg");
} else {
this.pics[i] = DragableImage.getEmptyImage();
}
images.add(this.pics[i]);
}
this.add(images, BorderLayout.CENTER);
this.setPreferredSize(new Dimension(630, 520));
this.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
// out cut/copy/paste buttons into bottom panel
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.LEFT));
buttons.add(cutButton);
buttons.add(copyButton);
buttons.add(pasteButton);
this.add(buttons, BorderLayout.NORTH);
}
private void registerControllers() {
// The transfer handler handles the drag-drop and cut-paste
// infrastructure
ImageTransferHandler picHandler = new ImageTransferHandler();
// This maintains the index of the currently selected image
// (this.selectedPic)
FocusListener fl = new PicFocusListener();
for (int i = 0; i < this.pics.length; i++) {
this.pics[i].setTransferHandler(picHandler);
this.pics[i].addFocusListener(fl);
}
cutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doCut();
}
});
copyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doCopy();
}
});
pasteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doPaste();
}
});
}
// Called when this component no longer owns the clipboard
public void lostOwnership(Clipboard clipboard, Transferable contents) {
System.out.println("Lost clipboard ownership for " + selectedPic);
}
/*
* Copy the currently selected image.
*/
private void doCopy() {
// Get the system clipboard
Clipboard systemClipboard = Toolkit.getDefaultToolkit()
.getSystemClipboard();
// Create a transferable object encapsulating all the info for the copy
Transferable transferObject = new ImageTransferable(pics[selectedPic]);
// Now set the contents of the clipboard to our transferable object
systemClipboard.setContents(transferObject, this);
}
private void doCut() {
this.doCopy(); // most of a cut is the same as a copy
this.pics[selectedPic].setImage(null);
}
private void doPaste() {
// Grab system clipboard
Clipboard systemClipboard = Toolkit.getDefaultToolkit()
.getSystemClipboard();
// For our own edification, print out the data formats available on the
// clipboard
for (DataFlavor flavor : systemClipboard.getAvailableDataFlavors()) {
System.out.println("Flavor: " + flavor);
}