Ryan O'Mara wrote:we have been using the book Java for students
Java for Students (6th ed), Douglas Bell and Mike Parr, 2010, Pearson Education Canada
Java for Students (5th ed), Douglas Bell and Mike Parr, 2006, Prentice Hall
I found a table of contents for the 5th edition
on the web. It lists chapter 3 as "Using graphics methods," which is pretty darn early in the book. It's before chapters on methods (chapter 5), conditionals (7), loops (8), classes (9), and inheritance (10).
There are also downloadable code examples
and, sure enough, chapter three includes this example (and others which are similar).
There are plenty of things to quibble about here. It's not creating the GUI on the EDT*, which was normal before 2004, so maybe not a ding against this 2006 book. There's no real reason to extend JFrame here, especially since inheritance isn't until chapter 10, but no biggie. I guess I can accept implementing ActionListener (as opposed to having to declare another class, nested or otherwise) in chapter 3 of an introductory book. Why give the JPanel a preferred size when you could put it in the CENTER of a BorderLayout? Why is it calling the content pane "window" when that term usually means something else? And why use a JPanel when a JComponent would do just as well?
But calling panel.getGraphics().drawOval() in the ActionListener is pretty bad. Perhaps the authors knew it was bad and were just trying to construct a graphical program simple enough to appear in chapter 3 of an introductory book, but I don't think that's a valid excuse for this code. For one thing, this code is drawing this circle only transiently. If the program's frame is redrawn for any reason (perhaps because it was temporarily obscured by another window) then the circle will disappear until the user clicks the button again. So not only was this code not written the way Sun/Oracle says it should be, which should be enough for most of us, but this program flat out doesn't behave correctly.
It's a shame that there are so many books out there that are wrong. They do a disservice to the students who try to use them. And it's no fun for those trying to give good advice on forums such as CodeRanch.
footnote: *My book doesn't create the GUI on the EDT either. However it was published in 2002, before the swing single threading rule quietly changed.