Java Graphics How to - Paint 2 images side-by-side








Question

We would like to know how to paint 2 images side-by-side.

Answer

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.net.URL;
//ww  w .j  ava2s.c  o  m
import javax.imageio.ImageIO;
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() {
      public void run() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        try {
          frame.add(new MyPanel());
        } catch (Exception e) {
          e.printStackTrace();
        }
        frame.setSize(250, 250);
        frame.setVisible(true);
      }
    });
  }
}

class MyPanel extends JPanel {
  public MyPanel() throws Exception {
    setLayout(new FlowLayout());
    int size = 100;

    URL url = new URL("http://www.java2s.com/style/download.png");
    BufferedImage bi = ImageIO.read(url);
    
    Image left = createImage(size, Color.YELLOW);
    
    Image merged = merge(left, bi);

    add(new JLabel(new ImageIcon(merged)));
  }

  public static Image createImage(int size, Color color) {
    BufferedImage image = new BufferedImage(size, size,
        BufferedImage.TYPE_INT_RGB);
    Graphics2D g = image.createGraphics();
    g.setColor(color);
    g.fillRect(0, 0, size, size);
    g.dispose();
    return image;
  }

  public static Image merge(Image left, Image right) {
    BufferedImage merged = new BufferedImage(left.getWidth(null)
        + right.getWidth(null), left.getHeight(null),
        BufferedImage.TYPE_INT_RGB);
    Graphics2D g = (Graphics2D) merged.getGraphics();
    g.drawImage(left, 0, 0, null);
    g.drawImage(right, left.getWidth(null), 0, null);
    return merged;
  }
}