I agree completely with Paul. I'd also like to add that there isn't usually any compelling reason to subclass
JFrame, either. If you're going to be working with GUI code, it's better to start right. To start with, we'll not extend the
JFrame class anymore. Instead, we create an instance of
JFrame. This is done using SwingUtilities.invokeLater(Runnable) to ensure that our GUI code executes on the
Event Dispatch Thread (EDT). All GUI code should be handled on that thread only.
Next, we can add the rest of the code you had in the constructor. Note that I've moved
setVisible(boolean) to be the last call. It's better to call this only once all of the content has been added. pack() will make the frame as small as it can be while still fitting all of the components you want it to contain. You can move your
setSize(int, int) call to the
Panel1 class, instead. Try using
setPreferredSize() or overriding
getPreferredSize() rather that calling
setSize(). Doing it this way also has the added benefit of knowing exactly how big your canvas is: the panel with the button is 600 x 100 now, whereas before, the whole window was 600 x 100. The size of the panel is dependent on how much space is taken up by the frame's decorations.
Just for the sake of completeness, your fields can now probably just be local variables in
Panel1's constructor. It's generally a good idea to reduce the scope of your variables to the minimum they can be. There's less potential for accidents that way.
