#1
  1. User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2005
    Location
    UK
    Posts
    468
    Rep Power
    73

    Sending data to parent class


    Hi,
    In Java, if I have a main class that creates a new JFrame and then fills this with content from another class, is there a way to send data from the content class back to the main class?

    So this is my mainClass and main() function:
    Code:
    f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		f2.setResizable(false);
    		f2.setTitle("Control");
    		f2.setBounds(600, 200, 150, 65);
    		GameControl control=new GameControl();
    		f2.getContentPane().add(control);
    		f2.show();
    and then the content class is:

    Code:
    public class GameControl extends JPanel implements ActionListener{
    
    	public GameControl(){
    
    		JButton roll;
    		roll = new JButton("Roll");
    
    		add(roll);
    
    		//roll.addActionListener(this);
    
    
    	}
    	public void actionPerformed(ActionEvent evt){
    
    	}
    }
    When the user click the Roll button, I want the function actionPerformed to call a function from the main class so that the game can continue.

    Am I going about this in the right way or is there a better approach?
    Any help would be greatly appreciated.
  2. #2
  3. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,711
    Rep Power
    347
    send data from the content class back to the main class?
    The Main class can call methods in the Content class to get data from it.


    want the function actionPerformed to call a function from the main class
    If the Main class passed a reference to itself (this) to the GameControl class's constructor when it created the instance of that class, then a method in the GameControl class could use that reference to call a method in the Main class.
  4. #3
  5. Lord of the Dance
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Oct 2003
    Posts
    3,575
    Rep Power
    1906
    You can have the calling (main) class as parameter in GameControl.
    Main:
    Code:
    GameControl control=new GameControl(this);
    GameControl:
    Code:
    	MainClas callingClass
    	public GameControl(MainClass mc){
    		callingClass = mc;
    you can then use callingClass to call the function.

IMN logo majestic logo threadwatch logo seochat tools logo