Question

I'm working on a digital Pokemon card-like game. When I try to paint any of my images, the JFrame remains empty. It may be a simple error, but I have not been able to find a solution. On Stack Overflow, I have seen many issues like mine though their solutions don't work on my code. Here's the code: The class for the JFrame:

import javax.swing.JFrame;


public class Rocks extends JFrame{

public Rocks(){
    setVisible(true);
    setTitle("Rocks Card Game");
    setSize(1200,297);
    add(new Display());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
    new Rocks();
}

}

The JPanel Class:

    import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JPanel;


public class Display extends JPanel{
    Image granite;
    public Display(){
        granite = new ImageIcon("C:\\Users\\Raj\\Pictures\\Granite.png").getImage();
        setBackground(Color.black);
    }
    public void paint(Graphics g){
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawImage(granite,0,0,null);
    }
}
Was it helpful?

Solution 2

Move setVisible(true); to the bottom of the Rocks constructor.

Edit: Explanation on why setVisible() should be called last

OTHER TIPS

Is there a reason to extends JFrame if you don't have it, just don't. It's preferrable composition over inheritance. As @camickr commnent it's no needing of custom painting , you can just use JLabel and call setIcon.

public class Rocks{

private JFrame frame;

public Rocks(){
    frame = new JFrame();
    frame.setTitle("Rocks Card Game");
    frame.setSize(1200,297);
    //frame.add(new Display());
    //as camickr comment
    JLabel label = new JLabel(new ImageIcon("C:\\Users\\Raj\\Pictures\\Granite.png"));
    frame.add(label);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack(); // size components
    frame.setVisible(true); // make it visible
}
public static void main(String[] args) {
    new Rocks();
}

}

And the other thing you have to see if that Swing programs should override paintComponent() instead of overriding paint()

So (if you still want to use a panel) change your panel class like this

public class Display extends JPanel{
    Image granite;
    public Display(){
        granite = new ImageIcon("C:\\Users\\Raj\\Pictures\\Granite.png").getImage();
        setBackground(Color.black);
    }
    @Override // always add override annotation
    public void paintComponent(Graphics g){
        super.paintComponent(g); // always call super first
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawImage(granite,0,0,this);
    }
}

Read more : Painting in AWT and Swing components

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top