Java Graphics How to - Create BufferedImage and paint yourself








Question

We would like to know how to create BufferedImage and paint yourself.

Answer

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
//ww w .  ja va2s  . com
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main {

  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new MyPanel());
        f.pack();
        f.setVisible(true);
      }
    });
  }
}

class MyPanel extends JPanel {
  int W = 800;
  int H = 600;

  public MyPanel() {
    this.setLayout(new GridLayout());
    this.setPreferredSize(new Dimension(W, H));
    int w = W / 2;
    int h = H / 2;
    int r = w / 5;
    BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bi.createGraphics();
    g.setColor(Color.gray);
    g.fillRect(0, 0, w, h);
    g.setColor(Color.blue);
    g.fillRect(w / 2 - r, h / 2 - r / 2, 2 * r, r);
    g.dispose();
    this.add(new JLabel(new ImageIcon(bi), JLabel.CENTER));
  }

}