Search code examples
javaswingjframejinternalframe

switch between jframe and jinternalframe


Hi stackoverflow developers I have to design a form in swing having two menus on it . onclicking a menu i want to add a jinternal frame on it . and then after clicking a button on jinternalframe the jinternalframe should be removed and new control should be added on jframe form .

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

 class MainMenu extends JFrame implements ActionListener
   {
    JMenuBar mb;
    Menu field,test;
   MainMenu()
  {
  Container cp=this.getContentPane();
   mb= new JMenuBar();
  field1= new JMenu("field1");
  test=new JMenu("test");
  mb.add(field1);
  mb.add(test);

  setJMenuBar(mb);
  field1.addActionListener(this);
 test.addActionListener(this);


}

 public void actionPerformed(ActionEvent ae)
  {
    if(ae.getActionCommand().equals("field1");
   {
     jinternalframe1 frm= new jinternalframe();
     cp.add(frm);
      frm.setBounds(0,0,600,600);
   }

    }

   public static void main(String args[])
   {

   MainMenu frm = new MainMenu();
    frm.setSize(1000,1000);
   frm.setVisible(true);
   }


 }

public class jinternalframe1 extends JInternalFrame implements ActionListener
{

 JButton jb1,jb2;

 jinternalframe1()
{
jb1= new JButton("1");
jb2=new JButton("2");
 add(jb1);
 add(jb2);
 jb1.addActionListener(this);
jb2.addActionListener(this);


 }

 public void actionPerformed(ActionEvent ae)
  {
  if(ae.getActionCommand().equals("1"))
   {
     JButton nn= new JButton("back");
     MainMenu frm= new MainMenu();
    frm.cp.add(nn);
    //this is creating new Form but i want to add the new button control instead of add        //jinternal frame

    }
  }

}


Solution

  • Pass the instance of main form to your JInternalFrame

    jinternalframe1 frm= new jinternalframe(this); 
    

    Declare an object of MainMenu in the jinternalframe1 class to point to the main class object.

    MainMenu myParent;
    

    Modify your jinternalframe1 constructor to accept the MainMenu instance

     jinternalframe1(MainMenu parent){
    
       myParent = parent;
    
       //rest of your code
    }
    

    And then in your actionPerformed add the new button to myParent instance.

    if(ae.getActionCommand().equals("1")){
    myParent.add(new JButton("back"));
    }
    

    But let me tell you, this is not a good practice at all ! And as said by trashgod your code is not sscce Hope that helps you.