2

How can I fill the following rectangle using an image? Can anyone help me please?

public void paintComponent(Graphics g) {
         setOpaque(false);  
        //Paint a filled rectangle at user's chosen point.
        if (point != null) {
            g.drawRect(0, 0,
                       rectWidth - 1, rectHeight - 1);
            g.setColor(Color.yellow);
            g.fillRect(1, 1,
                       rectWidth - 2, rectHeight - 2);
            }}

I tried this code but I couldn't find a way to make it work:

File imageFile = new File("duck.jpg");
BufferedImage img;
Graphics2D graph = img.createGraphics();
graph.setColor(Color.BLACK);
graph.fill(new Rectangle(1, 2, rectWidth, rectHeight));
graph.dispose();
ImageIO.write(img, "jpg", new File("duck.jpg"));
Dan
  • 863
  • 2
  • 23
  • 43
  • 3
    What do you create the variable `imageFile` for? Also, do you know what `dispose` means and did you read the comment of the method of the same name? – arne.b Mar 06 '13 at 13:00
  • 1
    Do you get a `NullPointerException` on this line by the way.. `Graphics2D graph = img.createGraphics();` – christopher Mar 06 '13 at 13:01

1 Answers1

3

You have to load an image into an Image object (like BufferedImage) and then call

graphics.drawImage()

on that image, giving the coordinates and other info.

Look in the tutorial for more info

Dariusz
  • 21,561
  • 9
  • 74
  • 114
  • 3
    I've tried your idea but it throws me an error: `Image img = Toolkit.getDefaultToolkit().getImage("duck.jpg"); int w = img.getWidth(null); int h = img.getHeight(null); BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); //Graphics g = bi.getGraphics(); g.drawImage(img, 0, 0, null);` – Dan Mar 06 '13 at 13:17
  • 3
    It's not an error, it's the line of code that throws it. Post the error. – Dariusz Mar 06 '13 at 13:25
  • 3
    `Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Width (-1) and height (-1) cannot be <= 0` and many many others after it – Dan Mar 06 '13 at 13:29
  • getWidth returns -1 if the width is not yet known. It means that the image is not loaded yet. Take a look at this http://stackoverflow.com/questions/3336558/getting-height-and-width-of-image-in-java-without-an-imageobserver – Dariusz Mar 06 '13 at 13:34