image not displaying in java frame
trying to learn windows programming in java, want to display a image to a frame.here is the problem code:
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("hello world");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,200);
开发者_如何转开发 Graphics graph = frame.getGraphics();
BufferedImage image = ImageIO.read(new File("data/image.jpg"));
graph.drawImage(image, 0,0,frame);
frame.pack();
frame.setVisible(true);
}
i have seen some successful examples subclass the Component class and call the Graphics.DrawImage method in the paint method. why do you have to do that, can't you just grab the Graphics object associated with the frame and draw the image directly?
You can't because that's not the way Swing painting works. For one thing, painting has to happen on the EDT, and the preferred way to achieve this is overriding the paintComponent(..)
method. Direct painting in the way you imagine is possible if you use full screen mode, though.
No need for custom painting to show an image. See How to Use Icons.
The tutorial also has a section on "Custom Painting".
精彩评论