Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7769105
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T16:04:51+00:00 2026-06-01T16:04:51+00:00

I have a swing gui application. I want to type into a image path

  • 0

I have a swing gui application. I want to type into a image path and then click button to load the image into a jpanel. The problem is it won’t be loaded, but if I add the extended jpanel which is able to load image when I instiate the jframe, image can be loaded normally. why is that?

code related:

package com.xdg.graphic;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class ImageLoader extends JPanel {
    private String imgPath;
    private BufferedImage image;


    public ImageLoader(String imgPath) {
        this.imgPath = imgPath;
        try {
            this.image=ImageIO.read(new File(imgPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void paint(Graphics g) {
        g.drawImage(image, 0, 0, null);
    }

    @Override
    protected void paintComponent(Graphics g) {
        g.drawImage(image, 0, 0, null);
    }

    public Dimension getPreferredSize() {
        if (image == null) {
             return new Dimension(100,100);
        } else {
           return new Dimension(image.getWidth(null), image.getHeight(null));
       }
    }

    public String getImgPath() {
        return imgPath;
    }

    public void setImgPath(String imgPath) {
        this.imgPath = imgPath;
    }



}

invoker class:

package com.xdg.image;

import com.xdg.graphic.ImageLoader;
import sun.awt.windows.ThemeReader;

import java.awt.*;

public class FrmImgCropper extends javax.swing.JFrame {
    private ImageLoader imageLoader;

    /** Creates new form FrmImgCropper */
    public FrmImgCropper() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    //GEN-BEGIN:initComponents
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        tfImagePath = new javax.swing.JTextField();
        btnPreview = new javax.swing.JButton();
        tfRatioW = new javax.swing.JTextField();
        tfRatioH = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        btnLoad = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btnPreview.setText("Preview");

        jLabel1.setText(":");

        btnLoad.setText("Load");
        btnLoad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoadActionPerformed(evt);
            }
        });

        jLabel2.setText("Image Path:");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(jPanel2Layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(
                        jPanel2Layout
                                .createSequentialGroup()
                                .addGap(34, 34, 34)
                                .addComponent(tfRatioW, javax.swing.GroupLayout.PREFERRED_SIZE, 55,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(tfRatioH, javax.swing.GroupLayout.PREFERRED_SIZE, 53,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 123,
                                        Short.MAX_VALUE)
                                .addComponent(btnLoad, javax.swing.GroupLayout.PREFERRED_SIZE, 82,
                                        javax.swing.GroupLayout.PREFERRED_SIZE).addGap(46, 46, 46)
                                .addComponent(btnPreview).addGap(276, 276, 276))
                .addGroup(
                        jPanel2Layout.createSequentialGroup().addGap(66, 66, 66).addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(tfImagePath, javax.swing.GroupLayout.DEFAULT_SIZE, 593, Short.MAX_VALUE)
                                .addGap(29, 29, 29)));
        jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(
                        javax.swing.GroupLayout.Alignment.TRAILING,
                        jPanel2Layout
                                .createSequentialGroup()
                                .addContainerGap(20, Short.MAX_VALUE)
                                .addGroup(
                                        jPanel2Layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(jLabel2)
                                                .addComponent(tfImagePath, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(18, 18, 18)
                                .addGroup(
                                        jPanel2Layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(jLabel1)
                                                .addComponent(tfRatioW, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(tfRatioH, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(btnPreview).addComponent(btnLoad)).addGap(20, 20, 20)));

        getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH);

        pack();
    }// </editor-fold>
    //GEN-END:initComponents

    private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) {
        if (imageLoader == null) {
            imageLoader = new ImageLoader(tfImagePath.getText());
            imageLoader.setBackground(Color.green);

            getContentPane().add(imageLoader, BorderLayout.CENTER);
            getContentPane().repaint();
            this.repaint();//image does not show up this way dnamically
        } else {
            imageLoader.setImgPath(tfImagePath.getText());
            imageLoader.repaint();
        }

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {

                FrmImgCropper cropper = new FrmImgCropper();
                cropper.getContentPane().add(new ImageLoader("i:\\temp4\\car.jpg"));  //if I add the image loader here directly,image shows up
                cropper.setSize(800, 900);
                cropper.setVisible(true);
            }
        });
    }

    //GEN-BEGIN:variables
    // Variables declaration - do not modify
    private javax.swing.JButton btnLoad;
    private javax.swing.JButton btnPreview;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField tfImagePath;
    private javax.swing.JTextField tfRatioH;
    private javax.swing.JTextField tfRatioW;
    // End of variables declaration//GEN-END:variables

}

any ideas? I’ve been working on it two hours.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T16:04:52+00:00Added an answer on June 1, 2026 at 4:04 pm

    To update your panel you should call revalidate() method on panel’s parent, not repaint() on the new panel since you change the content itself (the panel) but the image. In your case its content pane, which content should be validated.

    But its still not the best way to update the image inside the panel if you ask me…
    You can try this simple example (its much more simple and works perfectly):

    private static BufferedImage image = null;
    
    public static void main ( String[] args )
    {
        final JFrame imageFrame = new JFrame ();
        imageFrame.setLayout ( new BorderLayout () );
    
        final JPanel panel = new JPanel ()
        {
            protected void paintComponent ( Graphics g )
            {
                super.paintComponent ( g );
    
                if ( image != null )
                {
                    g.drawImage ( image, getWidth () / 2 - image.getWidth () / 2,
                            getHeight () / 2 - image.getHeight () / 2, this );
                }
            }
        };
        imageFrame.add ( panel, BorderLayout.CENTER );
    
        imageFrame.add ( new JButton ( "Load image" )
        {
            {
                addActionListener ( new ActionListener ()
                {
                    public void actionPerformed ( ActionEvent e )
                    {
                        JFileChooser fc = new JFileChooser ();
                        fc.setDialogType ( JFileChooser.OPEN_DIALOG );
    
                        if ( fc.showOpenDialog ( imageFrame ) == JFileChooser.APPROVE_OPTION )
                        {
                            try
                            {
                                image = ImageIO.read ( fc.getSelectedFile () );
                                panel.repaint ();
                            }
                            catch ( IOException e1 )
                            {
                                //
                            }
                        }
                    }
                } );
            }
        }, BorderLayout.SOUTH );
    
        imageFrame.setSize ( 500, 500 );
        imageFrame.setLocationRelativeTo ( null );
        imageFrame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
        imageFrame.setVisible ( true );
    }
    

    The only actual thing you need to do if you change the image inside panel – repaint the affected panel rect (or the whole panel if you don’t like to get deep into the way graphics in Swing works).

    As you can see i didn’t even touch the panel itself – just changed the image source.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm developing Swing application, and everything works fine usually. But I have an GUI
I have made a java swing GUI. Now I want to display a static
I am creating one GUI in swing Java. I have to use one button
I have created a Swing Application- GUI containing fields like TextFields, Labels, CheckBoxes and
I have written a swing application in Java and want to display the logo
I have designed a GUI connect to DB button using Swing in java now
We have a huge Java Swing application. Now we want to remove couplings from
I have a small java application with a swing gui. I have set a
I have implemented a standalone java application which uses the swing framework for GUI.As
I am developing desktop GUI application using java swing. And I want to show

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.