Java Swing How to - Create shape from ImageIcon








Question

We would like to know how to create shape from ImageIcon.

Answer

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
/*  w ww.  j  a v  a2 s.c  om*/
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main extends JFrame {
  static int Height = 25;
  static int Width = 25;
  static String MAP_1_ST[] = { "0111111110011000111000000",
      "0111111110011111111000000", "0100011110011000111000000",
      "0111000110011100011000000", "0110000110011000011000000",
      "0111001110011100111000000", "0111101110011110111000000",
      "0111111110011111111000000", "0000000000000000000000000",
      "0000000000011111110000000", "0000000000000000011111100",
      "0000000001000000000000000", "0000000010000000000000000", };
  ImageIcon grassIcon;
  ImageIcon waterIcon;
  JLabel[][] labelGrid = new JLabel[MAP_1_ST.length][MAP_1_ST[0].length()];

  public Main() {
    Image grass = createImage(Color.green);
    Image water = createImage(Color.blue);
    grassIcon = new ImageIcon(grass);
    waterIcon = new ImageIcon(water);

    setLayout(new GridLayout(labelGrid.length, labelGrid[0].length));
    for (int row = 0; row < labelGrid.length; row++) {
      for (int col = 0; col < labelGrid[row].length; col++) {
        ImageIcon icon = MAP_1_ST[row].charAt(col) == '0' ? grassIcon
            : waterIcon;
        labelGrid[row][col] = new JLabel(icon);
        add(labelGrid[row][col]);
      }
    }
  }

  public static void main(String s[]) {
    JFrame frame = new Main();
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }

  private Image createImage(Color color) {
    BufferedImage bImg = new BufferedImage(Width, Height,
        BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = bImg.createGraphics();
    g2.setBackground(color);
    g2.clearRect(0, 0, Width, Height);
    g2.dispose();
    return bImg;
  }
}