Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image rendering on java Jframe

I have moved on from C# to java and unable to render the image on java Jframe. Is there any ImageBox component or JFrame method that render the image Like this:

JPictureBox box=new JPictureBox("image_path");
JFrame fram=new JFrame();
fram.add(box); 
like image 331
Cody Avatar asked May 16 '26 16:05

Cody


1 Answers

This code creates a JFrame and displays the file with path f in that frame. It uses a JLabel as one of the commenters suggests.

    public static void display(String f) throws Exception {
        JFrame jf = new JFrame();
        JLabel jl = new JLabel(new ImageIcon(ImageIO.read(new File(f))));
        jf.add(jl);
        jf.setBounds(0, 0, 200, 200);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

Note that you would probably want to handle exceptions better, set the size from the image (you can ask the result of ImageIO.read() for .getWidth() and .getHeight()), and so on.

Here is a slightly more complex example where the image changes size to fill its boundary:

    public static void display(final String f) throws Exception {
        JFrame jf = new JFrame();
        JPanel jp = new JPanel() {
            private BufferedImage bi = ImageIO.read(new File(f));
            public void paint(Graphics g) {
                Graphics2D g2 = (Graphics2D)g;
                RenderingHints rh = new RenderingHints(
                    RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                g2.setRenderingHints(rh);

                int w = getWidth();
                int h = getHeight();
                g.drawImage(bi, 0, 0, w, h, null);
            }
        };
        jf.add(jp);
        jf.setBounds(0, 0, 400, 200);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

Note: after reading the links in the comments, I have to recommend MadProgrammer's exhaustive posts on the topic. The only merit of this answer is its short length - but if you want much better down-scaling, ratio-preserving scaling or other in-depth image-related, follow those links.

like image 138
tucuxi Avatar answered May 19 '26 05:05

tucuxi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!