Search code examples
javaswingjframesubclassjcomponent

how to add components to a subclass of a subclass of JFrame


I have a subclass of JFrame A. I have another class B which is the subclass of A. I want to add new components to frame B like JButtons. My code is as follows:

public B() extends A {
    //Calling super class constructor
    super();

    //Creating and adding a button 
    JButton btn = new JButton();
    this.add(btn);

    //other codes
}

When I display the frame, the button isn't added, and only the superclass frame and its components are displayed. How can I add those buttons in the subclass B's frame?

Update: Here is a condensed version of my code. I've used BorderLayout in super class ListObjects.

package assignment2;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ListAndModifyCustomer extends ListObjects {

public ListAndModifyCustomer() {
    //Calling super class constructor
    super("Customers");

    //Adding listener to the ok button
    super.selectBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            //codes to create another JFrame

            dispose();  //Closing the frame
        }
    });

    //Adding button to the panel
    super.panel.add(new JButton("NO"));

    JPanel jp = new JPanel();
    jp.add(super.selectBtn);

    super.add(jp, BorderLayout.SOUTH);
}
}

Solution

  • I found out that if we create a panel in the subclass and add all the items to that panel and add that panel to the frame of the super class then the components become visible.