-
drawing images
Hey all. I'm trying to finish the "image" button feature in my paint program. What I want it to do is prompt for an image, and then have that image be created by clicking twice in different spots and drawing it in the rectangle with the two points pressed representing opposite corners. Basically what I need to know how to do is draw an image onto a JPanel at a specified point and into a rectangle of specified dimensions, and have it stretch out to fit those dimensions.
Here's the code for my program: http://www.java-forums.org/new-java/...hed-paint.html
Thanks in advance...
-
i think this can help you
java.sun.com/docs/books/tutorial/2d/images/index.html
-
Thanks for the link. Working through it now. I'm a little confused by this example though:
Code:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
/**
* This class demonstrates how to load an Image from an external file
*/
public class LoadImageApp extends Component {
BufferedImage img;
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
public LoadImageApp() {
try {
img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
}
}
public Dimension getPreferredSize() {
if (img == null) {
return new Dimension(100,100);
} else {
return new Dimension(img.getWidth(null), img.getHeight(null));
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Load Image Sample");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.add(new LoadImageApp());
f.pack();
f.setVisible(true);
}
}
That was in the tutorial. The program, when I compiled and ran it, cause the image of the strawberry to appear. It is only drawn in the paint method though and I don't see any calls to that method. Why is it that it still was painted?
-
Essentially because "the GUI system" calls a component's paint() method whenever it needs to paint it.
-
Gotcha. Program finished. Thanks for the link :)