Krishan
Krishan

Reputation: 61

Why is JPanel not adding any component at Runtime?

public class Create_JFrame extends JFrame{

public Create_JFrame(){

     //Create a Frame
     JFrame Frame = new JFrame("Bla-Bla");
     JPanel Panel_1 = new JPanel();
     JPanel Panel_2 = new JPanel();
     JButton Option_1 = new JButton("Option-1");

     //Layout management for Panels
     Frame.getContentPane().add(BorderLayout.WEST, Panel_1);

     //Add button to Panel
     Panel_1.add(Option_1);

     //Registering Listeners for all my buttons
     Option_1.addActionListener(new ListenerForRadioButton(Panel_2));

     //Make the frame visible
     Frame.setSize(500, 300);
     Frame.setVisible(true);
}//end of Main
}//end of Class

public class ListenerForRadioButton implements ActionListener{

    JPanel Panel_2;
    JButton browse = new JButton("Browse");

    //Constructor, will be used to get parameters from Parent methods
    public ListenerForRadioButton(JPanel Panel){
        Panel_2 = Panel;
    }

    //Overridden function, will be used for calling my 'core code' when user clicks on button.
    public void actionPerformed(ActionEvent event){
        Panel_2.add(browse);
        System.out.println("My listener is called");
    }//end of method
}//end of class

Problem Statement:

I have 2 JPanel components in a a given JFrame. Panel_1 is having a Option_1 JButton. When user clicks on that I am expecting my code to add a JButton 'browse' in Panel_2 at runtime.

Runtime Output:

System is not adding any JButton in Panel_2. However, I see my debug message in output, indicating that system was successful in identifying user's click action on 'option-1'.

Question:

Why is JPanel not adding any component at Runtime?

Upvotes: 0

Views: 572

Answers (2)

Rahmat Waisi
Rahmat Waisi

Reputation: 1320

There are some reasons. but:

  • usually it's because of using unsuitable LayoutManager.
  • sometimes it's because of adding the JPanel to it's root component in worng way. which any operation (add, remove,...) works but is not visible.
  • you must refresh the view when you make some changes on it, like adding or removing components to/from it.

Upvotes: 0

Krishan
Krishan

Reputation: 61

Panel_2.add(browse);
Panel_2.revalidate();

adding a 'revalidate' will solve the problem.

Upvotes: 1

Related Questions