Skip to content
Advertisement

JPanel not showing in JFrame, but JFrame still changes size

I don’t know what I did, or what went wrong, but a change I made at some point in the last while has made my JPanel completely invisible. The JFrame it’s nested in still changes in size to house it, and I can still toggle the content in the combobox.

In my desperation, I tried replacing the content of the SnakeSettingsPanel class with a single button, but the same thing happened – completely invisible, yet I can still interact with it. I figured it might be a computer error, so I tried restarting, but still nothing. When I tried adding a button to the frame outside of the JPanel, it worked just fine. What am I doing wrong?

JavaScript

Advertisement

Answer

Let this be a lesson on why you should avoid mixing Model (your application’s data) with View (how it is displayed). Your SnakeSettingsPanel is currently both.

  • As Model, it contains 3 important fields: width, height, and speed.
  • As View, it is a full JPanel. JPanels have a lot of fields which you should avoid touching directly. Including width and height, usually accessed via getHeight and getWidth — which you are overwriting with a version that always returns the same built-in values of 20 and 15 (until the user changes those values through a UI that they cannot see).

The fast fix is to rename your current getWidth() and getHeight() to avoid clashing with the built-in getWidth() and getHeight() methods of the parent JPanel class. Call them getMyWidth(), getMyHeight(), and suddenly everything works.

The better fix is to remove those fields and methods entirely, and store your own model attributes in a SnakeSettings attribute. Update it when the user clicks on play, and return it when it is requested via getSettings(). Less code for you, less chance of accidental name clashes with your parent JPanel class. This would look like:

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