I'm new to swing, and was curious if anyone could point me in the right direction here. Cannot figure out how to make this repaint crap work, or if I'm supposed to be using repaint(), or what, to make this image get drawn to the background of my window. Here is my code that I have so far. It is drawing nothing at this point:

i

mport java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
 *
 * @author  
 * @version September 8, 2005, 11:54 PM
 */

 class MyPanel extends JPanel 
 {
        String imageFilePath =   "C:/MyDocuments/MemoryGame/woodTable.gif";
        ImageIcon icon;
        Image img;

        public MyPanel() 
        {
            icon = new ImageIcon(imageFilePath);
            img = icon.getImage();
        }

        public void paint(Graphics g) 
        {
            super.paint(g);
            g.drawImage(img, 300, 200, this);
        }
}

And Then My JFrame class

import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
 *
 * @author  
 * @version September 8, 2005, 10:40 PM
 */
public class memGame extends JFrame
{
    
    /** Creates a new instance of memGame */
    public memGame() 
    {
        super("Mario Memory Game");
        Container win = getContentPane();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(640,480);
        MyPanel mp = new MyPanel();
        mp.repaint();
        win.add(mp);
        
        JMenuBar menuBar = new JMenuBar();
        
        JMenu gMenu = new JMenu("Game");
        JMenu gMenu2 = new JMenu("Extra");
        
        JMenuItem newG = new JMenuItem("New Game");
        JMenuItem quit = new JMenuItem("Quit Game");
        JMenuItem help = new JMenuItem("Help");
        JMenuItem about = new JMenuItem("About");
        
        gMenu.add(newG);
        gMenu.add(quit);
        gMenu2.add(help);
        gMenu2.add(about);
        
        menuBar.add(gMenu);
        menuBar.add(gMenu2);
        setJMenuBar(menuBar);
    }
    
    public void ActionPerformed(ActionEvent e)
    {
    }
        
}

An lastly i have my main method which just calls an instance of my JFrame class, and then setVisibile(true)

If Anyone could tell me why it wont write the image, and how to remedy it, I would much appreciate. Thanks

Dani AI

Generated

A couple of small Swing gotchas are likely behind this. First, paint on a JPanel by overriding paintComponent, not paint, and always call super.paintComponent(g). Skipping super may appear to work sometimes (as noticed) but it breaks Swing’s paint pipeline and can cause flicker or components not to render correctly. Oracle’s tutorial points to paintComponent as the right place for custom painting. (docs.oracle.com)

Second, load the image in a way that fails fast and works on any OS. Avoid hard-coded C: paths; put the image on the classpath (e.g., in src/main/resources/images) and read it as a resource. Using ImageIO gives you a BufferedImage right away, so you are not waiting on asynchronous loading.

class BackgroundPanel extends JPanel {
  private final BufferedImage bg;

  BackgroundPanel() {
    try (InputStream in = getClass().getResourceAsStream("/images/woodTable.gif")) {
      bg = ImageIO.read(Objects.requireNonNull(in, "Missing /images/woodTable.gif"));
    } catch (IOException ex) {
      throw new UncheckedIOException(ex);
    }
    setOpaque(true);
  }

  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(bg, 0, 0, getWidth(), getHeight(), null); // scale to fill
  }
}

Quick checklist that ties back to comments from , , and :

  • Do not call repaint() manually here; add the panel, then show the frame. Repaint is scheduled automatically when needed. (docs.oracle.com)
  • Create and show your GUI on the Event Dispatch Thread with SwingUtilities.invokeLater to avoid intermittent issues. (docs.oracle.com)
  • If you prefer file paths during testing, use ImageIO.read(new File(...)) but switch to getResource for portability. (docs.oracle.com)
  • Drawing at (300,200) can put the image off where you expect; start at (0,0) and scale or tile as needed.

If the GIF is animated and you want it to animate, render it via an ImageIcon on a JLabel layered behind your game components; a BufferedImage render will be static.

Recommended Answers

All 8 Replies

It's probably not that the image isn't being drawn, it's that the image cannot be found.

Try this:
image = getImage(getDocumentBase(), "image.gif");


And make sure that the image is in the same file as the program.

I may be wrong here but do you need to 'escape' the path deliminators, like this:

String imageFilePath = "C:\\MyDocuments\\MemoryGame\\woodTable.gif";

The '\\' is not a typo. The first '\' escapes the second.

Kate

Remove the call to super.paintComponent(whatever it was). I spent 2 weeks trying to fix this once and found out that for some reason, calling that made the background disappear.
Example:

Your image is not being found. Probably the directory "C:/MyDocuments/MemoryGame/woodTable.gif"; doesn't exist.

If its in your documents folder then the correct directory would be:

C:/Documents and Settings/YOUR WINDOWS USER NAME HERE/My Documents/woodTable.gif.

For more help,

Okay, so long time not replying. Here's the deal.
One, I'm using Netbeans, and the image is being found, because netBeans raises bitchy errors if the image isn't found. So I don't believe it is that.

Two, that removal of the super.paint(g) call did nothing. It turned the screen white, instead of gray, which i suppose is something, but not what I need.

Three, the delimeters in netbeans do not need to be escaped. I've done files like this before and it's found them all. Something is wrong with my method, or with how I'm calling up the image once its been loaded. Somethign is missing. If someone has any more suggestions, I would like to know, because this looks logical to me.

My guess is the panel you're adding to the Frame isn't taking up the entire frame or the image isn't being found. The folloing code works fine on my machine.

public class ImageJPanel extends JPanel
{
	private Image aImage = null;
	
	public ImageJPanel()
	{
		init();
	}
	
	private void init()
	{
		File file = new File("D:\\Temp\\met_art_07_000891.jpg");
		System.out.println("file.exists(): " + file.exists());
		ImageIcon imageIcon = new ImageIcon(file.getAbsolutePath());
		aImage = imageIcon.getImage();
	}
	
	public void paint(Graphics g) 
    {
		super.paint(g);
        g.drawImage(aImage, 0, 0, this);
    }
}

Here is the frame using GridBagLayout.

public class ExtendedJFrame extends JFrame
{
	public ExtendedJFrame()
	{
		init();
	}
	
	public ExtendedJFrame(String title)
	{
		super(title);
		init();
	}
	
	private void init()
	{
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		setSize(640,480);
		
		GridBagLayout gbl = new GridBagLayout();
		getContentPane().setLayout(gbl);
		
		GridBagConstraints gbc = new GridBagConstraints();
		
		ImageJPanel panel = new ImageJPanel();
		gbc.gridx = 0;
		gbc.gridy = 0;
		gbc.weightx = 1;
		gbc.weighty = 1;
		gbc.fill = GridBagConstraints.BOTH;
		getContentPane().add(panel, gbc);
	}
}

Regards,

Nate

I still think it's the image is not being found. Can you do some system.out's to make sure that it's being found?

Ah, worked there! Thanks Nate. Dunno what was going on previously but works now. Strange. Anywho, thanks much!

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.