• Post Reply Bookmark Topic Watch Topic
  • New Topic

Basic Organization of Swing Program

 
Mark Dexter
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've seen at least 3 basic ways to build a Swing program.

1. public class MyGUI extends JFrame {...}
2. public class MyGUI extends JPanel {...}
3. public class MyGUI {
// fields
JFrame frame;
JPanel panel; ... }

Most of the Sun Swing tutorial examples use method (2). To me, method (3) seems the most straightforward. Method (1) (used, for example by Bruce Eckel in "Thinking in Java") also makes some sense, since JFrame is the top-level component.

Is this purely a question of style and personal preference, or are there advantages to one approach over the other? Thanks. Mark Dexter
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24213
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Once you get a little experience using these classes, I think you'll see that these aren't really equivalent alternatives; you'll need some element of all of these in most of your Swing applications.

Subclassing JPanel (or another similar class) is what you must do to use custom painting. If you need to draw any kind of graphics, then you need to implement paintComponent() , and to do that, you need some subclass of JComponent. If you're not painting, then you don't need to do that.

Subclassing JFrame is something you'll have to do when you want to customize how a top-level window behaves. It's also something you'll see done in small example programs just because main() has to go somewhere; this isn't done that much in the real world, but it's convenient for small programs.

Creating independent classes with member variables holding frames and panels and things, as in your third alternative, is quite common. But of course it can be and is done in combination with the other two -- i.e., member variables holding subclasses of JFrame and JPanel etc.

So generally you should just use whatever is convenient and appropriate; you'll learn what that is over time.
 
Mark Dexter
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. That is very helpful. Mark Dexter
 
Brian Cole
Author
Ranch Hand
Posts: 920
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I usually use your 2nd approach, mostly because I've found it makes reuse slightly easier.

btw, in JDK7 or JDK8 you might be doing one of these:
  • public class MyGUI extends Application {...}
  • public class MyGUI extends SingleFrameApplication {...}


  • These are from JSR-296: Swing Application Framework. The project's intro page has some examples.

    As it happens, I just blogged a bit about JSR-296.
    [ June 12, 2007: Message edited by: Brian Cole ]
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!