简体   繁体   中英

Trying to print image without frame

public class Main{
    public static void main(String []args){
        JLabel c=new JLabel();
        c.setIcon(new ImageIcon("picture.png"));
        JFrame frame = new JFrame();
        frame.setBackground(Color.WHITE);
        frame.setUndecorated(true);
        frame.getContentPane().add(c);
        frame.pack();
        BufferedImage bi = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D graphics = bi.createGraphics();
        c.print(graphics);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        graphics.dispose();
        frame.dispose();
    }
}

Hi all! I am simply trying to print an image without any frame onto the screen. This code should, I think, print the image to the screen; wait two seconds and then dispose of it. What am I doing wrong?

BTW I get no errors whatsoever, the program just stays alive for 2 seconds then dies.

Your image is in your JLabel. Why should it be printed on your screen if the frame where JLabel is is not showing?

You are already setting the frame undecorated. Setting visible on the frame, will work.

You don't need the Graphics part at the end and also you forgot to call setVisible(true);

public class Main{
    public static void main(String []args){
        JLabel c=new JLabel();
        c.setIcon(new ImageIcon("picture.png"));
        JFrame frame = new JFrame();
        frame.setBackground(Color.WHITE);
        frame.setUndecorated(true);
        frame.getContentPane().add(c);
        frame.pack();
        frame.setVisible(true);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        frame.dispose();
    }
}

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