WIlopu
WIlopu

Reputation: 47

Image not showing in a JPanel

Here are my two code samples:

public class Display extends JPanel
{
    protected BufferedImage buffer;
    private static final long serialVersionUID = 1L;

    public Display()
    {
        super();
        //setBackground(Color.BLACK);
        buffer = new BufferedImage(PONG_WIDTH, PONG_WIDTH, BufferedImage.TYPE_INT_RGB);
    }

    protected void paintComponent(Graphics2D g)
    {
        super.paintComponent(g);
        g.drawImage(buffer, 0, 0, this);
    }
}

and

public class Server extends Display
{
    private static final long serialVersionUID = 1L;

    public Server() throws IOException
    {
        super();

        Graphics2D g = buffer.createGraphics();
        g.setBackground(Color.BLACK);
        g.setColor(Color.WHITE);
        g.fillRect(0, (PONG_HEIGHT-RACKET_HEIGHT)/2, RACKET_WIDTH, RACKET_HEIGHT);
        repaint();

EDIT: Add the mainmethod:

public class Test {
    public static void main(String args[])
    {
        JFrame f = new JFrame();
        f.setTitle("Test2");
        f.setSize(1000, 1000);
        f.setLocationRelativeTo(null);
        try{
            Server s = new Server();
            f.add(s); //or f.setContentPane(s);
            s.repaint();
            f.setVisible(true);

            s.play();
        }
        catch (IOException e){}
    }
}

Why does the panel shows up blank or black if I uncomment the second line of Display's constructor, when I draw several shapes in the subclass? I've been trying to find out the answer but every one of my attempts fell short.

Upvotes: 0

Views: 117

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347204

There is no such method protected void paintComponent(Graphics2D g) in the component hierarchy, it should actually be protected void paintComponent(Graphics g) <- Note the formal parameter requirements of the method

You should be calling Graphics#dispose on the Graphics context you created from the BufferedImage once you're done with it, this could prevent some platforms from rendering the image properly (as well as prevent the program from consuming system resources).

You should be creating and modifying the state of the UI only from within the context of the EDT, see Initial Threads for more details.

There's also need reason to extend directly from JFrame, apart from introducing confusion into you code, you're not actually adding any features to the class.

Upvotes: 2

Related Questions