Java Tutorial/2D Graphics/ImageIcon — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 15:25, 31 мая 2010

A button which paints on it one or more scaled arrows in one of the cardinal directions

//Revised from greef ui;
import java.awt.BorderLayout;
import java.awt.ruponent;
import java.awt.Graphics;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
/**
 * A button which paints on it one or more scaled arrows in one of the cardinal directions.
 * @author Adrian BER
 */
public class ArrowIcon implements Icon {
    /** The cardinal direction of the arrow(s). */
    private int direction;
    /** The number of arrows. */
    private int arrowCount;
    /** The arrow size. */
    private int arrowSize;
    public ArrowIcon(int direction, int arrowCount, int arrowSize) {
        this.direction = direction;
        this.arrowCount = arrowCount;
        this.arrowSize = arrowSize;
    }
    /** Returns the cardinal direction of the arrow(s).
     * @see #setDirection(int)
     */
    public int getDirection() {
        return direction;
    }
    /** Sets the cardinal direction of the arrow(s).
     * @param direction the direction of the arrow(s), can be SwingConstants.NORTH,
     * SwingConstants.SOUTH, SwingConstants.WEST or SwingConstants.EAST
     * @see #getDirection()
     */
    public void setDirection(int direction) {
        this.direction = direction;
    }
    /** Returns the number of arrows. */
    public int getArrowCount() {
        return arrowCount;
    }
    /** Sets the number of arrows. */
    public void setArrowCount(int arrowCount) {
        this.arrowCount = arrowCount;
    }
    /** Returns the arrow size. */
    public int getArrowSize() {
        return arrowSize;
    }
    /** Sets the arrow size. */
    public void setArrowSize(int arrowSize) {
        this.arrowSize = arrowSize;
    }
    public void paintIcon(Component c, Graphics g, int x, int y) {
        // paint the arrows
        int w = getIconWidth();
        int h = getIconHeight();
        for (int i = 0; i < arrowCount; i++) {
            paintArrow(g,
                    (x + w - arrowSize * (direction == SwingConstants.EAST
                            || direction == SwingConstants.WEST ? arrowCount : 1)) / 2
                            + arrowSize * (direction == SwingConstants.EAST
                            || direction == SwingConstants.WEST ? i : 0),
                    (y + h - arrowSize * (direction == SwingConstants.EAST
                            || direction == SwingConstants.WEST ? 1 : arrowCount)) / 2
                            + arrowSize * (direction == SwingConstants.EAST
                            || direction == SwingConstants.WEST ? 0 : i)
                    );
        }
    }
    public int getIconWidth() {
        return arrowSize * (direction == SwingConstants.EAST
                || direction == SwingConstants.WEST ? arrowCount : 3);
    }
    public int getIconHeight() {
        return arrowSize * (direction == SwingConstants.NORTH
                || direction == SwingConstants.SOUTH ? arrowCount : 3);
    }
    private void paintArrow(Graphics g, int x, int y) {
        int mid, i, j;
        j = 0;
        arrowSize = Math.max(arrowSize, 2);
        mid = (arrowSize / 2) - 1;
        g.translate(x, y);
        switch (direction) {
            case SwingConstants.NORTH:
                for (i = 0; i < arrowSize; i++) {
                    g.drawLine(mid - i, i, mid + i, i);
                }
                break;
            case SwingConstants.SOUTH:
                j = 0;
                for (i = arrowSize - 1; i >= 0; i--) {
                    g.drawLine(mid - i, j, mid + i, j);
                    j++;
                }
                break;
            case SwingConstants.WEST:
                for (i = 0; i < arrowSize; i++) {
                    g.drawLine(i, mid - i, i, mid + i);
                }
                break;
            case SwingConstants.EAST:
                j = 0;
                for (i = arrowSize - 1; i >= 0; i--) {
                    g.drawLine(j, mid - i, j, mid + i);
                    j++;
                }
                break;
        }
        g.translate(-x, -y);
    }
}





Change JFrame image icon

import java.awt.Dimension;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Main extends JFrame {
  public static void main(String[] args) throws Exception {
    Main frame = new Main();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(new Dimension(300, 200));
    BufferedImage image = ImageIO.read(frame.getClass().getResource("/colors.jpg"));
    frame.setIconImage(image);
    frame.setVisible(true);
  }
}





Convert a non-RGB image to an RGB buffered image:

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
public class Main {
  public static void main(String[] argv) throws Exception {
    Image image = new ImageIcon("image.gif").getImage();
    BufferedImage bimage = new BufferedImage(image.getWidth(null), image
        .getHeight(null), BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bimage.createGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();
  }
}





Load an Icon from a jar

import javax.swing.Icon;
import javax.swing.UIManager;
public class Main {
  public static void main(String[] argv) throws Exception {
  }
  public static Icon getIconForType(int iconType) {
    switch (iconType) {
    case 0:
      return UIManager.getIcon("OptionPane.errorIcon");
    case 1:
      return UIManager.getIcon("OptionPane.informationIcon");
    case 2:
      return UIManager.getIcon("OptionPane.warningIcon");
    case 3:
      return UIManager.getIcon("OptionPane.questionIcon");
    }
    return null;
  }
}





Load image to ImageIcon and add it to Panel

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MainClass extends JFrame {
  public static void main(String[] args) {
    new MainClass();
  }
  public MainClass() {
    this.setTitle("Picture Application");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel1 = new JPanel();
    ImageIcon pic = new ImageIcon("your.jpg");
    panel1.add(new JLabel(pic));
    this.add(panel1);
    this.pack();
    this.setVisible(true);
  }
}





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





RGB Gray Filter

/*
 * Copyright (c) 2001-2009 JGoodies Karsten Lentzsch. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  o Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 *  o 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.
 *
 *  o Neither the name of JGoodies Karsten Lentzsch nor the names of
 *    its contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
 */

import java.awt.Image;
import java.awt.image.*;
import javax.swing.GrayFilter;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;

/**
 * An image filter that turns an icon into a grayscale icon. Used by
 * the JGoodies Windows and Plastic L&amp;Fs to create a disabled icon.<p>
 *
 * The high-resolution gray filter can be disabled globally using
 * {@link Options#setHiResGrayFilterEnabled(boolean)}; it is enabled by default.
 * The global setting can be overridden per component by setting
 * the client property key {@link Options#HI_RES_DISABLED_ICON_CLIENT_KEY}
 * to <code>Boolean.FALSE</code>.<p>
 *
 * Thanks to Andrej Golovnin for suggesting a simpler filter formula.
 *
 * @author Karsten Lentzsch
 * @version $Revision: 1.10 $
 */
public final class RGBGrayFilter extends RGBImageFilter {
    /**
     * Overrides default constructor; prevents instantiation.
     */
    private RGBGrayFilter() {
        canFilterIndexColorModel = true;
    }

    /**
     * Returns an icon with a disabled appearance. This method is used
     * to generate a disabled icon when one has not been specified.
     *
     * @param component the component that will display the icon, may be null.
     * @param icon the icon to generate disabled icon from.
     * @return disabled icon, or null if a suitable icon can not be generated.
     */
    public static Icon getDisabledIcon(JComponent component, Icon icon) {
        if (   (icon == null)
            || (component == null)
            || (icon.getIconWidth() == 0)
            || (icon.getIconHeight() == 0)) {
            return null;
        }
        Image img;
        if (icon instanceof ImageIcon) {
            img = ((ImageIcon) icon).getImage();
        } else {
            img = new BufferedImage(
                    icon.getIconWidth(),
                    icon.getIconHeight(),
                    BufferedImage.TYPE_INT_ARGB);
            icon.paintIcon(component, img.getGraphics(), 0, 0);
        }

        ImageProducer producer =
            new FilteredImageSource(img.getSource(), new RGBGrayFilter());
        return new ImageIcon(component.createImage(producer));
    }

    /**
     * Converts a single input pixel in the default RGB ColorModel to a single
     * gray pixel.
     *
     * @param x    the horizontal pixel coordinate
     * @param y    the vertical pixel coordinate
     * @param rgb  the integer pixel representation in the default RGB color model
     * @return a gray pixel in the default RGB color model.
     *
     * @see ColorModel#getRGBdefault
     * @see #filterRGBPixels
     */
    public int filterRGB(int x, int y, int rgb) {
        // Find the average of red, green, and blue.
        float avg = (((rgb >> 16) & 0xff) / 255f +
                     ((rgb >>  8) & 0xff) / 255f +
                      (rgb        & 0xff) / 255f) / 3;
        // Pull out the alpha channel.
        float alpha = (((rgb >> 24) & 0xff) / 255f);
        // Calculate the average.
        // Sun"s formula: Math.min(1.0f, (1f - avg) / (100.0f / 35.0f) + avg);
        // The following formula uses less operations and hence is faster.
        avg = Math.min(1.0f, 0.35f + 0.65f * avg);
        // Convert back into RGB.
       return (int) (alpha * 255f) << 24 |
              (int) (avg   * 255f) << 16 |
              (int) (avg   * 255f) << 8  |
              (int) (avg   * 255f);
    }
}