I want to use a layout manager to layout several JButtons, JComboBoxes, etc.. I also want to use the paintComponent method to make a custom background for the JFrame rather than just the normal solid color background. For some reason, the JButtons and other component that have been added to the layout manager show correctly but the shapes that I have drawn in the background with paintComponent do not show up. How can I fix this?
Asked
Active
Viewed 65 times
-1

camickr
- 321,443
- 19
- 166
- 288
-
*How can I fix this?* - fix what? You have a problem with your painting code. Since you didn't post your [mre] showing what you did we can't really help. All we can do is suggest that you read the Swing tutorial on [Custom Painting](https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html) for the proper way to do the painting. Note a JFrame doesn't have a paintComponent() method. So first get the painting working, then add your components to the panel. – camickr Apr 28 '22 at 03:08
1 Answers
0
If you want to be able to use paintComponent with a layout manager you are not going to be able to do it from withing the class that extends the JFrame. I would recommend adding a JPanel to the JFrame and having the paintComponent method in the JPanel. The JPanel should have no problem using the paintComponent method with the layout manager. If you use setLayout with the JPanel then you should be able to exclude it from the layout manager.
I hope that this answers your question.

49KWIC
- 68
- 1
- 5
-
This does not completely work because when I use the setLayout null the JPanel does not seem to show up, but this has definitely put me on the right track for fixing my problem. Thank you! – CharlesThenotsogreatProgrammer Apr 28 '22 at 03:15
-
1@CharlesThenotsogreatProgrammer, Don't use a null layout. Swing was designed to be used with layout managers. The layout manager has nothing to do with the painting problem. First learn how to do custom painting properly. Read the tutorial. – camickr Apr 28 '22 at 03:17