Java - Working with separate classes

Discussion in 'Mac Programming' started by D A, Oct 22, 2009.

  1. D A
    macrumors regular

    Joined:
    Nov 21, 2008
    #1
    Due to the size of the code I've separated it into multiple classes (instead of having it all in one giant class).

    I have these classes:

    main class:
    creates gui

    button class:
    creates buttons

    calculation class:
    where all the actual 'work' takes place.

    My problem:
    I need to access a JTextField I created in the main class in the calculation class. The trouble is that calculation class is initialized in my button class, in the actionPerformed() function.

    How would I gain access to the JTextField in my calculation class? Should I pass it along while initializing the button class? Or some other way?


    Basic code of what I have now:

    main
    PHP:
    public class myMain extends JFrame
    {
       private 
    JPanel leftright;
       private 
    JTextField mytext;
       public 
    myMain()
       {
          
    // Creating GUI here...
       
    }
       public 
    void main(String[] args)
       {
          
    myMain mainClass = new myMain();
          
    buttons myButtons = new buttons();
          
    myButtons.createButtons(myMain.leftmyMain.right);
          
    // ...
       
    }
    }
    button
    PHP:
    public class buttons implements ActionListener
    {
       public 
    void createButtons(JPanel leftJPanel Right)
       {
          
    //Creating buttons here...
       
    }
       public 
    void actionPerformed(ActionEvent e)
       {
          
    calculation myCalc = new calculation();
          
    myCalc.performCalc();
       }
    }
    calculation
    PHP:
    public class calculation
    {
       public 
    void performCalc()
       {
          
    // Do stuff...
          
    updateTextField();
       }
       public 
    void updateTextField()
       {
          
    // Do stuff with text
          
    mytext.setText("The text");
       }
    }
    What do I need to change to be able to write to mytext in the class calculation?
     
  2. macrumors 6502a

    Joined:
    May 16, 2006
    #2
    Make a method in the class with the object that does the change, and then call that class.method() from the other class.
     

Share This Page