简体   繁体   中英

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM