Solved

Data Transfer Between JFrame and child jPanel or various jFrames

Posted on 2011-09-19
7
2,862 Views
Last Modified: 2012-06-21
I seem to paint myself to the corner on many occasions while programming multi-frame and multi-class Java applications, so I certainly will take Expert Exchange member hmccurdy's advice and I will get  Drake's book "Data Structures and Algorithms.". Hopefully it will help me to come up with better design structures.

Lately I was experimenting and trying to understand the possibilities of data transfer between various classes in order to solve some problems I have a Java application, which is consisting of the following classes:

TestDataSharing.java - jFrame containing the main() method, with jLabels and jTestFields for entering and displaying data. Also a button to call data transfer methods, and a button to instantiate a child frame jFrame (if it doesn't exist) that contains the JPanel class called ChildPanel.java.

Main_Functionality.java - This class gets instantiated from the main jFrame TestDataSharing.java and would normally contain methods that process data entered through TestDataSharing.java GUI controls.

ChildPanel.java - This jPanel is used to provide the GUI for the jFrame instantiated from the main frame.

ChildPanel_Functionality.java - This class gets instantiated from ChildPanel.java jPanel  and would normally contain methods that process data entered through ChildPanel.java GUI controls.

GlobalValues.java - will contain STATIC variables and methods therefore they can be accessed from ANY other class, and can be called from any instances. The only catch is that
from a static method you cannot call a class instance method, so this really has to work as an intermediary that can be called from anywhere, the set fields here has to be called from the instances it connects separately.

If I make any static methods in classes in Main_Functionality.java or ChildPanel_Functionality.java they can be accessed

BUT!  There seems to no way to transfer data between the main jFrame TestDataSharing.java  and the child PANEL ChildPanel.java, because to update the GUI I would need to generate a captured action with an ActionListener such as pushing a button. And that would be a user action, that cannot be initiated from another independent class.

Is there a way to transfer data between a child panel and the mainframe or between multiple child panels, without this user interaction? (Essentially automatically update the GUI in one class with data entered in the other class?

Thank you.







 This is ascreenshot of the running program, to show Swing controls
package TestDataSharing;

import java.awt.Color;
import java.awt.Dimension;

import java.awt.Font;
import java.awt.Rectangle;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;


public class TestDataSharing extends JFrame {
    private JButton jbtnTransferData = new JButton();
    private JLabel jLabel4 = new JLabel();
    private JLabel jlblFromChildPanel = new JLabel();
    private JLabel jLabel6 = new JLabel();
    private JTextField jtfToChildPanel = new JTextField();
    
    public static JFrame childFrame;
    private static boolean childExists = false;
    private JButton jbtnOpenChildWindow = new JButton();
    
    // Create an instance of Main_Functionality class
    public Main_Functionality main_Functionality = new Main_Functionality();
    private JLabel jLabel1 = new JLabel();


    public TestDataSharing() {
        super("main frame");
        try {
            jbInit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void unsetChildExists() {
            childExists = false;
        }
    
    public static void main(String[] args) {
        TestDataSharing testDataSharing = new TestDataSharing();
        testDataSharing.setVisible(true); 
    }
    

    private void jbInit() throws Exception {
        this.getContentPane().setLayout( null );
        this.setSize(new Dimension(403, 307));
        jbtnTransferData.setText("Transfer Data");
        jbtnTransferData.setBounds(new Rectangle(135, 190, 135, 30));
        jbtnTransferData.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    jButton1_actionPerformed(e);
                }
            });
        jLabel4.setText("From Child_Panel:");
        jLabel4.setBounds(new Rectangle(20, 115, 165, 30));
        jLabel4.setFont(new Font("Tahoma", 1, 16));
        jlblFromChildPanel.setText("<data>");
        jlblFromChildPanel.setBounds(new Rectangle(195, 115, 190, 30));
        jlblFromChildPanel.setFont(new Font("Tahoma", 1, 16));
        jLabel6.setText("To Child_Panel:");
        jLabel6.setBounds(new Rectangle(20, 150, 165, 30));
        jLabel6.setFont(new Font("Tahoma", 1, 16));
        jtfToChildPanel.setBounds(new Rectangle(240, 155, 110, 20));
        jbtnOpenChildWindow.setText("Open Child Window");
        jbtnOpenChildWindow.setBounds(new Rectangle(87, 235, 225, 30));
        jbtnOpenChildWindow.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    jButton2_actionPerformed(e);
                }
            });
        jLabel1.setText("Main Frame");
        jLabel1.setBounds(new Rectangle(120, 25, 155, 60));
        jLabel1.setForeground(new Color(0, 0, 214));
        jLabel1.setFont(new Font("Tahoma", 1, 25));
        this.getContentPane().add(jLabel1, null);
        this.getContentPane().add(jbtnOpenChildWindow, null);
        this.getContentPane().add(jtfToChildPanel, null);
        this.getContentPane().add(jLabel6, null);
        this.getContentPane().add(jlblFromChildPanel, null);
        this.getContentPane().add(jLabel4, null);
        this.getContentPane().add(jbtnTransferData, null);
    }

    private void jButton1_actionPerformed(ActionEvent e) {
       System.out.println("Transfer data clicked"); 
       
        // Calling a Static method in a different class for temp storage of data
       GlobalValues.setGlobalTextString( jtfToChildPanel.getText());
       
       System.out.println(jtfToChildPanel.getText() + " value saved in GlobalValues Class");
           
        // But!  How do you make it load it into ChildPanel???
       
       // How do you makeit get it from childpanel???
        jlblFromChildPanel.setText(GlobalValues.getGlobalTextString2());
       
    }
    
    private void jButton2_actionPerformed(ActionEvent e) {
        if (childExists == false) {
                    childExists = true;
                    System.out.println("Child Opened");
                    ChildPanel.createAndShowGUI();
                } else {
                    childFrame.toFront();
                }
    }
}

Open in new window

package TestDataSharing;

import java.math.BigInteger;

import java.security.SecureRandom;

public class Main_Functionality {
    
    
    private String functionalityMain1;
    
    private SecureRandom random = new SecureRandom();

    public void setFunctionalityMain1(String functionalityMain1) {
        this.functionalityMain1 = functionalityMain1;
    }

    public String getFunctionalityMain1() {
        return functionalityMain1;
    }
    
    public static String nextRandomStringFromMainFunctionality()
    {
       // Will NOT work: because random() is NOT a static method 
       // it cannot be called from a static method
      //  return new BigInteger(130, random).toString(32);
        
        
        // This will work:
        
        // Math.round() and Math.random() are Static methods:
        String retString = Double.toString(Math.round(100*Math.random()));
        return retString;
    }
    
    public static void printFromChildWindow(String stringToPrint){
        
        System.out.println(stringToPrint + " printed from Child Window");
        
    }

    
    
}

Open in new window

package TestDataSharing;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class ChildPanel extends JPanel {

    private JLabel jLabel1 = new JLabel();
    private JLabel jLabel2 = new JLabel();
    private JLabel jLabel3 = new JLabel();
    private JTextField jTextField1 = new JTextField();
    private JTextField jTextField2 = new JTextField();
    private JLabel jLabel6 = new JLabel();
    private JLabel jLabel5 = new JLabel();
    private JLabel jLabel4 = new JLabel();
    private JButton jButton1 = new JButton();
    private JButton jButton2 = new JButton();
    
    ChildPanel_Functionality childPanel_Functionality = new ChildPanel_Functionality();

    public ChildPanel() {
        try {
            jbInit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
    public void jbInit() throws Exception {
        this.setLayout( null );
        this.setSize(new Dimension(535, 300));
        jLabel1.setText("From Main_Functionality:");
        jLabel1.setBounds(new Rectangle(20, 25, 220, 30));
        jLabel1.setFont(new Font("Tahoma", 1, 16));
        jLabel2.setText("<data>");
        jLabel2.setBounds(new Rectangle(275, 25, 230, 30));
        jLabel2.setFont(new Font("Tahoma", 1, 16));
        jLabel3.setText("To Main_Functionality:");
        jLabel3.setBounds(new Rectangle(20, 65, 220, 25));
        jLabel3.setFont(new Font("Tahoma", 1, 16));
        jTextField1.setBounds(new Rectangle(240, 70, 265, 20));
        jTextField2.setBounds(new Rectangle(240, 155, 265, 20));
        jLabel6.setText("To Main Frame:");
        jLabel6.setBounds(new Rectangle(20, 150, 165, 30));
        jLabel6.setFont(new Font("Tahoma", 1, 16));
        jLabel5.setText("<data>");
        jLabel5.setBounds(new Rectangle(275, 115, 230, 30));
        jLabel5.setFont(new Font("Tahoma", 1, 16));
        jLabel4.setText("From Main Frame:");
        jLabel4.setBounds(new Rectangle(20, 115, 165, 30));
        jLabel4.setFont(new Font("Tahoma", 1, 16));
        jButton1.setText("Transfer Data");
        jButton1.setBounds(new Rectangle(135, 210, 135, 30));
        jButton1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    jButton1_actionPerformed(e);
                }
            });
        jButton2.setText("Close Child Window");
        jButton2.setBounds(new Rectangle(85, 255, 230, 30));
        jButton2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    jButton2_actionPerformed(e);
                }
            });
        this.add(jButton2, null);
        this.add(jButton1, null);
        this.add(jLabel4, null);
        this.add(jLabel5, null);
        this.add(jLabel6, null);
        this.add(jTextField2, null);
        this.add(jTextField1, null);
        this.add(jLabel3, null);
        this.add(jLabel2, null);
        this.add(jLabel1, null);
        
        TestDataSharing.childFrame.addWindowListener(new WindowAdapter() {
        public void windowClosed(WindowEvent e) {
        TestDataSharing.unsetChildExists();
        System.out.println("Child Closed");
                        }       
                } );
    }
    
    
    public static void createAndShowGUI() {
           TestDataSharing.childFrame = new JFrame("Child Window");
 
           TestDataSharing.childFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
           
           ChildPanel childPanel = new ChildPanel();
           
           TestDataSharing.childFrame.setContentPane(childPanel);
           TestDataSharing.childFrame.setResizable(false);
           TestDataSharing.childFrame.setLocation(390, 50);
           TestDataSharing.childFrame.setSize(542,330);
           TestDataSharing.childFrame.setVisible(true);
       }

    private void jButton1_actionPerformed(ActionEvent e) {
        System.out.println("Child functionality transfer data clicked"); 
        
        // childPanel_Functionality is instantiated from this class
       //  jLabel2.setText(childPanel_Functionality.nextRandomString());
        
        // If the method accessed is Static in the class NOT associated with ChildPanel
        // The instance of the class is nor created in this class where the method is:
        // You can still get the data
        jLabel2.setText(Main_Functionality.nextRandomStringFromMainFunctionality());
        
        Main_Functionality.printFromChildWindow(jTextField1.getText());
        
        // It will be transfered to GlobalValues class field first
        GlobalValues.setGlobalTextString(jTextField2.getText());

        jLabel5.setText(GlobalValues.getGlobalTextString2());


    }
    
    
    
    private void jButton2_actionPerformed(ActionEvent e) {
        TestDataSharing.childFrame.dispose();     // close the child frame
    }
}

Open in new window

package TestDataSharing;

    import java.security.SecureRandom;
    import java.math.BigInteger;

public class ChildPanel_Functionality {
    
        private SecureRandom random = new SecureRandom();
    
    private String functionalityChildPanel1;

    public void setFunctionalityMain1(String functionalityCP) {
        this.functionalityChildPanel1 = functionalityCP;
    }

    public String getFunctionalityChildPanel() {
        return functionalityChildPanel1;
    }
    

      public String nextRandomString()
      {
        return new BigInteger(130, random).toString(32);
      }

    
}

Open in new window

package TestDataSharing;

public class GlobalValues {
    
    private static String globalTextString;
    private static String globalTextString2="GlobalString2";

    public static void setGlobalTextString(String globalTextString) {
        GlobalValues.globalTextString = globalTextString;
        
        // Problem:  you cannot call a method which is not static in ChildPanel.java class
        // Is there a way to update the GUI of childPanel instance from / with
        // globalTextString value???
        
        System.out.println("GlobalValues.setGlobalTextString() called");
        
    }

    public static String getGlobalTextString() {
        return globalTextString;
        
        // Well, this can be called from anywhere inside the childPanel jPanel,
        // including non-static methods.
        
        // BUT what method should I put it inside ChildPanel class to call
        // getGlobalTextString() method here???
        
    }

    public static void setGlobalTextString2(String globalTextString2) {
        GlobalValues.globalTextString2 = globalTextString2;
    }

    public static String getGlobalTextString2() {
        return globalTextString2;
    }
}

Open in new window

0
Comment
Question by:AttilaB
  • 6
7 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 36563615

Not going into details of your particular design - the obvuious answer is that if they are in one
Java application - there certaibnly is a way to have any kind of communications between differnt windows.

In my mind one of the normal way of doing it is to have say one class (maybe your main class of which you should have just one instance in your app)
carrying references to all your windows. And your winodws which were instaited from this class mostly should carry references to
the parent from which they were created. In this way whatever user does in any window you can prpagate to your "dispatcher" class and
from this class you can access any other window in your app - and do wahtever you want with the interface.

In general the MVC architecture has also to do with such situation,
but I prefer to think about it in this scheme of connections, which ssesm kind of more concrete to me.

0
 
LVL 47

Expert Comment

by:for_yan
ID: 36563767
package TestDataSharing;

import java.awt.Color;
import java.awt.Dimension;

import java.awt.Font;
import java.awt.Rectangle;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;


public class TestDataSharing extends JFrame {
    private JButton jbtnTransferData = new JButton();
    private JLabel jLabel4 = new JLabel();
    private JLabel jlblFromChildPanel = new JLabel();
    private JLabel jLabel6 = new JLabel();
    private JTextField jtfToChildPanel = new JTextField();

    public static JFrame childFrame;
    private static boolean childExists = false;
    private JButton jbtnOpenChildWindow = new JButton();

    // Create an instance of Main_Functionality class
    public Main_Functionality main_Functionality = new Main_Functionality();
    private JLabel jLabel1 = new JLabel();


    public TestDataSharing() {
        super("main frame");
        try {
            jbInit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void unsetChildExists() {
            childExists = false;
        }

    public static void main(String[] args) {
        TestDataSharing testDataSharing = new TestDataSharing();
        testDataSharing.setVisible(true);
    }


    private void jbInit() throws Exception {
        this.getContentPane().setLayout( null );
        this.setSize(new Dimension(403, 307));
        jbtnTransferData.setText("Transfer Data");
        jbtnTransferData.setBounds(new Rectangle(135, 190, 135, 30));
        jbtnTransferData.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    jButton1_actionPerformed(e);
                }
            });
        jLabel4.setText("From Child_Panel:");
        jLabel4.setBounds(new Rectangle(20, 115, 165, 30));
        jLabel4.setFont(new Font("Tahoma", 1, 16));
        jlblFromChildPanel.setText("<data>");
        jlblFromChildPanel.setBounds(new Rectangle(195, 115, 190, 30));
        jlblFromChildPanel.setFont(new Font("Tahoma", 1, 16));
        jLabel6.setText("To Child_Panel:");
        jLabel6.setBounds(new Rectangle(20, 150, 165, 30));
        jLabel6.setFont(new Font("Tahoma", 1, 16));
        jtfToChildPanel.setBounds(new Rectangle(240, 155, 110, 20));
        jbtnOpenChildWindow.setText("Open Child Window");
        jbtnOpenChildWindow.setBounds(new Rectangle(87, 235, 225, 30));
        jbtnOpenChildWindow.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    jButton2_actionPerformed(e);
                }
            });
        jLabel1.setText("Main Frame");
        jLabel1.setBounds(new Rectangle(120, 25, 155, 60));
        jLabel1.setForeground(new Color(0, 0, 214));
        jLabel1.setFont(new Font("Tahoma", 1, 25));
        this.getContentPane().add(jLabel1, null);
        this.getContentPane().add(jbtnOpenChildWindow, null);
        this.getContentPane().add(jtfToChildPanel, null);
        this.getContentPane().add(jLabel6, null);
        this.getContentPane().add(jlblFromChildPanel, null);
        this.getContentPane().add(jLabel4, null);
        this.getContentPane().add(jbtnTransferData, null);
    }

    private void jButton1_actionPerformed(ActionEvent e) {
       System.out.println("Transfer data clicked");

        // Calling a Static method in a different class for temp storage of data
       GlobalValues.setGlobalTextString( jtfToChildPanel.getText());

       System.out.println(jtfToChildPanel.getText() + " value saved in GlobalValues Class");

        // But!  How do you make it load it into ChildPanel???

       // How do you makeit get it from childpanel???

         ChildPanel.childPanel.getJTextField1().setText(jtfToChildPanel.getText());
        jlblFromChildPanel.setText(GlobalValues.getGlobalTextString2());

    }

    private void jButton2_actionPerformed(ActionEvent e) {
        if (childExists == false) {
                    childExists = true;
                    System.out.println("Child Opened");
                    ChildPanel.createAndShowGUI();
                } else {
                    childFrame.toFront();
                }
    }
}

Open in new window



package TestDataSharing;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class ChildPanel extends JPanel {

    private JLabel jLabel1 = new JLabel();
    private JLabel jLabel2 = new JLabel();
    private JLabel jLabel3 = new JLabel();
    private JTextField jTextField1 = new JTextField();
    private JTextField jTextField2 = new JTextField();
    private JLabel jLabel6 = new JLabel();
    private JLabel jLabel5 = new JLabel();
    private JLabel jLabel4 = new JLabel();
    private JButton jButton1 = new JButton();
    private JButton jButton2 = new JButton();
     static ChildPanel childPanel;

    ChildPanel_Functionality childPanel_Functionality = new ChildPanel_Functionality();

    public ChildPanel() {
        try {
            jbInit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void jbInit() throws Exception {
        this.setLayout( null );
        this.setSize(new Dimension(535, 300));
        jLabel1.setText("From Main_Functionality:");
        jLabel1.setBounds(new Rectangle(20, 25, 220, 30));
        jLabel1.setFont(new Font("Tahoma", 1, 16));
        jLabel2.setText("<data>");
        jLabel2.setBounds(new Rectangle(275, 25, 230, 30));
        jLabel2.setFont(new Font("Tahoma", 1, 16));
        jLabel3.setText("To Main_Functionality:");
        jLabel3.setBounds(new Rectangle(20, 65, 220, 25));
        jLabel3.setFont(new Font("Tahoma", 1, 16));
        jTextField1.setBounds(new Rectangle(240, 70, 265, 20));
        jTextField2.setBounds(new Rectangle(240, 155, 265, 20));
        jLabel6.setText("To Main Frame:");
        jLabel6.setBounds(new Rectangle(20, 150, 165, 30));
        jLabel6.setFont(new Font("Tahoma", 1, 16));
        jLabel5.setText("<data>");
        jLabel5.setBounds(new Rectangle(275, 115, 230, 30));
        jLabel5.setFont(new Font("Tahoma", 1, 16));
        jLabel4.setText("From Main Frame:");
        jLabel4.setBounds(new Rectangle(20, 115, 165, 30));
        jLabel4.setFont(new Font("Tahoma", 1, 16));
        jButton1.setText("Transfer Data");
        jButton1.setBounds(new Rectangle(135, 210, 135, 30));
        jButton1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    jButton1_actionPerformed(e);
                }
            });
        jButton2.setText("Close Child Window");
        jButton2.setBounds(new Rectangle(85, 255, 230, 30));
        jButton2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    jButton2_actionPerformed(e);
                }
            });
        this.add(jButton2, null);
        this.add(jButton1, null);
        this.add(jLabel4, null);
        this.add(jLabel5, null);
        this.add(jLabel6, null);
        this.add(jTextField2, null);
        this.add(jTextField1, null);
        this.add(jLabel3, null);
        this.add(jLabel2, null);
        this.add(jLabel1, null);

        TestDataSharing.childFrame.addWindowListener(new WindowAdapter() {
        public void windowClosed(WindowEvent e) {
        TestDataSharing.unsetChildExists();
        System.out.println("Child Closed");
                        }
                } );
    }


    public static void createAndShowGUI() {
           TestDataSharing.childFrame = new JFrame("Child Window");

           TestDataSharing.childFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

           childPanel = new ChildPanel();

           TestDataSharing.childFrame.setContentPane(childPanel);
           TestDataSharing.childFrame.setResizable(false);
           TestDataSharing.childFrame.setLocation(390, 50);
           TestDataSharing.childFrame.setSize(542,330);
           TestDataSharing.childFrame.setVisible(true);
       }

    public JTextField getJTextField1(){
       return  jTextField1;
    }

    private void jButton1_actionPerformed(ActionEvent e) {
        System.out.println("Child functionality transfer data clicked");

        // childPanel_Functionality is instantiated from this class
       //  jLabel2.setText(childPanel_Functionality.nextRandomString());

        // If the method accessed is Static in the class NOT associated with ChildPanel
        // The instance of the class is nor created in this class where the method is:
        // You can still get the data
        jLabel2.setText(Main_Functionality.nextRandomStringFromMainFunctionality());

        Main_Functionality.printFromChildWindow(jTextField1.getText());

        // It will be transfered to GlobalValues class field first
        GlobalValues.setGlobalTextString(jTextField2.getText());

        jLabel5.setText(GlobalValues.getGlobalTextString2());


    }



    private void jButton2_actionPerformed(ActionEvent e) {
        TestDataSharing.childFrame.dispose();     // close the child frame
    }
}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 36563777
I added line 105 in the first class above
and modified lines 30, 105 and added lines 114-116 in the secone class

Now when you click TranferData in the main whatever is in the toChildPanel appaears in To_Mina_Functionality of the child
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 47

Expert Comment

by:for_yan
ID: 36563840
In general it looks really convoluted.

Don't know people do it dufferently - I don't seee the reason to make
those window-classes static - ilike you child is static varaibale of the first class -  no reason for that and for mee looks confusing.

Then you start from one main class (and it may represent JFrame - like you main class) but then
create all other windows form this class and make them instance varibales of this class.
Then you'll be able to access all windows form this class.
And when creating these children pass them in the constructor reference to the cretaor
like
ChildPanel cp; // instance declaed at the head onf main class

somehwre in method or in constructor of main class

cp = new ChildPanel(this,.....);



then in the
ChildPanel

at the top instance varaibale

TestDataSharing parent;

public ChildPanel(TestDataSharing parent,....) {
this.parent = parent;
...

}

This would allow you form any place in ChilePnale to access metohods of parent class


And in your child classes provide methods like setTextFiistBox(String), setTextSecondBox(Strin) - or more meaningful names better
then from the main class having the handles (instances)  to all children you will be able in any child class
to set say any text, or say background color, or whatever - for which you'll have neccessary methods.
and if you have two-tier situation when the child created form the main class needs to create
another wiindow it will all also nbe manageable through these methods.

Something like that would be much more understandable, so it seems to me
0
 
LVL 47

Accepted Solution

by:
for_yan earned 500 total points
ID: 36563871
So now they ca go both ways - form parent to child and form child to parent

package TestDataSharing;

import java.awt.Color;
import java.awt.Dimension;

import java.awt.Font;
import java.awt.Rectangle;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;


public class TestDataSharing extends JFrame {
    private JButton jbtnTransferData = new JButton();
    private JLabel jLabel4 = new JLabel();
    private JLabel jlblFromChildPanel = new JLabel();
    private JLabel jLabel6 = new JLabel();
    private JTextField jtfToChildPanel = new JTextField();

    public static JFrame childFrame;
    private static boolean childExists = false;
    private JButton jbtnOpenChildWindow = new JButton();

    // Create an instance of Main_Functionality class
    public Main_Functionality main_Functionality = new Main_Functionality();
    private JLabel jLabel1 = new JLabel();


    public TestDataSharing() {
        super("main frame");
        try {
            jbInit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void unsetChildExists() {
            childExists = false;
        }

    public static void main(String[] args) {
        TestDataSharing testDataSharing = new TestDataSharing();
        testDataSharing.setVisible(true);
    }


    private void jbInit() throws Exception {
        this.getContentPane().setLayout( null );
        this.setSize(new Dimension(403, 307));
        jbtnTransferData.setText("Transfer Data");
        jbtnTransferData.setBounds(new Rectangle(135, 190, 135, 30));
        jbtnTransferData.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    jButton1_actionPerformed(e);
                }
            });
        jLabel4.setText("From Child_Panel:");
        jLabel4.setBounds(new Rectangle(20, 115, 165, 30));
        jLabel4.setFont(new Font("Tahoma", 1, 16));
        jlblFromChildPanel.setText("<data>");
        jlblFromChildPanel.setBounds(new Rectangle(195, 115, 190, 30));
        jlblFromChildPanel.setFont(new Font("Tahoma", 1, 16));
        jLabel6.setText("To Child_Panel:");
        jLabel6.setBounds(new Rectangle(20, 150, 165, 30));
        jLabel6.setFont(new Font("Tahoma", 1, 16));
        jtfToChildPanel.setBounds(new Rectangle(240, 155, 110, 20));
        jbtnOpenChildWindow.setText("Open Child Window");
        jbtnOpenChildWindow.setBounds(new Rectangle(87, 235, 225, 30));
        jbtnOpenChildWindow.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    jButton2_actionPerformed(e);
                }
            });
        jLabel1.setText("Main Frame");
        jLabel1.setBounds(new Rectangle(120, 25, 155, 60));
        jLabel1.setForeground(new Color(0, 0, 214));
        jLabel1.setFont(new Font("Tahoma", 1, 25));
        this.getContentPane().add(jLabel1, null);
        this.getContentPane().add(jbtnOpenChildWindow, null);
        this.getContentPane().add(jtfToChildPanel, null);
        this.getContentPane().add(jLabel6, null);
        this.getContentPane().add(jlblFromChildPanel, null);
        this.getContentPane().add(jLabel4, null);
        this.getContentPane().add(jbtnTransferData, null);
    }

    private void jButton1_actionPerformed(ActionEvent e) {
       System.out.println("Transfer data clicked");

        // Calling a Static method in a different class for temp storage of data
       GlobalValues.setGlobalTextString( jtfToChildPanel.getText());

       System.out.println(jtfToChildPanel.getText() + " value saved in GlobalValues Class");

        // But!  How do you make it load it into ChildPanel???

       // How do you makeit get it from childpanel???

         ChildPanel.childPanel.getJTextField1().setText(jtfToChildPanel.getText());
        jlblFromChildPanel.setText(GlobalValues.getGlobalTextString2());

    }

    public void  setText(String s){
              jtfToChildPanel.setText(s);
    }

    private void jButton2_actionPerformed(ActionEvent e) {
        if (childExists == false) {
                    childExists = true;
                    System.out.println("Child Opened");
                    ChildPanel.createAndShowGUI(this);
                } else {
                    childFrame.toFront();
                }
    }
}

Open in new window


package TestDataSharing;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class ChildPanel extends JPanel {
    TestDataSharing parent;

    private JLabel jLabel1 = new JLabel();
    private JLabel jLabel2 = new JLabel();
    private JLabel jLabel3 = new JLabel();
    private JTextField jTextField1 = new JTextField();
    private JTextField jTextField2 = new JTextField();
    private JLabel jLabel6 = new JLabel();
    private JLabel jLabel5 = new JLabel();
    private JLabel jLabel4 = new JLabel();
    private JButton jButton1 = new JButton();
    private JButton jButton2 = new JButton();
     static ChildPanel childPanel;

    ChildPanel_Functionality childPanel_Functionality = new ChildPanel_Functionality();

    public ChildPanel(TestDataSharing parent) {
        this.parent=parent;
        try {
            jbInit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void jbInit() throws Exception {
        this.setLayout( null );
        this.setSize(new Dimension(535, 300));
        jLabel1.setText("From Main_Functionality:");
        jLabel1.setBounds(new Rectangle(20, 25, 220, 30));
        jLabel1.setFont(new Font("Tahoma", 1, 16));
        jLabel2.setText("<data>");
        jLabel2.setBounds(new Rectangle(275, 25, 230, 30));
        jLabel2.setFont(new Font("Tahoma", 1, 16));
        jLabel3.setText("To Main_Functionality:");
        jLabel3.setBounds(new Rectangle(20, 65, 220, 25));
        jLabel3.setFont(new Font("Tahoma", 1, 16));
        jTextField1.setBounds(new Rectangle(240, 70, 265, 20));
        jTextField2.setBounds(new Rectangle(240, 155, 265, 20));
        jLabel6.setText("To Main Frame:");
        jLabel6.setBounds(new Rectangle(20, 150, 165, 30));
        jLabel6.setFont(new Font("Tahoma", 1, 16));
        jLabel5.setText("<data>");
        jLabel5.setBounds(new Rectangle(275, 115, 230, 30));
        jLabel5.setFont(new Font("Tahoma", 1, 16));
        jLabel4.setText("From Main Frame:");
        jLabel4.setBounds(new Rectangle(20, 115, 165, 30));
        jLabel4.setFont(new Font("Tahoma", 1, 16));
        jButton1.setText("Transfer Data");
        jButton1.setBounds(new Rectangle(135, 210, 135, 30));
        jButton1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    jButton1_actionPerformed(e);
                }
            });
        jButton2.setText("Close Child Window");
        jButton2.setBounds(new Rectangle(85, 255, 230, 30));
        jButton2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    jButton2_actionPerformed(e);
                }
            });
        this.add(jButton2, null);
        this.add(jButton1, null);
        this.add(jLabel4, null);
        this.add(jLabel5, null);
        this.add(jLabel6, null);
        this.add(jTextField2, null);
        this.add(jTextField1, null);
        this.add(jLabel3, null);
        this.add(jLabel2, null);
        this.add(jLabel1, null);

        TestDataSharing.childFrame.addWindowListener(new WindowAdapter() {
        public void windowClosed(WindowEvent e) {
        TestDataSharing.unsetChildExists();
        System.out.println("Child Closed");
                        }
                } );
    }


    public static void createAndShowGUI(TestDataSharing tds) {
           TestDataSharing.childFrame = new JFrame("Child Window");

           TestDataSharing.childFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

           childPanel = new ChildPanel(tds);

           TestDataSharing.childFrame.setContentPane(childPanel);
           TestDataSharing.childFrame.setResizable(false);
           TestDataSharing.childFrame.setLocation(390, 50);
           TestDataSharing.childFrame.setSize(542,330);
           TestDataSharing.childFrame.setVisible(true);
       }

    public JTextField getJTextField1(){
       return  jTextField1;
    }

    private void jButton1_actionPerformed(ActionEvent e) {
        System.out.println("Child functionality transfer data clicked");

        // childPanel_Functionality is instantiated from this class
       //  jLabel2.setText(childPanel_Functionality.nextRandomString());

        // If the method accessed is Static in the class NOT associated with ChildPanel
        // The instance of the class is nor created in this class where the method is:
        // You can still get the data
        jLabel2.setText(Main_Functionality.nextRandomStringFromMainFunctionality());

        Main_Functionality.printFromChildWindow(jTextField1.getText());

        parent.setText(jTextField2.getText());
        // It will be transfered to GlobalValues class field first
        GlobalValues.setGlobalTextString(jTextField2.getText());

        jLabel5.setText(GlobalValues.getGlobalTextString2());


    }



    private void jButton2_actionPerformed(ActionEvent e) {
        TestDataSharing.childFrame.dispose();     // close the child frame
    }
}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 36563984
look at this simple interaction between three windows - type something in
textbox and press the button next to it
and look at the code
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyMainWindow extends JFrame implements ActionListener {

      JTextField txt;
      JButton button;
      MyChildWindow child1;
      MyChildWindow child2;


    public MyMainWindow(){
        super("main");
     txt = new JTextField(10);
      button = new JButton("press");
        button.addActionListener(this);
            Container c = this.getContentPane();
        c.setLayout(new FlowLayout());
        c.add(txt);
        c.add(button);
          this.setSize(200,200);
        this.setLocation(100, 100);

      child1 = new MyChildWindow(this, 1);


           child2 = new MyChildWindow(this,2);


        child1.setVisible(true);
        child2.setVisible(true);
        this.setVisible(true);



    }
       public void setText(String s){
        txt.setText(s);
    }


    public void actionPerformed(ActionEvent e) {
            child1.setText(txt.getText());
          child2.setText(txt.getText());


    }

    public MyChildWindow getChild(int i){
        if(i==1)return child1;
        else return child2;
    }


    public static void main(String[] args) {
        new MyMainWindow();
    }


}

class MyChildWindow extends JFrame implements ActionListener {
    MyMainWindow parent;
       JTextField txt;
      JButton button;
    int num;

    public MyChildWindow(MyMainWindow parent, int num){
        super("child " + num );
        this.parent = parent;
        this.num = num;
           txt = new JTextField(10);
      button = new JButton("press");
           button.addActionListener(this);
        Container c = this.getContentPane();
          c.setLayout(new FlowLayout());
        c.add(txt);
        c.add(button);
        this.setSize(200,200);
        this.setLocation(num*200, num*200);

    }

    public void setText(String s){
        txt.setText(s);
    }

       public void actionPerformed(ActionEvent e) {
           parent.setText(txt.getText());
              MyChildWindow childNotMe = null;
           if(num == 1){
              childNotMe = parent.getChild(2);


           } else    childNotMe = parent.getChild(1);
           childNotMe.setText(txt.getText());



    }


}

Open in new window

0
 

Author Closing Comment

by:AttilaB
ID: 36564716
Thank you. I really enjoy reading your notes and learn a lot from them.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now