Drag Color Demo : Drag Drop « Swing JFC « Java






Drag Color Demo

Drag Color Demo
  
/* From http://java.sun.com/docs/books/tutorial/index.html */

/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */

/*
 * DragColorDemo.java is a 1.4 example that requires 
 * the following file:
 *    ColorTransferHandler.java
 */

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
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.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.TransferHandler;

/**
 * Example code that shows any JComponent can be customized to allow dropping of
 * a color.
 */
public class DragColorDemo extends JPanel implements ActionListener {
  JCheckBox toggleForeground;

  ColorTransferHandler colorHandler;

  public DragColorDemo() {
    super(new BorderLayout());
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    JColorChooser chooser = new JColorChooser();
    chooser.setDragEnabled(true);
    add(chooser, BorderLayout.PAGE_START);

    //Create the color transfer handler.
    colorHandler = new ColorTransferHandler();

    //Create a matrix of 9 buttons.
    JPanel buttonPanel = new JPanel(new GridLayout(3, 3));
    for (int i = 0; i < 9; i++) {
      JButton tmp = new JButton("Button " + i);
      tmp.setTransferHandler(colorHandler);
      buttonPanel.add(tmp);
    }
    add(buttonPanel, BorderLayout.CENTER);

    //Create a check box.
    toggleForeground = new JCheckBox("Change the foreground color.");
    toggleForeground.setSelected(true);
    toggleForeground.addActionListener(this);
    JPanel textPanel = new JPanel(new BorderLayout());
    textPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    textPanel.add(toggleForeground, BorderLayout.PAGE_START);

    //Create a label.
    JLabel label = new JLabel(
        "Change the color of any button or this label by dropping a color.");
    label.setTransferHandler(colorHandler);
    label.setOpaque(true); //So the background color can be changed.
    textPanel.add(label, BorderLayout.PAGE_END);
    add(textPanel, BorderLayout.PAGE_END);
  }

  public void actionPerformed(ActionEvent e) {
    colorHandler.setChangesForegroundColor(toggleForeground.isSelected());
  }

  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);

    //Create and set up the window.
    JFrame frame = new JFrame("DragColorDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Create and setup the content pane.
    JComponent newContentPane = new DragColorDemo();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
  }

  public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}

/*
 * ColorTransferHandler.java is used by the 1.4 DragColorDemo.java and
 * DragColorTextFieldDemo examples.
 */

/**
 * An implementation of TransferHandler that adds support for dropping colors.
 * Dropping a color on a component having this TransferHandler changes the
 * foreground or the background of the component to the dropped color, according
 * to the value of the changesForegroundColor property.
 */

class ColorTransferHandler extends TransferHandler {
  //The data type exported from JColorChooser.
  String mimeType = DataFlavor.javaJVMLocalObjectMimeType
      + ";class=java.awt.Color";

  DataFlavor colorFlavor;

  private boolean changesForegroundColor = true;

  ColorTransferHandler() {
    //Try to create a DataFlavor for color.
    try {
      colorFlavor = new DataFlavor(mimeType);
    } catch (ClassNotFoundException e) {
    }
  }

  /**
   * Overridden to import a Color if it is available.
   * getChangesForegroundColor is used to determine whether the foreground or
   * the background color is changed.
   */
  public boolean importData(JComponent c, Transferable t) {
    if (hasColorFlavor(t.getTransferDataFlavors())) {
      try {
        Color col = (Color) t.getTransferData(colorFlavor);
        if (getChangesForegroundColor()) {
          c.setForeground(col);
        } else {
          c.setBackground(col);
        }
        return true;
      } catch (UnsupportedFlavorException ufe) {
        System.out.println("importData: unsupported data flavor");
      } catch (IOException ioe) {
        System.out.println("importData: I/O exception");
      }
    }
    return false;
  }

  /**
   * Does the flavor list have a Color flavor?
   */
  protected boolean hasColorFlavor(DataFlavor[] flavors) {
    if (colorFlavor == null) {
      return false;
    }

    for (int i = 0; i < flavors.length; i++) {
      if (colorFlavor.equals(flavors[i])) {
        return true;
      }
    }
    return false;
  }

  /**
   * Overridden to include a check for a color flavor.
   */
  public boolean canImport(JComponent c, DataFlavor[] flavors) {
    return hasColorFlavor(flavors);
  }

  protected void setChangesForegroundColor(boolean flag) {
    changesForegroundColor = flag;
  }

  protected boolean getChangesForegroundColor() {
    return changesForegroundColor;
  }
}
           
         
    
  








Related examples in the same category

1.Tree: Drag and DropTree: Drag and Drop
2.Drag and dropDrag and drop
3.Adding Image-Dragging Behavior
4.Dropper - show File Drop Target from Drag-n-DropDropper - show File Drop Target from Drag-n-Drop
5.Demonstrate various aspects of Swing data transferDemonstrate various aspects of Swing data transfer
6.File Tree Drop TargetFile Tree Drop Target
7.File Tree Drag SourceFile Tree Drag Source
8.Editor Drop Target 4Editor Drop Target 4
9.Drag Drop Tree ExampleDrag Drop Tree Example
10.JLabel Drag Source JLabel Drag Source
11.Panel Drop TargetPanel Drop Target
12.Editor Drop Target 3Editor Drop Target 3
13.Editor Drop TargetEditor Drop Target
14.Editor Drop Target 2Editor Drop Target 2
15.JTextArea subclass allows TransferableColor objects toJTextArea subclass allows TransferableColor objects to
16.Transferable Color
17.Color Drag Source
18.A sample component for dragging and dropping a collection of files into a tree.A sample component for dragging and dropping a collection of files into a tree.
19.Test of the DragGesture classes and JList to see if weTest of the DragGesture classes and JList to see if we
20.A TransferHandler and JTextArea that will accept any drop at allA TransferHandler and JTextArea that will accept any drop at all
21.Drag and drop: TextAreaDrag and drop: TextArea
22.Drag capabilities: JListDrag capabilities: JList
23.A simple drop tester application for JDK 1.4 Swing componentsA simple drop tester application for JDK 1.4 Swing components
24.Drag and Drop:JList and ListDrag and Drop:JList and List
25.DnD (drag and drop)JTree code DnD (drag and drop)JTree code
26.Drop: TextAreaDrop: TextArea
27.Drag and drop: TextArea 2Drag and drop: TextArea 2
28.Label DnD (Drag and Drop) Label DnD (Drag and Drop)
29.LabelDnD2 allows dropping color onto the foreground of the JLabelLabelDnD2 allows dropping color onto the foreground of the JLabel
30.Drag List Demo Drag List Demo
31.Drag Picture Demo
32.Extended DnD (Drag and Drop) DemoExtended DnD (Drag and Drop) Demo
33.Drag File DemoDrag File Demo
34.Drag Picture Demo 2
35.Drag Color TextField DemoDrag Color TextField Demo
36.BasicDnD (Drag and Drop)BasicDnD (Drag and Drop)
37.Drag and drop icons: use an icon property.
38.Implement drag & drop functionality in your application
39.Detect a drag initiating gesture in your application
40.Making a Component Draggable
41.Getting and Setting Text on the System Clipboard
42.Use drag and drop to reorder a list
43.Create a drag source a drop target and a transferable object.
44.implements DragGestureListener, Transferable
45.Comma separated text will be inserted into two or more rows.
46.TransferHandler subclass wraps another TransferHandler and delegates most of its operations to the wrapped handler
47.Setting text drag in a JTextArea
48.Built-in drag and drop support: utilize a TransferHandler class
49.This program demonstrates drag and drop in an image list.
50.This program demonstrates the basic Swing support for drag and drop.