Skip to content
Advertisement

Rectangle shows up only after resizing on JFrame

I have some experience with Java but I am new with Swing. I am trying to run a very simple example but I run into an annoying problem that I cannot solve.

I am trying to open a white window and draw a blue rectangle. Somehow, the rectangle only shows up after I manually resize the window. I have tried multiple things like unvalidate then validate, changing the visibility, but I cannot get my rectangle to show.

Here is the code of the JFrame and the main function

public class FieldView extends JFrame {

    public FieldView(String name) {
        super(name);
        
        getContentPane().setBackground(Color.WHITE);
        setSize(480, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        
    }
    
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.BLUE);
        g2d.drawRect(30, 50, 10, 10);

    }
}
public class AnimalApplication {

    public static void main(String[] args) {
        
        FieldView view = new FieldView("My view");
        view.setVisible(true);

    }

}

Note: I was reading this tutorial and I run into the same problem with the provided code.

Advertisement

Answer

You should create a JPanel that draws what you want. That JPanel should have a size preference.

class DrawPanel extends JPanel{
    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(Color.BLUE);
        g.drawRect(20, 20, 90, 90);
    }
    @Override
    public Dimension getPreferredSize(){
        return new Dimension(480, 200);
    }

}

Now we have a component that draws a rectangle and has a size. Create a JFrame add it to the layout and display the frame.

JFrame frame = new JFrame("holds my component");
DrawPanel panel = new DrawPanel();
frame.add( panel, BorderLayout.CENTER );
frame.pack();
frame.setVisible(true);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement