Hi. Please could anyone help me look at this code and tell me why the image is not getting drawn? I have already cross-checked the path, and it is alright, as it does not throw any exception. Thanks in advance.

class PotPanel extends JPanel{
        public PotPanel(int width, int height){
            Dimension size = new Dimension(width, height);
            setPreferredSize(size);
            setMinimumSize(size);
            setMaximumSize(size);
            setSize(size);
            setLayout(null);
        }

        @Override
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            BufferedImage imoge = null;
            try {
                imoge = ImageIO.read(new File("C:\\projectPics\\seed1.png"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            g.drawImage(imoge, getWidth(), getHeight(), null);
        }
    }

ImageIO.read may return null rather than throwing an exception if, for example, it can't find a suitable decoder (not one of Sun's greatest decisions!) - so test for image == null after the read. You may also want to check what getWidth() and getHeight() are giving you there.

You didn't post the rest of your code, so it's possible the panel isn't being displayed at all - try changing its background color to check that.

ps: Your paintComponent may/will be called numerous times, so it's a bad idea to read the image file every time.

  • override getPreferredSize not setXxxSize

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(int, int);
    }
    
  • JPanel is ImageObserver, then null should be this

    g.drawImage(image, getWidth(), getHeight(), this);

  • its container (assume that JFrame) take it from JFrame.pack()

  • interesing is that you can to determine MinimumSize by

        JFrame.pack();
        // enforces the minimum size of both frame and component
        JFrame.setMinimumSize(getSize());
        //setMaximumSize(getMaximumSize());
        JFrame.setVisible(true);
    
  • note max size isn't possible to set

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.