This week I’ve been doing a bit of Unit 8, which is about threads, but I’ve decided to go back to the material we covered in Unit 6, and hopefully consolidate my understanding of layout managers. I did fairly well with the practical exercises in that unit, but I still feel like I don’t fully grasp how to use layout managers effectively.

So, my first layout experiment has been about displaying two JPanels, with the bigger one taking up the top three-quarters of the frame. Which sounds pretty simple, I know, but it took me a while to get it to work. Initially, no matter what layout manager I used, my top panel displayed as a tiny section of itself:

Layout Experiment 1

It turns out (thanks to several Google searches) that the problem was my use of setSize() rather than setPreferredSize(). As I understand it, setSize() is setting the size of the JPanel to my intended 200×220 – but then the layout manager is applying its own approximation of the appropriate size for the component. Using setPreferredSize() instead seems to fix this, so now I have a lovely big JPanel on which to draw my terribly exciting animated ball:

Layout Experiment 2

Now, if I can resist the temptation to spend all morning messing about with bouncing, colour-changing, growing, shrinking, animated balls – the next thing on the agenda is getting to grips with GridBagLayout

Advertisements