Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You don't need to extend JFrame and in fact many of us who do a lot of Swing programming make it a point <em>not</em> 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.</p> <p>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.</p> <p>A silly example based on your code:</p> <pre><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(); } }); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload