Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice With JFrame Constructors?

In both my Java classes, and the books we used in them laying out a GUI with code heavily involved the constructor of the JFrame. The standard technique in the books seems to be to initialize all components and add them to the JFrame in the constructor, and add anonymous event handlers to handle events where needed, and this is what has been advocated in my class.

This seems to be pretty easy to understand, and easy to work with when creating a very simple GUI, but seems to quickly get ugly and cumbersome when making anything other than a very simple gui. Here is a small code sample of what I'm describing:

public class FooFrame extends JFrame {

   JLabel inputLabel;
   JTextField inputField;
   JButton fooBtn;
   JPanel fooPanel;

   public FooFrame() {
      super("Foo");

      fooPanel = new JPanel();
      fooPanel.setLayout(new FlowLayout());


      inputLabel = new JLabel("Input stuff");
      fooPanel.add(inputLabel);

      inputField = new JTextField(20);
      fooPanel.add(inputField);

      fooBtn = new JButton("Do Foo");
      fooBtn.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            //handle event
         }
      });
      fooPanel.add(fooBtn);

      add(fooPanel, BorderLayout.CENTER);
   }

}

Is this type of use of the constructor the best way to code a Swing application in java? If so, what techniques can I use to make sure this type of constructor is organized and maintainable? If not, what is the recommended way to approach putting together a JFrame in java?

like image 623
David Barry Avatar asked Apr 26 '10 21:04

David Barry


2 Answers

When you get a more complex UI I recommend that you separate different JPanels from the JFrame, so they become "modules" or "building blocks" of your user interface.

like image 160
Jonas Avatar answered Sep 20 '22 12:09

Jonas


Unfortunately there are a lot of bad books out there. And a lot of bad code.

You should not abuse inheritance by using it where not necessary. (Okay, there is the Double Brace idiom, which is complete inheritance abuse.) This applies to JFrame, JPanel, Thread and practically everything except java.lang.Object.

Also it is an extremely good idea to make fields private and where possible final. It turns out that references to components generally don't need to be stored in fields, at least not like this.

like image 31
Tom Hawtin - tackline Avatar answered Sep 21 '22 12:09

Tom Hawtin - tackline