DragColorDemo.java Source code

Java tutorial

Introduction

Here is the source code for DragColorDemo.java

Source

/* 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;
    }
}