Reputation: 1145
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?
Upvotes: 1
Views: 1216
Reputation: 324118
No need for custom painting to show an image. See How to Use Icons.
The tutorial also has a section on "Custom Painting".
Upvotes: 3
Reputation: 10487
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.
Upvotes: 4