Java/2D Graphics GUI/Icon

Материал из Java эксперт
Версия от 06:54, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

An empty icon with arbitrary width and height.

  
/**
 * @PROJECT.FULLNAME@ @VERSION@ License.
 *
 * Copyright @YEAR@ L2FProd.ru
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.awt.ruponent;
import java.awt.Graphics;
import javax.swing.Icon;
/**
 * An empty icon with arbitrary width and height.
 */
public final class EmptyIcon implements Icon {
  private int width;
  private int height;
  
  public EmptyIcon() {
    this(0, 0);
  }
  
  public EmptyIcon(int width, int height) {
    this.width = width;
    this.height = height;
  }
  public int getIconHeight() {
    return height;
  }
  public int getIconWidth() {
    return width;
  }
  public void paintIcon(Component c, Graphics g, int x, int y) {
  }
}



An icon for painting a square swatch of a specified Color.

  
/*
 *  ColorSwatch.java
 *  2007-03-03
 */
//cb.aloe.decor;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Graphics;
import javax.swing.Icon;
/**
 * An icon for painting a square swatch of a specified Color.
 * 
 * @author Christopher Bach
 */
public class ColorSwatch implements Icon {
  private Color ourSwatchColor = Color.white;
  private Color ourBorderColor = Color.black;
  private boolean ourBorderPainted = true;
  private boolean ourSwatchIsMultiColor = false;
  private boolean ourSwatchIsVoid = false;
  private int ourSwatchSize = 14;
  /**
   * Creates a standard 14 x 14 swatch with a black border and white background.
   */
  public ColorSwatch() {
  }
  /**
   * Creates a swatch of the specified size with a black border and white
   * background.
   */
  public ColorSwatch(int size) {
    setSwatchSize(size);
  }
  /**
   * Creates a swatch of the specified size with a black border and white
   * background and determines whether or n not the border should be painted.
   */
  public ColorSwatch(int size, boolean borderPainted) {
    setSwatchSize(size);
    setBorderPainted(borderPainted);
  }
  /**
   * 
   */
  public ColorSwatch(Color color) {
    setColor(color);
  }
  /**
   * 
   */
  public ColorSwatch(int size, Color color) {
    setSwatchSize(size);
    setColor(color);
  }
  /**
   * 
   */
  public ColorSwatch(int size, Color color, Color borderColor) {
    setSwatchSize(size);
    setColor(color);
    setBorderColor(borderColor);
    setBorderPainted(true);
  }
  /**
   * Sets the size of this swatch.
   */
  public void setSwatchSize(int size) {
    if (size > 0)
      ourSwatchSize = size;
    else
      ourSwatchSize = 14;
  }
  /**
   * Returns the size of this swatch.
   */
  public int getSwatchSize() {
    return ourSwatchSize;
  }
  /**
   * Determines whether or not this swatch"s border should be painted.
   */
  public void setBorderPainted(boolean borderPainted) {
    ourBorderPainted = borderPainted;
  }
  /**
   * Returns whether or not this swatch"s border is painted.
   */
  public boolean isBorderPainted() {
    return ourBorderPainted;
  }
  /**
   * Sets the color of this swatch"s border.
   */
  public void setBorderColor(Color color) {
    ourBorderColor = color;
  }
  /**
   * Returns the color of this swatch"s border.
   */
  public Color getBorderColor() {
    return ourBorderColor;
  }
  /**
   * Sets the color that this swatch represents.
   */
  public void setColor(Color color) {
    ourSwatchIsMultiColor = false;
    ourSwatchColor = color;
  }
  /**
   * Returns the color that this swatch represents.
   */
  public Color getColor() {
    return ourSwatchColor;
  }
  /**
   * Sets this swatch to represent more than one color.
   */
  public void setMultiColor() {
    ourSwatchIsMultiColor = true;
  }
  /**
   * Returns whether or not this swatch represents more than one color.
   */
  public boolean isMultiColor() {
    return ourSwatchIsMultiColor;
  }
  /**
   * Determines whether or not this swatch is void. If the swatch is void, it
   * will not be painted at all.
   */
  public void setVoid(boolean isVoid) {
    // When true, this icon will not be painted at all.
    ourSwatchIsVoid = isVoid;
  }
  /**
   * Returns whether this swatch is void. If the swatch is void, it will not be
   * painted at all.
   */
  public boolean isVoid() {
    return ourSwatchIsVoid;
  }
  // // Icon implementation ////
  /**
   * Returns the width of this Icon.
   */
  public int getIconWidth() {
    return ourSwatchSize;
  }
  /**
   * Returns the height of this Icon.
   */
  public int getIconHeight() {
    return ourSwatchSize;
  }
  /**
   * Paints this Icon into the provided graphics context.
   */
  public void paintIcon(Component c, Graphics g, int x, int y) {
    if (ourSwatchIsVoid)
      return;
    Color oldColor = g.getColor();
    if (ourSwatchIsMultiColor) {
      g.setColor(Color.white);
      g.fillRect(x, y, ourSwatchSize, ourSwatchSize);
      g.setColor(ourBorderColor);
      for (int i = 0; i < ourSwatchSize; i += 2) {
        g.drawLine(x + i, y, x + i, y + ourSwatchSize);
      }
    }
    else if (ourSwatchColor != null) {
      g.setColor(ourSwatchColor);
      g.fillRect(x, y, ourSwatchSize, ourSwatchSize);
    }
    else {
      g.setColor(Color.white);
      g.fillRect(x, y, ourSwatchSize, ourSwatchSize);
      g.setColor(ourBorderColor);
      g.drawLine(x, y, x + ourSwatchSize, y + ourSwatchSize);
      g.drawLine(x, y + ourSwatchSize, x + ourSwatchSize, y);
    }
    if (ourBorderPainted) {
      g.setColor(ourBorderColor);
      g.drawRect(x, y, ourSwatchSize, ourSwatchSize);
    }
    g.setColor(oldColor);
  }
}



Arrow Icon

    
/*
 * jMemorize - Learning made easy (and fun) - A Leitner flashcards tool
 * Copyright(C) 2004-2008 Riad Djemili and contributors
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 1, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Graphics;
import javax.swing.Icon;
/**
 * @author djemili
 */
public class Arrow implements Icon
{
    private boolean descending;
    private int     size;
    public Arrow(boolean descending, int size)
    {
        this.descending = descending;
        this.size = size;
    }
    public void paintIcon(Component c, Graphics g, int x, int y)
    {
        Color color = c == null ? Color.GRAY : c.getBackground();
        
        int dx = (int)(size / 2);
        int dy = descending ? dx : -dx;
        
        // Align icon (roughly) with font baseline.
        y = y + 5 * size / 6 + (descending ? -dy : 0);
        
        g.translate(x, y);
        g.setColor(Color.GRAY);
        g.fillPolygon(new int[]{dx/2, dx, 0}, new int[]{dy, 0, 0}, 3);
        g.translate(-x, -y);
        g.setColor(color);
    }
    public int getIconWidth()
    {
        return size;
    }
    public int getIconHeight()
    {
        return size;
    }
}



A simple application to test the functionality of the OvalIcon class

     
import java.awt.ruponent;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class TestOval {
  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JLabel label1 = new JLabel(new OvalIcon(20, 50));
    JLabel label2 = new JLabel(new OvalIcon(50, 20));
    JLabel label3 = new JLabel("Round!", new OvalIcon(60, 60),
        SwingConstants.CENTER);
    label3.setHorizontalTextPosition(SwingConstants.CENTER);
    Container c = f.getContentPane();
    c.setLayout(new FlowLayout());
    c.add(label1);
    c.add(label2);
    c.add(label3);
    f.pack();
    f.setVisible(true);
  }
}
class OvalIcon implements Icon {
  private int width, height;
  public OvalIcon(int w, int h) {
    width = w;
    height = h;
  }
  public void paintIcon(Component c, Graphics g, int x, int y) {
    g.drawOval(x, y, width - 1, height - 1);
  }
  public int getIconWidth() {
    return width;
  }
  public int getIconHeight() {
    return height;
  }
}



Calendar Page icons with Weekday, Day and Month

     
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.text.DecimalFormat;
import java.util.Calendar;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
/**
 * Display one of those standard Calendar Page icons with Weekday, Day and
 * Month. Can be used as the Icon in a JButton. Can include or exclude an
 * updating Clock at the top (invoke constructor with value of true to include).
 * However, it should be excluded when using as an Icon, and true when using as
 * a Component.
 * 
 * @author Ian Darwin, http://www.darwinsys.ru
 * @version $Id: CalIcon.java,v 1.3 2003/05/29 18:06:31 ian Exp $
 */
public class CalIcon extends JComponent implements Icon {
  /** The size shalle be 64x64. */
  protected final int SIZE = 64;
  protected final Dimension d = new Dimension(SIZE, SIZE);
  /** The size of the inner white box */
  protected final int RBW = 40, RBH = 40;
  /** The x location of the inner box */
  protected final int RBX;
  /** The y location of the inner box */
  protected final int RBY;
  /** Our Calendar */
  protected Calendar myCal;
  /** True if user wants the time shown */
  protected boolean showTime = true;
  /** The Clock to show the time, if showTime */
  protected Clock clock;
  /** Font for displaying the time */
  protected Font dayNumbFont;
  /** FontMetrics for displaying the time */
  protected FontMetrics dayNumbFM;
  /** Font for displaying the time */
  protected Font dayNameFont;
  /** FontMetrics for displaying the time */
  protected FontMetrics dayNameFM;
  /** Font for displaying the time */
  protected Font monNameFont;
  /** FontMetrics for displaying the time */
  protected FontMetrics monNameFM;
  /** Construct the object with default arguments */
  public CalIcon(boolean showT) {
    this(Calendar.getInstance(), showT);
  }
  /** Construct the object with a Calendar object */
  public CalIcon(Calendar c, boolean showT) {
    super();
    showTime = showT;
    myCal = c;
    setLayout(null); // we don"t need another layout, ...
    if (showTime) {
      // System.err.println("Constructing and adding Clock");
      clock = new Clock();
      add(clock);
      clock.setBounds(0, 2, SIZE, 10);
      // clock.setBackground(Color.black);
      // clock.setForeground(Color.green);
      RBY = d.height - (RBH + (showTime ? 12 : 0) / 2);
    } else {
      RBY = 6;
    }
    RBX = 12; // raised box x offset
    // System.err.println("RBX, RBY = " + RBX + "," + RBY);
    dayNumbFont = new Font("Serif", Font.BOLD, 20);
    dayNumbFM = getFontMetrics(dayNumbFont);
    dayNameFont = new Font("SansSerif", Font.PLAIN, 10);
    dayNameFM = getFontMetrics(dayNameFont);
    monNameFont = new Font("SansSerif", Font.ITALIC, 10);
    monNameFM = getFontMetrics(monNameFont);
  }
  /** Days of the week */
  public String[] days = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
  public String[] mons = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL",
      "AUG", "SEP", "OCT", "NOV", "DEC", };
  /**
   * Paint: draw the calendar page in the JComponent. Delegates most work to
   * paintIcon().
   */
  public void paint(Graphics g) {
    paintIcon(this, g, 0, 0);
  }
  /** paintIcon: draw the calendar page. */
  public void paintIcon(Component c, Graphics g, int x, int y) {
    // Allow clock to get painted (voodoo magic)
    if (showTime)
      super.paint(g);
    // Outline it.
    g.setColor(Color.black);
    g.draw3DRect(x, y, d.width - 2, d.height - 2, true);
    // Show the date: First, a white page with a drop shadow.
    g.setColor(Color.gray);
    g.fillRect(x + RBX + 3, y + RBY + 3, RBW, RBH);
    g.setColor(Color.white);
    g.fillRect(x + RBX, y + RBY, RBW, RBH);
    // g.setColor(getForeground());
    g.setColor(Color.black);
    String s = days[myCal.get(Calendar.DAY_OF_WEEK) - 1];
    g.setFont(dayNameFont);
    int w = dayNameFM.stringWidth(s);
    g.drawString(s, x + RBX + ((RBW - w) / 2), y + RBY + 10);
    s = Integer.toString(myCal.get(Calendar.DAY_OF_MONTH));
    g.setFont(dayNumbFont);
    w = dayNumbFM.stringWidth(s);
    g.drawString(s, x + RBX + ((RBW - w) / 2), y + RBY + 25);
    s = mons[myCal.get(Calendar.MONTH)];
    g.setFont(monNameFont);
    w = monNameFM.stringWidth(s);
    g.drawString(s, x + RBX + ((RBW - w) / 2), y + RBY + 35);
  }
  public int getIconWidth() {
    return SIZE;
  }
  public int getIconHeight() {
    return SIZE;
  }
  public Dimension getPreferredSize() {
    return d;
  }
  public Dimension getMinimumSize() {
    return d;
  }
  public static void main(String[] args) {
    JFrame jf = new JFrame("Calendar");
    Container cp = jf.getContentPane();
    cp.setLayout(new GridLayout(0, 1, 5, 5));
    CalIcon c = new CalIcon(true);
    cp.add(c);
    JButton j = new JButton("As Icon", new CalIcon(false));
    cp.add(j);
    jf.pack();
    jf.setVisible(true);
  }
}
class Clock extends javax.swing.JComponent {
  protected DecimalFormat tflz, tf;
  protected boolean done = false;
  public Clock() {
    new Thread(new Runnable() {
      public void run() {
        while (!done) {
          Clock.this.repaint();  // request a redraw
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e){ /* do nothing*/ }
        }
      }
    }).start();
    tf = new DecimalFormat("#0");
    tflz = new DecimalFormat("00");
  }
  public void stop() {
    done = true;
  }
 
  /* paint() - get current time and draw (centered) in Component. */ 
  public void paint(Graphics g) {
    Calendar myCal = Calendar.getInstance();
    StringBuffer sb = new StringBuffer();
    sb.append(tf.format(myCal.get(Calendar.HOUR)));
    sb.append(":");
    sb.append(tflz.format(myCal.get(Calendar.MINUTE)));
    sb.append(":");
    sb.append(tflz.format(myCal.get(Calendar.SECOND)));
    String s = sb.toString();
    FontMetrics fm = getFontMetrics(getFont());
    int x = (getSize().width - fm.stringWidth(s))/2;
    // System.out.println("Size is " + getSize());
    g.drawString(s, x, 10);
  }
  public Dimension getPreferredSize() {
    return new Dimension(100, 30);
  }
  public Dimension getMinimumSize() {
    return new Dimension(50, 10);
  }
}



Color Icon

    
//
//
//   ColorIcon
//
//   Copyright (C) by Andrea Carboni.
//   This file may be distributed under the terms of the LGPL license.
//

import java.awt.Color;
import java.awt.ruponent;
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.Icon;
//
public class ColorIcon implements Icon
{
  private int iWidth;
  private int iHeight;
  private Color  color;
  private Color  border;
  private Insets insets;
  //---------------------------------------------------------------------------
  public ColorIcon()
  {
    this(32, 16);
  }
  //---------------------------------------------------------------------------
  public ColorIcon(int width, int height)
  {
    this(width, height, Color.black);
  }
  //---------------------------------------------------------------------------
  public ColorIcon(int width, int height, Color c)
  {
    iWidth  = width;
    iHeight = height;
    color   = c;
    border  = Color.black;
    insets  = new Insets(1,1,1,1);
  }
  //---------------------------------------------------------------------------
  public void setColor(Color c)
  {
    color = c;
  }
  //---------------------------------------------------------------------------
  public Color getColor()
  {
    return color;
  }
  //---------------------------------------------------------------------------
  public void setBorderColor(Color c)
  {
    border = c;
  }
  //---------------------------------------------------------------------------
  //---
  //--- Icon interface methods
  //---
  //---------------------------------------------------------------------------
  public int getIconWidth()
  {
    return iWidth;
  }
  //---------------------------------------------------------------------------
  public int getIconHeight()
  {
    return iHeight;
  }
  //---------------------------------------------------------------------------
  public void paintIcon(Component c, Graphics g, int x, int y)
  {
    g.setColor(border);
    g.drawRect(x,y,iWidth-1, iHeight-2);
    x += insets.left;
    y += insets.top;
    int w = iWidth  - insets.left - insets.right;
    int h = iHeight - insets.top  - insets.bottom -1;
    g.setColor(color);
    g.fillRect(x,y, w,h);
  }
}



Create a dynamic icon

     
import java.awt.BorderLayout;
import java.awt.ruponent;
import java.awt.Graphics;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Main{
  Icon icon = new DynamicIcon();
  final JSlider width = new JSlider(JSlider.HORIZONTAL, 1, 150, 75);
  final JSlider height = new JSlider(JSlider.VERTICAL, 1, 150, 75);
  final JLabel dynamicLabel = new JLabel(icon);
  Main(){
    Updater updater = new Updater();
    width.addChangeListener(updater);
    height.addChangeListener(updater);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    f.add(width, BorderLayout.NORTH);
    f.add(height, BorderLayout.WEST);
    f.add(dynamicLabel, BorderLayout.CENTER);
    f.setSize(210, 210);
    f.setVisible(true);
  }
  public static void main(String[] args) {
    new Main();
  }
  class Updater implements ChangeListener {
    public void stateChanged(ChangeEvent ev) {
      dynamicLabel.repaint();
    }
  }
  class DynamicIcon implements Icon {
    public int getIconWidth() {
      return width.getValue();
    }
    public int getIconHeight() {
      return height.getValue();
    }
    public void paintIcon(Component c, Graphics g, int x, int y) {
      g.fill3DRect(x, y, getIconWidth(), getIconHeight(), true);
    }
  }
}



Create Image Icon from PNG file

     
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class PngIcon{
  public PngIcon(){
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JButton bt = new JButton(new ImageIcon("dtmail.png"));
    JLabel lab = new JLabel(new ImageIcon("dtterm.png"));
    bt.setFocusPainted(false);
    frame.add(bt, BorderLayout.NORTH);
    frame.add(lab, BorderLayout.SOUTH);
    frame.setBounds(50, 50, 200, 200);
    frame.setVisible(true);
  }
  public static void main(String[] args){
    new PngIcon();
  }
}



Creates a transparent icon.

   

import java.awt.image.BufferedImage;
import java.util.Arrays;
import javax.swing.Icon;
import javax.swing.ImageIcon;

public final class ImageUtils
{

  /**
   * Creates a transparent image.  These can be used for aligning menu items.
   *
   * @param width  the width.
   * @param height the height.
   * @return the created transparent image.
   */
  public static BufferedImage createTransparentImage (final int width, final int height)
  {
    return new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
  }
  /**
   * Creates a transparent icon. The Icon can be used for aligning menu items.
   *
   * @param width  the width of the new icon
   * @param height the height of the new icon
   * @return the created transparent icon.
   */
  public static Icon createTransparentIcon (final int width, final int height)
  {
    return new ImageIcon(createTransparentImage(width, height));
  }
}



Custom Icon Demo

     
/*
 * 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.
 */

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.AbstractButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class CustomIconDemo extends JPanel implements ActionListener {
  protected JButton b1, b2, b3;
  public CustomIconDemo() {
    Icon leftButtonIcon = new ArrowIcon(SwingConstants.RIGHT);
    Icon middleButtonIcon = new ImageIcon("images/middle.gif");
    Icon rightButtonIcon = new ArrowIcon(SwingConstants.LEFT);
    b1 = new JButton("Disable middle button", leftButtonIcon);
    b1.setVerticalTextPosition(AbstractButton.CENTER);
    b1.setHorizontalTextPosition(AbstractButton.LEFT);
    b1.setMnemonic(KeyEvent.VK_D);
    b1.setActionCommand("disable");
    b2 = new JButton("Middle button", middleButtonIcon);
    b2.setVerticalTextPosition(AbstractButton.BOTTOM);
    b2.setHorizontalTextPosition(AbstractButton.CENTER);
    b2.setMnemonic(KeyEvent.VK_M);
    b3 = new JButton("Enable middle button", rightButtonIcon);
    //Use the default text position of CENTER, RIGHT.
    b3.setMnemonic(KeyEvent.VK_E);
    b3.setActionCommand("enable");
    b3.setEnabled(false);
    //Listen for actions on buttons 1 and 3.
    b1.addActionListener(this);
    b3.addActionListener(this);
    b1.setToolTipText("Click this button to disable the middle button.");
    b2.setToolTipText("This middle button does nothing when you click it.");
    b3.setToolTipText("Click this button to enable the middle button.");
    //Add Components to this container, using the default FlowLayout.
    add(b1);
    add(b2);
    add(b3);
  }
  public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equals("disable")) {
      b2.setEnabled(false);
      b1.setEnabled(false);
      b3.setEnabled(true);
    } else {
      b2.setEnabled(true);
      b1.setEnabled(true);
      b3.setEnabled(false);
    }
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("CustomIconDemo");
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    frame.getContentPane().add(new CustomIconDemo(), BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
  }
}
class ArrowIcon implements Icon, SwingConstants {
  private int width = 9;
  private int height = 18;
  private int[] xPoints = new int[4];
  private int[] yPoints = new int[4];
  public ArrowIcon(int direction) {
    if (direction == LEFT) {
      xPoints[0] = width;
      yPoints[0] = -1;
      xPoints[1] = width;
      yPoints[1] = height;
      xPoints[2] = 0;
      yPoints[2] = height / 2;
      xPoints[3] = 0;
      yPoints[3] = height / 2 - 1;
    } else /* direction == RIGHT */{
      xPoints[0] = 0;
      yPoints[0] = -1;
      xPoints[1] = 0;
      yPoints[1] = height;
      xPoints[2] = width;
      yPoints[2] = height / 2;
      xPoints[3] = width;
      yPoints[3] = height / 2 - 1;
    }
  }
  public int getIconHeight() {
    return height;
  }
  public int getIconWidth() {
    return width;
  }
  public void paintIcon(Component c, Graphics g, int x, int y) {
    int length = xPoints.length;
    int adjustedXPoints[] = new int[length];
    int adjustedYPoints[] = new int[length];
    for (int i = 0; i < length; i++) {
      adjustedXPoints[i] = xPoints[i] + x;
      adjustedYPoints[i] = yPoints[i] + y;
    }
    if (c.isEnabled()) {
      g.setColor(Color.black);
    } else {
      g.setColor(Color.gray);
    }
    g.fillPolygon(adjustedXPoints, adjustedYPoints, length);
  }
}



Draw an Icon object

     
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class BasicDraw {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.add(new MyComponent());
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}
class MyComponent extends JComponent {
  public void paint(Graphics g) {
    ImageIcon icon = new ImageIcon("a.png");
    int x = 0;
    int y = 100;
    icon.paintIcon(this, g, x, y);
  }
}



Example of an icon that changes form

     
import java.awt.BorderLayout;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.Graphics;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class DynamicIconExample {
  public static void main(String[] args) {
    final JSlider width = new JSlider(JSlider.HORIZONTAL, 1, 150, 75);
    final JSlider height = new JSlider(JSlider.VERTICAL, 1, 150, 75);
    class DynamicIcon implements Icon {
      public int getIconWidth() {
        return width.getValue();
      }
      public int getIconHeight() {
        return height.getValue();
      }
      public void paintIcon(Component c, Graphics g, int x, int y) {
        g.fill3DRect(x, y, getIconWidth(), getIconHeight(), true);
      }
    }
    
    Icon icon = new DynamicIcon();
    final JLabel dynamicLabel = new JLabel(icon);
    class Updater implements ChangeListener {
      public void stateChanged(ChangeEvent ev) {
        dynamicLabel.repaint();
      }
    }
    Updater updater = new Updater();
    width.addChangeListener(updater);
    height.addChangeListener(updater);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container c = f.getContentPane();
    c.setLayout(new BorderLayout());
    c.add(width, BorderLayout.NORTH);
    c.add(height, BorderLayout.WEST);
    c.add(dynamicLabel, BorderLayout.CENTER);
    f.setSize(210, 210);
    f.setVisible(true);
  }
  
}



Icon Codec

    
/*
  JSmooth: a VM wrapper toolkit for Windows
  Copyright (C) 2003 Rodrigo Reyes <reyes@charabia.net>
 
  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.
 
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
 
  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
 */

import java.io.*;
import java.awt.image.*;
import java.awt.*;
/**
 *
 * @author  Rodrigo Reyes
 */
public class IcoCodec
{
    static public class IconDir
    {
        int idType;
        int idCount;
  public IconDir(BinaryInputStream in) throws IOException
  {
      in.readUShortLE();
      idType = in.readUShortLE();
      idCount = in.readUShortLE();
  }
  
  public String toString()
  {
      return "{ idType=" + idType + ", " + idCount + " }";
  }
    }
    
    static public class IconEntry
    {
        short  bWidth;
        short  bHeight;
        short  bColorCount;
        short  bReserved;
        int  wPlanes;
        int  wBitCount;
        long dwBytesInRes;
        long dwImageOffset;
  public IconEntry(BinaryInputStream in) throws IOException
  {
      bWidth = in.readUByte();
      bHeight = in.readUByte();
      bColorCount = in.readUByte();
      bReserved = in.readUByte();
      wPlanes = in.readUShortLE();
      wBitCount = in.readUShortLE();
      dwBytesInRes = in.readUIntLE();
      dwImageOffset = in.readUIntLE();
  }
  public String toString()
  {
      StringBuffer buffer = new StringBuffer();
      buffer.append("{ bWidth="+bWidth+"\n");
      buffer.append("  bHeight="+bHeight+"\n");
      buffer.append("  bColorCount="+bColorCount+"\n");
      buffer.append("  wPlanes="+wPlanes+"\n");
      buffer.append("  wBitCount="+wBitCount+"\n");
      buffer.append("  dwBytesInRes="+dwBytesInRes+"\n");
      buffer.append("  dwImageOffset="+dwImageOffset+"\n");
      buffer.append("}");
      return buffer.toString();
  }
    }
    static public class IconHeader
    {
  public long Size;            /* Size of this header in bytes DWORD 0*/
  public long Width;           /* Image width in pixels LONG 4*/
  public long Height;          /* Image height in pixels LONG 8*/
  public int  Planes;          /* Number of color planes WORD 12 */
  public int  BitsPerPixel;    /* Number of bits per pixel WORD 14 */
  /* Fields added for Windows 3.x follow this line */
  public long Compression;     /* Compression methods used DWORD 16 */
  public long SizeOfBitmap;    /* Size of bitmap in bytes DWORD 20 */
  public long HorzResolution;  /* Horizontal resolution in pixels per meter LONG 24 */
  public long VertResolution;  /* Vertical resolution in pixels per meter LONG 28*/
  public long ColorsUsed;      /* Number of colors in the image DWORD 32 */
  public long ColorsImportant; /* Minimum number of important colors DWORD 36 */
  
  public IconHeader(BinaryInputStream in) throws IOException
  {
      Size = in.readUIntLE();
      Width = in.readUIntLE();
      Height = in.readUIntLE();
      Planes = in.readUShortLE();
      BitsPerPixel = in.readUShortLE();
      Compression = in.readUIntLE();
      SizeOfBitmap = in.readUIntLE();
      HorzResolution = in.readUIntLE();
      VertResolution = in.readUIntLE();
      ColorsUsed = in.readUIntLE();
      ColorsImportant = in.readUIntLE();
  }
  public String toString()
  {
      StringBuffer buffer = new StringBuffer();
      buffer.append("Size="); buffer.append(Size);
      buffer.append("\nWidth="); buffer.append(Width);
      buffer.append("\nHeight="); buffer.append(Height);
      buffer.append("\nPlanes="); buffer.append(Planes);
      buffer.append("\nBitsPerPixel="); buffer.append(BitsPerPixel);
      buffer.append("\nCompression="); buffer.append(Compression);
      buffer.append("\nSizeOfBitmap="); buffer.append(SizeOfBitmap);
      buffer.append("\nHorzResolution="); buffer.append(HorzResolution);
      buffer.append("\nVertResolution="); buffer.append(VertResolution);
      buffer.append("\nColorsUsed="); buffer.append(ColorsUsed);
      buffer.append("\nColorsImportant="); buffer.append(ColorsImportant);
      return buffer.toString();
  }
    }
    
    static public BufferedImage[] loadImages(File f) throws IOException
    {
  InputStream istream = new FileInputStream(f);
        BufferedInputStream buffin = new BufferedInputStream(istream);
  BinaryInputStream in = new BinaryInputStream(buffin);
  try {
      in.mark(32000);
      IconDir dir = new IconDir(in);
      //      System.out.println("DIR = " + dir);
      
      IconEntry[] entries = new IconEntry[dir.idCount];
      BufferedImage[] images = new BufferedImage[dir.idCount];
      for (int i=0; i<dir.idCount; i++)
    {
        entries[i] = new IconEntry(in);
        //        System.out.println("ENTRY " + i + " = " + entries[i]);
    }
      IconEntry entry = entries[0];
      //      System.out.println("ENTRYx = " + entry);
      for (int i=0; i<dir.idCount; i++)
    {
        in.reset();
        in.skip(entries[i].dwImageOffset);
        IconHeader header = new IconHeader(in);
        //        System.out.println("Header: " + header);
        long toskip = header.Size - 40;
        if (toskip>0)
      in.skip((int)toskip);
        //        System.out.println("skipped data");
        
        BufferedImage image = new BufferedImage((int)header.Width, (int)header.Height/2,
                  BufferedImage.TYPE_INT_ARGB);
        
        switch(header.BitsPerPixel)
      {
      case 4:
      case 8:
          loadPalettedImage(in, entries[i], header, image);
          break;
          
      default:
          throw new Exception("Unsupported ICO color depth: " + header.BitsPerPixel);
      }
        images[i] = image;
    }
      return images;
  } catch (Exception exc)
      {
    exc.printStackTrace();
      }
  return null;
    }
    static private void loadPalettedImage(BinaryInputStream in, IconEntry entry, IconHeader header, BufferedImage image) throws Exception
    {
  //  System.out.println("Loading image...");
  
  //  System.out.println("Loading palette...");
  // 
  // First, load the palette
  //
  int cols = (int)header.ColorsUsed;
  if (cols == 0)
      {
    if (entry.bColorCount != 0)
        cols = entry.bColorCount;
    else
        cols = 1 << header.BitsPerPixel;
      }
  int[] redp = new int[cols];
  int[] greenp = new int[cols];
  int[] bluep = new int[cols];
  for (int i=0; i<cols; i++)
      {
    bluep[i] = in.readUByte();
    greenp[i] = in.readUByte();
    redp[i] = in.readUByte();
    in.readUByte();
      }
  //  System.out.println("Palette read!");
  //
  // Set the image
  int xorbytes = (((int)header.Height/2) * (int)header.Width);
  int readbytes = 0;
  for (int y=(int)(header.Height/2)-1; y>=0; y--)
      {
    for (int x=0; x<header.Width; x++)
        {
      switch(header.BitsPerPixel)
          {
          case 4:
        {
            int pix = in.readUByte();
            readbytes++;
            int col1 = (pix>>4) & 0x0F;
            int col2 = pix & 0x0F;
            image.setRGB(x, y, (0xFF<<24) | (redp[col1]<<16) | (greenp[col1]<<8) | bluep[col1]);
            image.setRGB(++x, y, (0xFF<<24) | (redp[col2]<<16) | (greenp[col2]<<8) | bluep[col2]);
        }
        break;
          case 8:
        {
            int col1 = in.readUByte();
            readbytes++;
            image.setRGB(x, y, (0xFF<<24) | (redp[col1]<<16) | (greenp[col1]<<8) | bluep[col1]);
        }
        break;
          }
        }
      }
  //  System.out.println("XOR data read (" + readbytes + " bytes)");
  int height = (int)(header.Height/2);
  int rowsize = (int)header.Width / 8;
  if ((rowsize%4)>0)
      {
    rowsize += 4 - (rowsize%4);
      }
  
  //  System.out.println("rowsize = " + rowsize);
  int[] andbytes = new int[rowsize * height ];
  for (int i=0; i<andbytes.length; i++)
      andbytes[i] = in.readUByte();

  for (int y=height-1; y>=0; y--)
      {
    for (int x=0; x<header.Width; x++)
        {
      int offset = ((height - (y+1))*rowsize) + (x/8);
      if ( (andbytes[offset] & (1<<(7-x%8))) != 0)
          {
        image.setRGB(x, y, 0);
          }
        }
      }
  //  for (int i=0; i<andbytes; i++)
  //      {
  //    int pix = in.readUByte();
  //    readbytes++;
  //    int xb = (i*8) % (int)header.Width;
  //    int yb = ((int)header.Height/2) - (((i*8) / (int)header.Width)+1);
  //    for (int offset=7; offset>=0; offset--)
  //        {
  //      //
  //      // Modify the transparency only if necessary
  //      //
  //      System.out.println("SET AND (" + xb + "," + yb + ")-" + (7-offset));
  //      if (((1<<offset) & pix)!=0)
  //          {
  //        int argb = image.getRGB(xb+(7-offset), yb);
  //        image.setRGB(xb+(7-offset), yb, argb & 0xFFFFFF);
  //          }
  //        }
  //      }
  
  //  System.out.println("AND data read (" + readbytes + " bytes total)");
    }
    
    static public void main(String[]args) throws Exception
    {
  File f = new File(args[0]);
  Image img = IcoCodec.loadImages(f)[0];
  //  System.out.println("img = " + img);
  javax.swing.JFrame jf = new javax.swing.JFrame("Test");
  javax.swing.JButton button = new javax.swing.JButton(new javax.swing.ImageIcon(img));
  jf.getContentPane().add(button);
  jf.pack();
  jf.setVisible(true);
    }
    
}
/*
JSmooth: a VM wrapper toolkit for Windows
Copyright (C) 2003 Rodrigo Reyes <reyes@charabia.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
class BinaryInputStream extends FilterInputStream
{
  public BinaryInputStream(InputStream in)
  {
super(in);
  }
  public void skip(int toskip) throws IOException
  {
for (int skipped = 0; skipped >= toskip; skipped += in.skip(toskip - skipped))
    ;
  }
  public byte readByte() throws IOException
  {
return (byte)read();
  }
  public short readUByte() throws IOException
  {
return (short)read();
  }
  public short readShortBE() throws IOException
  {
int a = read();
int b = read();
return (short) (((a&0xff)<<8) | (b&0xff));
  }
  public int readUShortBE() throws IOException
  {
int a = read();
int b = read();
return ((a&0xff)<<8) | (b&0xff);
  }
  public short readShortLE() throws IOException
  {
int a = read();
int b = read();
return (short) (((b&0xff)<<8) | (a&0xff));
  }
  public int readUShortLE() throws IOException
  {
int a = read();
int b = read();
return ((b&0xff)<<8) | (a&0xff);
  }
  public int readIntBE() throws IOException
  {
int a = read();
int b = read();
int c = read();
int d = read();
return ((a&0xff)<<24) | ((b&0xff)<<16) | ((c&0xff)<<8) | (d&0xff);
  }
  public long readUIntBE() throws IOException
  {
int a = read();
int b = read();
int c = read();
int d = read();
return (long)((a&0xff)<<24) | (long)((b&0xff)<<16) | (long)((c&0xff)<<8) | (long)(d&0xff);
  }
  public int readIntLE() throws IOException
  {
int a = readByte();
int b = readByte();
int c = readByte();
int d = readByte();
return ((d&0xff)<<24) | ((c&0xff)<<16) | ((b&0xff)<<8) | (a&0xff);
  }
  public long readUIntLE() throws IOException
  {
int a = readByte();
int b = readByte();
int c = readByte();
int d = readByte();
return (long)((d&0xff)<<24) | (long)((c&0xff)<<16) | (long)((b&0xff)<<8) | (long)(a&0xff);
  }
}



Icon Displayer

     
/*
 * 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.
 */
/*
 * IconDisplayer.java is a 1.4 application that requires the following files:
 * images/rocketship.gif
 */
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
/*
 * This component displays a single icon one or more times in a row. The images
 * are right-aligned, with 5 pixels padding in between. All but the rightmost
 * image are mostly transparent.
 */
public class IconDisplayer extends JComponent {
  private Icon icon;
  private int preferredNumImages = 2;
  private int pad = 5; //space between images
  private Rectangle iconRect = new Rectangle();
  private Rectangle clipRect = new Rectangle();
  public IconDisplayer(Icon icon, int preferredNumImages, int pad) {
    this.icon = icon;
    if (preferredNumImages > 0) {
      this.preferredNumImages = preferredNumImages;
    }
    if (pad >= 0) {
      this.pad = pad;
    }
    //Set a reasonable default border.
    if (this.pad > 0) {
      setBorder(BorderFactory.createEmptyBorder(this.pad, this.pad,
          this.pad, this.pad));
    }
  }
  public Dimension getPreferredSize() {
    if (icon != null) {
      Insets insets = getInsets();
      return new Dimension(icon.getIconWidth() * preferredNumImages + pad
          * (preferredNumImages - 1) + insets.left + insets.right,
          icon.getIconHeight() + insets.top + insets.bottom);
    } else {
      return new Dimension(100, 100);
    }
  }
  public Dimension getMinimumSize() {
    if (icon != null) {
      Insets insets = getInsets();
      //Return enough space for one icon.
      return new Dimension(icon.getIconWidth() + insets.left
          + insets.right, icon.getIconHeight() + insets.top
          + insets.bottom);
    } else {
      return new Dimension(0, 0);
    }
  }
  protected void paintComponent(Graphics g) {
    if (isOpaque()) { //paint background
      g.setColor(getBackground());
      g.fillRect(0, 0, getWidth(), getHeight());
    }
    if (icon != null) {
      //Draw the icon over and over, right aligned.
      Insets insets = getInsets();
      int iconWidth = icon.getIconWidth();
      int iconX = getWidth() - insets.right - iconWidth;
      int iconY = insets.top;
      boolean faded = false;
      //Copy the Graphics object, which is actually
      //a Graphics2D object. Cast it so we can
      //set alpha composite.
      Graphics2D g2d = (Graphics2D) g.create();
      //Draw the icons, starting from the right.
      //After the first one, the rest are faded.
      //We won"t bother painting icons that are clipped.
      g.getClipBounds(clipRect);
      while (iconX >= insets.left) {
        iconRect.setBounds(iconX, iconY, iconWidth, icon
            .getIconHeight());
        if (iconRect.intersects(clipRect)) {
          icon.paintIcon(this, g2d, iconX, iconY);
        }
        iconX -= (iconWidth + pad);
        if (!faded) {
          g2d.setComposite(AlphaComposite.getInstance(
              AlphaComposite.SRC_OVER, 0.1f));
          faded = true;
        }
      }
      g2d.dispose(); //clean up
    }
  }
  /** Returns an ImageIcon, or null if the path was invalid. */
  protected static ImageIcon createImageIcon(String path) {
    java.net.URL imgURL = IconDisplayer.class.getResource(path);
    if (imgURL != null) {
      return new ImageIcon(imgURL);
    } else {
      System.err.println("Couldn"t find file: " + path);
      return null;
    }
  }
  /**
   * 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("IconDisplayer");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    ImageIcon ship = createImageIcon("rocketship.gif");
    IconDisplayer id = new IconDisplayer(ship, 5, -1);
    frame.getContentPane().add(id, BorderLayout.CENTER);
    //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();
      }
    });
  }
}



Icon Line

    
//   IconLine
//   Copyright (C) by Andrea Carboni.
//   This file may be distributed under the terms of the LGPL license.
//

import java.awt.ruponent;
import java.awt.Graphics;
import java.awt.Image;
import java.util.Vector;
import javax.swing.Icon;
//
public class IconLine implements Icon
{
  private int    iWidth  = 0;
  private int    iHeight = 0;
  private int    iSpace  = 1;
  private Vector vImages = new Vector();
  //---------------------------------------------------------------------------
  //---
  //--- Constructor
  //---
  //---------------------------------------------------------------------------
  public IconLine() {}
  //---------------------------------------------------------------------------
  public IconLine(int space)
  {
    iSpace = space;
  }
  //---------------------------------------------------------------------------
  //---
  //--- Constructor
  //---
  //---------------------------------------------------------------------------
  public void addImage(Image image)
  {
    vImages.add(image);
    iWidth  = iWidth + image.getWidth(null);
    iHeight = image.getHeight(null);
  }
  //---------------------------------------------------------------------------
  public void setImage(int index, Image image)
  {
    vImages.set(index, image);
    iHeight = image.getHeight(null);
  }
  //---------------------------------------------------------------------------
  //---
  //--- Icon interface methods
  //---
  //---------------------------------------------------------------------------
  public int getIconWidth()
  {
    return iWidth;
  }
  //---------------------------------------------------------------------------
  public int getIconHeight()
  {
    return iHeight;
  }
  //---------------------------------------------------------------------------
  public void paintIcon(Component c, Graphics g, int x, int y)
  {
    int dx = 0;
    for(int i=0; i<vImages.size(); i++)
    {
      Image image = (Image) vImages.get(i);
      g.drawImage(image, x +dx, y, c);
      dx += image.getWidth(c) +iSpace;
    }
  }
}
//



Implement the Icon interface

     
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Graphics;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class IconInterfaceDemo extends JPanel {
  public IconInterfaceDemo() {
  }
  public static void main(String[] a) {
    JFrame mainFrame = new JFrame();
    JLabel label = new JLabel("label");
    label.setIcon(new ColoredSquare(Color.green));
    label.setDisabledIcon(new ColoredSquare(Color.red));
    mainFrame.getContentPane().add(label);
    mainFrame.setSize(100, 100);
    mainFrame.setVisible(true);
  }
}
class ColoredSquare implements Icon {
  Color color;
  public ColoredSquare(Color color) {
    this.color = color;
  }
  public void paintIcon(Component c, Graphics g, int x, int y) {
    Color oldColor = g.getColor();
    g.setColor(color);
    g.fill3DRect(x, y, getIconWidth(), getIconHeight(), true);
    g.setColor(oldColor);
  }
  public int getIconWidth() {
    return 12;
  }
  public int getIconHeight() {
    return 12;
  }
}



Layered Icon

  
/*
 *  LayeredIcon.java
 *  2006-08-09
 */
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.util.ArrayList;
import javax.swing.Icon;
import javax.swing.SwingConstants;
/**
 * @author Christopher Bach
 */
public class LayeredIcon implements Icon {
  public static final int TOP = SwingConstants.TOP, LEFT = SwingConstants.LEFT,
      BOTTOM = SwingConstants.BOTTOM, RIGHT = SwingConstants.RIGHT, CENTER = SwingConstants.CENTER;
  private Dimension ourPrefSize = new Dimension(0, 0);
  private ArrayList ourLayers = new ArrayList();
  private Insets ourPadding = new Insets(0, 0, 0, 0);
  /**
   * 
   */
  public LayeredIcon() {
  }
  /**
   * 
   */
  public LayeredIcon(int padding) {
    setPadding(padding, padding, padding, padding);
  }
  /**
   * Creates a new instance of LayeredIcon with the specified width and height,
   * but no graphic.
   */
  public LayeredIcon(int width, int height) {
    setIconSize(width, height);
  }
  /**
   * 
   */
  public LayeredIcon(int width, int height, int padding) {
    setIconSize(width, height);
    setPadding(padding, padding, padding, padding);
  }
  /**
   * 
   */
  public LayeredIcon(int topPadding, int leftPadding, int bottomPadding, int rightPadding) {
    setPadding(topPadding, leftPadding, bottomPadding, rightPadding);
  }
  /**
   * 
   */
  public LayeredIcon(int width, int height, int topPadding, int leftPadding, int bottomPadding,
      int rightPadding) {
    setIconSize(width, height);
    setPadding(topPadding, leftPadding, bottomPadding, rightPadding);
  }
  /**
   * If any client Icons have been added and painting is enabled, paints the
   * client Icons at the specified coordinates into the provided graphics
   * context for the indicated Component.
   */
  public void paintIcon(Component c, Graphics g, int x, int y) {
    Dimension iconSize = getIconSize();
    for (int i = 0, size = ourLayers.size(); i < size; i++) {
      Layer layer = (Layer) ourLayers.get(i);
      if (layer.painted) {
        int w = layer.icon.getIconWidth();
        int h = layer.icon.getIconHeight();
        int dx = (layer.halign == LEFT ? 0 : iconSize.width - w);
        if (layer.halign != RIGHT)
          dx = dx / 2;
        dx += ourPadding.left;
        int dy = (layer.valign == TOP ? 0 : iconSize.height - h);
        if (layer.valign != BOTTOM)
          dy = dy / 2;
        dy += ourPadding.top;
        layer.icon.paintIcon(c, g, x + dx, y + dy);
      }
    }
  }
  /**
   * Returns the width of the LayeredIcon. If any client Icons have been added,
   * returns the max width of all client Icons. Otherwise, returns the
   * LayeredIcon"s explicit width.
   */
  public int getIconWidth() {
    return getIconSize().width + ourPadding.left + ourPadding.right;
  }
  /**
   * Returns the height of the LayeredIcon. If any client Icons have been added,
   * returns the max height of all client Icons. Otherwise, returns the
   * LayeredIcon"s explicit height.
   */
  public int getIconHeight() {
    return getIconSize().height + ourPadding.top + ourPadding.bottom;
  }
  /**
   * Sets the explicit size of the LayeredIcon to be used when no client Icons
   * have been added.
   */
  public void setIconSize(int width, int height) {
    ourPrefSize.width = width;
    ourPrefSize.height = height;
  }
  /**
   * 
   */
  public void setPadding(int padding) {
    ourPadding.top = padding;
    ourPadding.left = padding;
    ourPadding.bottom = padding;
    ourPadding.right = padding;
  }
  /**
   * 
   */
  public void setPadding(int topPadding, int leftPadding, int bottomPadding, int rightPadding) {
    ourPadding.top = topPadding;
    ourPadding.left = leftPadding;
    ourPadding.bottom = bottomPadding;
    ourPadding.right = rightPadding;
  }
  /**
   * 
   */
  public Insets getPadding() {
    return new Insets(ourPadding.top, ourPadding.left, ourPadding.bottom, ourPadding.right);
  }
  /**
   * 
   */
  public void addIcon(Icon icon) {
    if (icon != null) {
      ourLayers.add(new Layer(icon));
    }
  }
  /**
   * 
   */
  public void addIcon(Icon icon, int index) {
    if (icon != null && index >= 0 && index <= ourLayers.size()) {
      ourLayers.add(index, new Layer(icon));
    }
  }
  /**
   * 
   */
  public void addIcon(Icon icon, int halign, int valign) {
    if (icon != null) {
      ourLayers.add(new Layer(icon, checkHAlign(halign), checkVAlign(valign)));
    }
  }
  /**
   * 
   */
  public void addIcon(Icon icon, int index, int halign, int valign) {
    if (icon != null && index >= 0 && index <= ourLayers.size()) {
      ourLayers.add(index, new Layer(icon, checkHAlign(halign), checkVAlign(valign)));
    }
  }
  /**
   * 
   */
  public void removeIcon(Icon icon) {
    Layer layer = getLayer(icon);
    if (layer != null) {
      ourLayers.remove(layer);
    }
  }
  /**
   * 
   */
  public void clear() {
    ourLayers.clear();
  }
  /**
   * 
   */
  public Icon getIcon(int index) {
    Layer layer = (Layer) ourLayers.get(index);
    if (layer != null)
      return layer.icon;
    else
      return null;
  }
  /**
   * 
   */
  public int indexOf(Icon icon) {
    for (int i = 0, size = ourLayers.size(); i < size; i++) {
      Layer layer = (Layer) ourLayers.get(i);
      if (layer.icon == icon)
        return i;
    }
    return -1;
  }
  /**
   * 
   */
  public int iconCount() {
    return ourLayers.size();
  }
  /**
   * 
   */
  public boolean isIconPainted(int iconIndex) {
    Layer layer = (Layer) ourLayers.get(iconIndex);
    if (layer != null)
      return layer.painted;
    else
      return false;
  }
  /**
   * 
   */
  public void setIconPainted(int iconIndex, boolean painted) {
    Layer layer = (Layer) ourLayers.get(iconIndex);
    if (layer != null)
      layer.painted = painted;
  }
  /**
   * 
   */
  public boolean isIconPainted(Icon icon) {
    Layer layer = getLayer(icon);
    if (layer != null)
      return layer.painted;
    else
      return false;
  }
  /**
   * 
   */
  public void setIconPainted(Icon icon, boolean painted) {
    Layer layer = getLayer(icon);
    if (layer != null)
      layer.painted = painted;
  }
  /**
   * 
   */
  public void setIconAlignment(Icon icon, int halign, int valign) {
    Layer layer = getLayer(icon);
    if (layer != null) {
      layer.halign = checkHAlign(halign);
      layer.valign = checkVAlign(valign);
    }
  }
  /**
   * 
   */
  public void setIconAlignment(int iconIndex, int halign, int valign) {
    Layer layer = (Layer) ourLayers.get(iconIndex);
    if (layer != null) {
      layer.halign = checkHAlign(halign);
      layer.valign = checkVAlign(valign);
    }
  }
  /**
   * 
   */
  public int getIconHAlignment(Icon icon) {
    Layer layer = getLayer(icon);
    if (layer != null)
      return layer.halign;
    else
      return CENTER;
  }
  /**
   * 
   */
  public int getIconVAlignment(Icon icon) {
    Layer layer = getLayer(icon);
    if (layer != null)
      return layer.valign;
    else
      return CENTER;
  }
  /**
   * 
   */
  public int getIconHAlignment(int iconIndex) {
    Layer layer = (Layer) ourLayers.get(iconIndex);
    if (layer != null)
      return layer.halign;
    else
      return CENTER;
  }
  /**
   * 
   */
  public int getIconVAlignment(int iconIndex) {
    Layer layer = (Layer) ourLayers.get(iconIndex);
    if (layer != null)
      return layer.valign;
    else
      return CENTER;
  }
  /**
   * 
   */
  private int checkHAlign(int halign) {
    if (halign != LEFT && halign != RIGHT && halign != CENTER)
      return CENTER;
    else
      return halign;
  }
  /**
   * 
   */
  private int checkVAlign(int valign) {
    if (valign != TOP && valign != BOTTOM && valign != CENTER)
      return CENTER;
    else
      return valign;
  }
  /**
   * 
   */
  private Layer getLayer(Icon icon) {
    for (int i = 0, size = ourLayers.size(); i < size; i++) {
      Layer layer = (Layer) ourLayers.get(i);
      if (layer.icon == icon)
        return layer;
    }
    return null;
  }
  /**
   * 
   */
  private Dimension getIconSize() {
    if (ourLayers.size() == 0)
      return ourPrefSize;
    Dimension d = new Dimension(0, 0);
    for (int i = 0, size = ourLayers.size(); i < size; i++) {
      Layer layer = (Layer) ourLayers.get(i);
      d.height = Math.max(d.height, layer.icon.getIconHeight());
      d.width = Math.max(d.width, layer.icon.getIconWidth());
    }
    return d;
  }
  /**
   * 
   */
  private class Layer {
    public Icon icon = null;
    public boolean painted = true;
    public int halign = CENTER;
    public int valign = CENTER;
    public Layer() {
    }
    public Layer(Icon icon) {
      this.icon = icon;
    }
    public Layer(Icon icon, int halign, int valign) {
      this.icon = icon;
      this.halign = halign;
      this.valign = valign;
    }
  }
}



MemImage is an in-memory icon showing a Color gradient

     
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
///
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.MemoryImageSource;
/** MemImage is an in-memory icon showing a Color gradient. */
public class MemImage extends Component {
  /**
   * Demo main program, showing two ways to use it. Create a small MemImage
   * and set it as this Frame"s iconImage. Also display a larger version of
   * the same image in the Frame.
   */
  public static void main(String[] av) {
    Frame f = new Frame("MemImage.java");
    f.add(new MemImage());
    f.setIconImage(new MemImage(16, 16).getImage());
    f.pack();
    f.setVisible(true);
  }
  /** The image */
  private Image img;
  /** The image width */
  private int w;
  /** The image height */
  private int h;
  /** Construct a MemImage with a default size */
  public MemImage() {
    this(100, 100);
  }
  /** Construct a MemImage with a specified width and height */
  public MemImage(int w, int h) {
    this.w = w;
    this.h = h;
    int pix[] = new int[w * h];
    int index = 0;
    for (int y = 0; y < h; y++) {
      int red = (y * 255) / (h - 1);
      for (int x = 0; x < w; x++) {
        int blue = (x * 255) / (w - 1);
        pix[index++] = (255 << 24) | (red << 16) | blue;
      }
    }
    img = createImage(new MemoryImageSource(w, h, pix, 0, w));
    setSize(getPreferredSize());
  }
  /** Getter for the Image */
  public Image getImage() {
    return img;
  }
  public Dimension getPreferredSize() {
    return new Dimension(w, h);
  }
  public void paint(Graphics g) {
    g.drawImage(img, 0, 0, getSize().width, getSize().height, this);
  }
}



Plain Color Icon

    
// The UMLet source code is distributed under the terms of the GPL; see license.txt

import java.awt.Color;
import java.awt.ruponent;
import java.awt.Graphics;
import javax.swing.Icon;
public class PlainColorIcon implements Icon {
  
  private Color color;
  
  public PlainColorIcon(Color color) {
    this.color = color;
  }
  public void paintIcon(Component c, Graphics g, int x, int y) {
    Color old_color = g.getColor();
    g.setColor(color);
    g.fillRect(x,y,10,10);
    g.setColor(old_color);
  }
  public int getIconWidth() {
    return 10;
  }
  public int getIconHeight() {
    return 10;
  }
  
}



Reading an Image or Icon from a File

     
import java.awt.Image;
import java.awt.Toolkit;
public class BasicDraw {
  public static void main(String[] args) {
    Image image = Toolkit.getDefaultToolkit().getImage("image.gif");
    int width = image.getWidth(null);
    int height = image.getHeight(null);
    if (width >= 0) {
      // The image has been fully loaded
    } else {
      // The image has not been fully loaded
    }
  }
}



Return a filled oval as an Icon

    
/*
 This file is part of the BlueJ program. 
 Copyright (C) 1999-2009  Michael K�lling and John Rosenberg 
 
 This program is free software; you can redistribute it and/or 
 modify it under the terms of the GNU General Public License 
 as published by the Free Software Foundation; either version 2 
 of the License, or (at your option) any later version. 
 
 This program is distributed in the hope that it will be useful, 
 but WITHOUT ANY WARRANTY; without even the implied warranty of 
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 GNU General Public License for more details. 
 
 You should have received a copy of the GNU General Public License 
 along with this program; if not, write to the Free Software 
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA. 
 
 This file is subject to the Classpath exception as provided in the  
 LICENSE.txt file that accompanied this code.
 */
import javax.swing.*;
import java.awt.*;
/**
 * Return a filled oval as an Icon
 *
 * @author  Andrew Patterson
 * @cvs     $Id: OvalIcon.java 6164 2009-02-19 18:11:32Z polle $
 */
public class OvalIcon implements Icon
{
    private static OvalIcon redIcon = new OvalIcon(Color.red);
    private static OvalIcon blankIcon = new OvalIcon(null);
    public static OvalIcon getRedOvalIcon()
    {
        return redIcon;        
    }
    public static OvalIcon getBlankOvalIcon()
    {
        return blankIcon;
    }
    private Color color;
    public OvalIcon (Color c) {
       color = c;
    }
    public void paintIcon (Component c, Graphics g, int x, int y)
    {
  if(color != null) {
  int width = getIconWidth();
  int height = getIconHeight();
   g.setColor (color);
  g.fillOval (x, y, width, height);
  }
}
public int getIconWidth() {
  return 10;
}
public int getIconHeight() { 
  return 10;
}
}



Transparent icon with no content

    
/*
    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public
    License as published by the Free Software Foundation; either
    version 2 of the license, or (at your option) any later version.
*/

import javax.swing.*;
import java.awt.*;
/**
    Transparent icon with no content.
    @author 
    @version $Revision: 1.1 $ $Date: 2003/08/18 07:46:43 $
*/
public class EmptyIcon implements Icon {
    private int width;
    private int height;
    /**
     * Constructor.
     * @param width the width of the icon.
     * @param height the height of the icon.
     */
    public EmptyIcon(int width, int height) {
        this.width = width;
        this.height = height;
    }
    public void paintIcon(Component c, Graphics g, int x, int y) {
    }
    public int getIconWidth() {
        return width;
    }
    public int getIconHeight() {
        return height;
    }
}