Monday, January 18, 2010

Adding, Removing and Changing Components in Panel | Java Swing

Recently I faced this problem of changing the components of the panel I’m using. I found this solution and thought of sharing it.

Adding, Removing componets from JPanel

Following is the code…
   1: package changepanel;
   3: /**
   4:  * @author HUNTER4U AKA SRIHARSHA
   5:  *
   6:  */
   7: public class Main {
   9:     public static void main(String[] args) {
  10:         new TestFrame().setVisible(true);
  11:     }
  12: }

   1: package changepanel;
   3: /**
   4:  * @author HUNTER4U AKA SRIHARSHA
   5:  *
   6:  */
   7: import java.awt.BorderLayout;
   8: import javax.swing.JFrame;
   9: import java.awt.event.ActionEvent;
  10: import java.awt.event.ActionListener;
  12: public class TestFrame extends JFrame{
  14:     FirstPanel firstPanel = new FirstPanel();
  15:     SecondPanel secondPanel = new SecondPanel();
  17:     public TestFrame(){
  19:         this.getContentPane().add(BorderLayout.NORTH, firstPanel);
  20:         this.getContentPane().add(BorderLayout.CENTER, secondPanel);
  22:         this.setSize(250, 150);
  23:         this.setLocation(250, 250);
  24:         this.setDefaultCloseOperation(EXIT_ON_CLOSE);
  25:         this.setResizable(false);
  27:         firstPanel.btnFirst.addActionListener(new BtnListener());
  28:     }
  31:     class BtnListener implements ActionListener{
  33:         public void actionPerformed(ActionEvent e) {
  35:             // REMOVE ALL THE COMPONENTS
  36:             //secondPanel.removeAll();
  39:             secondPanel.remove(secondPanel.btnSecond);
  40:             // BOTH WILL WORK HERE !!!
  42:             // ADD THE NEW COMPONENT
  43:             secondPanel.add(secondPanel.lblMsg);
  45:             // THIS IS INTRESTING PART...
  46:             secondPanel.revalidate();
  47:             secondPanel.repaint();
  48:         }
  49:     }
  50: }

   1: package changepanel;
   3: /**
   4:  * @author HUNTER4U AKA SRIHARSHA
   5:  *
   6:  */
   7: import javax.swing.JButton;
   8: import javax.swing.JPanel;
  10: public class FirstPanel extends JPanel{
  12:     JButton btnFirst = new JButton("Click me");
  14:     public FirstPanel(){
  15:         this.add(btnFirst);
  16:     }
  17: }

   1: package changepanel;
   3: /**
   4:  * @author HUNTER4U AKA SRIHARSHA
   5:  *
   6:  */
   7: import javax.swing.JButton;
   8: import javax.swing.JLabel;
   9: import javax.swing.JPanel;
  11: public class SecondPanel extends JPanel{
  13:     JButton btnSecond = new JButton("I'll Vanish !!!");
  14:     JLabel lblMsg = new JLabel("I ate ur BUTTON :P");
  16:     public SecondPanel(){
  17:         this.add(btnSecond);
  18:     }
  19: }

Well following is the explanation for revalidate() and repaint() I read while browsing the web.

  1. invalidate()/validate()/revalidate() only affects the layout. It results in a repaint if the layout actually changes.
  2. invalidate()/validate() is the mechanism for batching changes (like beginPaint, paint, paint, paint, endPaint of windowing SDKs). You mark, using invalidate(), all the components that might affect the layout as invalid. Then call the parent container's validate() method. In the validate() method the parent checks if at least one of its immediate children is invalid. If it finds a child marked invalid, it calls layoutComponents() on its layout manager.

    If the layoutmanager actually re-lays out the children, then, as a side effect, repaint() will get called.

    The thing to note here is that the Container only looks for invalid immediate children.

    For precisely this reason sometimes the resulting layout is not what you expected as the parent's parent and children's chidren may not get re-layed out. To work around this issue Swing added the revalidate() method.

  3. What revalidate() does is basically marks all the container upto the top level (window and its subclasses or applet) as invalid. Then it calls validate() on the top level.

Hope it helped you ;)


  1. Nice post ,, :) ,Giving lots of new information

  2. great job, first google result and saved my ass!

  3. Great work harsha...helped me a lot

  4. this is what I'm looking for..
    so what I need is revalidate and repaint..

  5. walangyaka gago ka

  6. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training Core Java 8 Training in Chennai Core java 8 online training JavaEE Training in Chennai Java EE Training in Chennai

  7. Java Online Training Java Online Training Java Online Training Java Online Training Java Online Training Java Online Training

    Hibernate Online Training Hibernate Online Training Spring Online Training Spring Online Training Spring Batch Training Online Spring Batch Training Online

  8. Thank you for every other great post. The place else may just anyone get that type of info in such a perfect way of writing? I ave a presentation next week, and I am at the look for such info.

    Powershell Online Training By Realtime Trainer In India

    Sap BW Hana Online Training By Realtime Trainer In India

    Sap Hana Online Training By Realtime Trainer In India

  9. Useful information. i am looking for SAP HANA Online Training from professional expert.

  10. I simply wanted to write down a quick word to say thanks to you for those wonderful tips and hints you are showing on this site.
    Best Devops online Training
    Online DevOps Certification Course - Gangboard

  11. Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic.
    Python Online training
    python Training in Chennai
    Python training in Bangalore

  12. Swing sets are a popular spring project for families with young, energetic children with energy to burn. Installing a swing set is not difficult but it does take more time and patience than most parents realize. Home owners should be realistic in estimating how much time they need to assemble the swing set and whether they have the time to complete the project. Get tips on the most common planning and preparation mistakes that can be avoided so everyone enjoys your families new swing set.backyard swing sets

  13. Do not pass by, go to the online casino and try your luck best casino slot Do you like to play online casino? Then come to us and win like the last day.