Java Tutorial/Swing/Image ImageIcon

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

14. Getting Image object from ImageIcon object

import java.awt.Image;
import javax.swing.ImageIcon;
public class MainClass {
  public static void main(String[] a) {
    ImageIcon imageIcon = new ImageIcon("yourFile.gif");
    Image image = imageIcon.getImage();
  }
}





14. GrayFilter: Create a disabled version of an Image

import java.awt.Image;
import javax.swing.GrayFilter;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class CreateDiabledVersionOfanImage {
  public static void main(String[] a) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ImageIcon icon = new ImageIcon("yourFile.gif");
    Image normalImage = icon.getImage();
    Image grayImage = GrayFilter.createDisabledImage(normalImage);
    Icon warningIcon = new ImageIcon(grayImage);
    JLabel warningLabel = new JLabel(warningIcon);
    JLabel label3 = new JLabel("Warning", icon, JLabel.CENTER);
    frame.add(warningLabel,"Center");
    frame.add(label3,"South");
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}





14. use the image proxy. Images are only loaded when you press on a tab

import java.awt.ruponent;
import java.awt.Graphics;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
public class ProxyTester {
  public static void main(String[] args) {
    JTabbedPane tabbedPane = new JTabbedPane();
    for (String name : imageNames) {
      JLabel label = new JLabel(new ImageProxy(name));
      tabbedPane.add(name, label);
    }
    JFrame frame = new JFrame();
    frame.add(tabbedPane);
    frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
  private static final String[] imageNames = { "A.gif", "B.gif",
      "C.gif", "D.gif", "E.gif" };
  private static final int FRAME_WIDTH = 500;
  private static final int FRAME_HEIGHT = 300;
}
class ImageProxy implements Icon {
  public ImageProxy(String name) {
    this.name = name;
    image = null;
  }
  public void paintIcon(Component c, Graphics g, int x, int y) {
    ensureImageLoaded();
    image.paintIcon(c, g, x, y);
  }
  public int getIconWidth() {
    ensureImageLoaded();
    return image.getIconWidth();
  }
  public int getIconHeight() {
    ensureImageLoaded();
    return image.getIconHeight();
  }
  private void ensureImageLoaded() {
    if (image == null) {
      System.out.println("Loading " + name);
      image = new ImageIcon(name);
    }
  }
  private String name;
  private ImageIcon image;
}