0

I am using a JPanel and JFrame class to create simple graphics in a window and have found a rather odd problem. My current setup is as such:

import javax.swing.JFrame;

public class MyFrame extends JFrame{

    public MyFrame() {
        super("App Schmapp!");
        this.setSize(new java.awt.Dimension(500, 500));
        this.setMinimumSize(this.getSize());
        this.setMaximumSize(this.getSize());
        this.setVisible(true);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        MyPanel c = new MyPanel();
        MyFrame a = new MyFrame();
        a.add(c);
        c.repaint();

    }

}

Above is obviously my JFrame class and below is my JPanel class

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;

public class MyPanel extends JPanel {

    public void paintComponent(Graphics G) {
        super.paintComponent(G);
        Graphics2D g = (Graphics2D) G;
        g.setColor(Color.RED);
        g.fillRect(50, 50, 50, 50);
    }

}

My hope would be that this would work, however when I run this code a blank window pops up with no graphics. The part I don't understand is that if I changed the dimensions of the JFrame to something like 7000 by 10000 it works fine... please help?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373

1 Answers1

0

Replace c.repaint(); to:

a.pack();
a.setVisible(true);

It should show red square as you wish.

Maxim
  • 9,701
  • 5
  • 60
  • 108