Why do we need to extend JFrame in a swing application?

You don’t need to extend JFrame and in fact many of us who do a lot of Swing programming make it a point not to extend this class. Myself, I try to extend classes where I plan on altering the innate behavior of the class — i.e., override one of the non-static methods of the class. Since I rarely have to do this for a JFrame, I’ll rarely want to extend it.

Another reason to avoid extending it: what if you later want to display the GUI you’ve just created in a JDialog or a JOptionPane or in another container as part of a complex GUI? If your class extends JFrame this will be hard to do. Myself, I try to gear my GUI classes towards creating JPanels so that this is much easier to do.

A silly example based on your code:

import javax.swing.*;

// this guy extends *nothing*
public class TunaExample {
   private static final int COLS = 10;
   private JPanel mainPanel = new JPanel(); // this is what I'll add to contentPane
   private JTextField field1 = new JTextField(COLS);
   private JTextField field2 = new JTextField(COLS);
   private JPasswordField passwordField = new JPasswordField(COLS);
   private JComponent[] allComponents = { new JLabel("Field 1:"), field1,
         new JLabel("Field 2:"), field2, new JLabel("Password:"), passwordField };

   public TunaExample() {
      field2.setEditable(false);
      field2.setFocusable(false);
      field1.setText("Field 1");
      field2.setText("Uneditable");

      for (JComponent comp : allComponents) {
         mainPanel.add(comp);
      }
   }

   public JComponent getMainComponent() {
      return mainPanel;
   }

   private static void createAndShowGui() {
      TunaExample tunaExample = new TunaExample();

      // creating my JFrame only when I need it and where I need it
      JFrame frame = new JFrame("Tuna Example");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(tunaExample.getMainComponent());
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Leave a Comment