Displaying images on java Jframe

I switched from C # to java and was unable to display the image on the java Jframe. Is there any ImageBox component or JFrame method that displays an image Like this:

JPictureBox box=new JPictureBox("image_path");
JFrame fram=new JFrame();
fram.add(box); 

      

+3


source to share


1 answer


This code creates JFrame

and displays a file with an outline f

in this frame. He uses 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 probably want to handle exceptions better, set the image size (you can query the result ImageIO.read()

for .getWidth()

and .getHeight()

), etc.



Here's a slightly more complex example where an image is resized to fill its border:

    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 must recommend MadProgrammer's comprehensive posts on this topic. The only merit of this answer is its short length, but if you want to significantly improve scaling , aspect ratio scaling , or other detailed images, follow these links.

+1


source







All Articles