Which is better for drawing JPGs on JLabel: ImageIcon or directly?
I'm currently using this everywhere.
BufferedImage bi;
Jlabel jLabel;
ImageIcon img =new ImageIcon( bi );
jLabel.setIcon(imgIcon);
but now I've discovered I can write images directly to the component from paintComponent( Graphics g )
(from a subclass of JLabel)
publicvoid paintComponent( Graphics g ){
super.paintComponent( g );
Graphics2D g2 = (Graphics2D)g;
BufferedImage bi=getBufImg();
g2.drawImage(bi, 0, 0, this.getWidth(), this.getHeight(),null );
Is this more efficient or better form? Should I update my code everywhere?
Also, the latter method seems to work the first time I call it, but I can't seem to change the image on an event like mouseEnter using code like this:
publicvoid mouseEntered(MouseEvent e){
Graphics g = this.getGraphics();
Graphics2D g2 = (Graphics2D)g;
BufferedImage bi=getBufImg();
g2.drawImage(bi, 0, 0, this.getWidth(), this.getHeight(),null );
}
what's wrong?
[1350 byte] By [
mixersofta] at [2007-11-27 6:39:18]

# 4
Is this more efficient or better form?
No.
Should I update my code everywhere?
It depends on what you want to do. If you want to show an image then ImageIcon is an easy way. Override paintComponent when you want to do something other than simply display the image, eg, write text on top of the image or alter the image with things like rotation and scaling.
Also, the latter method seems to work the first time I call it, but I can't seem to change the image on an event like mouseEnter using code like this
Don't put painting code inside event code. Painting/drawing code belongs in an appropriate painting method. Use member variables in the enclosing class for state, manipulate these from your event code and set up your painting method to be able to accurately render this state at any time.
stephensk8s is correct about the mouseEntered method. It works for components. So using a simple JLabel with ImageIcon is a carefree way to achieve rollover affects.
Creating this kind of thing for custom graphics and images takes a little more effort. It all depends on what you are trying to do.
Is there a good place to go to get a better understanding of this, or just ask on this forum?
Ask when you need help.
Resources that may be helpful to get started:
[url=http://java.sun.com/docs/books/tutorial/uiswing/events/index.html]Lesson: Writing Event Listeners[/url]
[url=http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html]Lesson: Performing Custom Painting[/url]
[url=http://java.sun.com/docs/books/tutorial/uiswing/components/icon.html]How to Use Icons[/url]
[url=http://java.sun.com/docs/books/tutorial/2d/images/index.html]Lesson: Working with Images[/url]
[url=http://java.sun.com/developer/JDCTechTips/]Core Java Technologies Tech Tips[/url].