Java Graphics How to - Draw a filled rectangle over an imageIcon using the coordinates of the image








Question

We would like to know how to draw a filled rectangle over an imageIcon using the coordinates of the image.

Answer

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
/*www. j  av  a  2 s. c  om*/
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

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

class TestPane extends JPanel {
  private BufferedImage myImage;
  private Rectangle myOffice = new Rectangle(150, 50, 30, 20);
  public TestPane() {
    try {
      myImage = ImageIO.read(new File("test.png"));
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  @Override
  public Dimension getPreferredSize() {
    return myImage == null ? new Dimension(200, 200) : new Dimension(
        myImage.getWidth(), myImage.getHeight());
  }

  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g.create();
    if (myImage != null) {
      int x = (getWidth() - myImage.getWidth()) / 2;
      int y = (getHeight() - myImage.getHeight()) / 2;
      g2d.drawImage(myImage, x, y, this);

      g2d.setColor(Color.RED);
      g2d.translate(x, y);
      g2d.draw(myOffice);
    }
    g2d.dispose();
  }
}