Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

D A

macrumors regular
Original poster
Nov 21, 2008
216
3
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 left, right;
   private JTextField mytext;
   public myMain()
   {
      // Creating GUI here...
   }
   public void main(String[] args)
   {
      myMain mainClass = new myMain();
      buttons myButtons = new buttons();
      myButtons.createButtons(myMain.left, myMain.right);
      // ...
   }
}
button
PHP:
public class buttons implements ActionListener
{
   public void createButtons(JPanel left, JPanel 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?
 
Make a method in the class with the object that does the change, and then call that class.method() from the other class.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.