View Full Version : Java - Working with separate classes

Oct 22, 2009, 03:26 PM
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:


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);
// ...


public class buttons implements ActionListener
public void createButtons(JPanel left, JPanel Right)
//Creating buttons here...
public void actionPerformed(ActionEvent e)
calculation myCalc = new calculation();


public class calculation
public void performCalc()
// Do stuff...
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?

Oct 22, 2009, 03:28 PM
Make a method in the class with the object that does the change, and then call that class.method() from the other class.