i wrote the following code to get a frame,button in south and a red color circle,which i got.In the "actionPerformed" method i wrote "setContentPane(mp2)" thinking it would put another panel on the frame with a blue circle but when i pushed the button,the button got stucked and the circled did not change.Can anyone explain why?
I always prefer to let my components decide how big they are. You set some
overall size with 'frame.setSize', but my experience is that this will make things
complicated whenever you want to resize some components.
The key to achieve what you want is to use 'frame.pack()', just before
puttng the frame to screen. That command makes the frame to ask all its
components what sizes they are, and then it determines the size of the frame.
So look at the next code:
and to make sure that the actionListener does indeed change the
contentpane, we use pack again:
(note: there are other ways to achieve this, but I find this way easiest).
Finally, it is nearly always a good idea to clear a panel first to its
backgroundcolor, before painting anything else on it. So for instance: