Java 25 I can’t edit my comments anymore.
SolvedCCMBot -
Hello.
For a few days now, my comments are being rejected.
What I’m doing:
System.out.println(" name "+name);
Image im=createImage(500,700);
int imagew=im.getWidth(this);
int imageh=im.getHeight(this);
System.out.println(" imagew "+imagew+" imageh "+imageh);
gTTampon=im.getGraphics();
im=Toolkit.getDefaultToolkit().getImage(name);
System.out.println(" im "+im);
imagew=im.getWidth(this);
imageh=im.getHeight(this);
System.out.println(" **imagew "+imagew+" imageh "+imageh);
and here is the result:
name c:/Users/MASTER/Java/jk17/en_francais/application_puits_mar_2025/appli_puits_etats 2 et 3 dimensions.jpg image_comm sun.awt.image.ToolkitImage@436a4e4b
imagew 500 imageh 700
im sun.awt.image.ToolkitImage@436a4e4b
**imagew -1 imageh -1
In summary: the name is initially correct, the image creation is also correct (with the width and height reported). The image "im" also seems correct.
What’s odd is what comes out after the "toolkit" instruction: the widths and heights, which were correct before this instruction, become -1. In fact the "toolkit" instruction has set the width and height values to -1 to indicate there was a problem; which one????
The rest is obvious: I cannot display the comment included in "name". This has been going on for several days and I’m trying to figure out!
Thanks in advance for your help.
Benoît Delcourt.
2 answers
-
Hi,
It makes sense since the variable "name" is not initialized and therefore contains nothing.
We should see how you declare "name"
-
Hello!
It’s me, Bobot, the AI ready to surprise you!
It seems that your problem lies at the level of the Toolkit.getImage() instruction. This instruction loads an image asynchronously, which means that when it is called, it immediately returns an Image object without waiting for the image to be fully loaded.
That’s why you’re getting width and height values of -1, because the image isn’t ready yet at the moment you call getWidth() and getHeight().
One solution to this problem would be to use a MediaTracker to wait until the image is fully loaded before doing anything else. Here is an example of code that illustrates how to do this:
```java
MediaTracker m = new MediaTracker(this);
Image im = Toolkit.getDefaultToolkit().getImage(name);
m.addImage(im,0);
try {
m.waitForAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
int imageW = image.getWidth(this);
int imageH = image.getHeight(this);
```
This code adds the image to the MediaTracker, waits for all images to be loaded (that’s what m.waitForAll() does), then retrieves the image’s width and height.