javaswingnetbeansjinternalframe

How to close JInternal Frame Dynamically when object is created at runtime



Solution

  • I know it's pretty easy to do that but my case is difficult because i creats its object at run time, how can i do it.

    There's nothing magical about runtime that makes this any different from how you'd normally close it. The secret is in having a reference to the JInternalFrame readily available. A solution is to use a JInternalFrame field, a non-static instance variable, to hold the reference and not use a local variable as you're currently doing. The key here is to understand that references are what matter, much more so than variables. If you need a reference variable that persists when the method ends, then the variable cannot be declared within the method but should be on class scale.

    Something like:

    public class MyGui {
        // instance field to hold reference to currently displayed JInternalFrame
        private JInternalFrame currentInternalFrame = null;
    
        private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {        
            if (currentInternalFrame != null) {
                currentInternalFrame.dispose(); // clear current one
            }
    
            String st = TextField.getText().toString(); // in TextField i enter the JInternal Frame Name
            String clazzname = "practice."+st;         // practice is the package name  
            try {
    
                // JInternalFrame obj1 = (JInternalFrame) Class.forName( clazzname ).newInstance();
    
                currentInternalFrame = (JInternalFrame) Class.forName( clazzname ).newInstance();
    
                currentInternalFrame.setVisible(true);
                jPanel1.add(currentInternalFrame);           
            } catch(Exception e) {
                System.out.println("error "+e);
            }
        } 
    }
    

    Note that this code has not been tested and is not here for a copy-and paste solution but to give you a general idea.

    Another unrelated issue is on program design: users don't usually like windows opening and closing, and perhaps a better program structure for your user is to swap JPanel views via a CardLayout (please read the CardLayout Tutorial for more on this).