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

JavaScript
JavaScript

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.

JavaScript

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.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement