Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why can't I use getScaledInstance to scale images?

 
Howard Ting
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The statement I tried is as follows:

g.drawImage(new ImageIcon("chi_wei.jpg").getImage().getScaledInstance(100,100,Image.SCALE_DEFAULT),0,0,Color.WHITE,this);

But it ended up drawing nothing out.
Could somebody tell me if there's something wrong with the statement above or something I forget?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This sounds like a Swing/AWT question to me, so I'm going to move this to the Swing/AWT forum.
 
Craig Wood
Ranch Hand
Pie
Posts: 1535
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes — two things:
1 - You load a new image each time your paintComponent method calls drawImage. You only need to load the image one time so this line

belongs in your class constructor or a method called from it.

2 - in the test app below I originally put this line

inside paintComponent here

and the (System.out.println()) marker showed that paintComponent was being called repeatedly, so much so that the app would/could not repaint itself after being partially covered/uncovered by another window. The marker output in the console was

suggesting that the second instance of ImageScalingPanel loaded first and the first one went spastic.

So I looked in the getScaledInstance method detail to find this line: The new Image object may be loaded asynchronously even if the original source image has already been loaded completely. Apparently the attempt to load the scaled instance inside paintComponent was causing a runaway loop.

The code below works okay. Note what happens to the image quality for scale factors over 1.0.

[ August 10, 2004: Message edited by: Craig Wood ]
 
Howard Ting
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply, yet there's still the problem.
I copied the complete code to compile and run, but it can't still show the scaled picture. There was nothing in the window, just as before.
How in the world can I solve this problem? Is it because of my compiler?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic