action listener as separate class... needs to access variables
I have a GUI that needs both an action listener and a change listener so i made them into separate classes. The problem is that I need to be able to access information entered by the user into the main GUI. Does anyone know how I can do this?
Here is a sample of what the action listener class looks like:
import java.awt.event.*;
class MyActionListenerimplements ActionListener{
publicvoid actionPerformed(ActionEvent e){
System.out.println("Action Listener affected.");
}
}
I'm a first year java student, so please be as explicit with you suggestions as possible.
Thanks.
-Ro
# 1
You're about to learn of the wonders of inner classes
public class GUI extends JPanel {
String value = "A value from the GUI class that you can access";
//Your GUI code
class listeningClass implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println(value);
}
}
}
So, we have an outer class called GUI and an inner class called listeningClass, which implements the ActionLIstener. The inner class can see all the variables and methods in the outer class but as far as I can remember the outer class can't see into the inner class.
Message was edited by:
RedUnderTheBed
# 2
> The problem is that I need to be able to access information entered by the user into the main GUI
Then you need access to the main GUI which you do by passing in a reference to the GUI when you create the ActionListener;
class MyActionListener implements ActionListener
{
JFrame myGui;
public MyActionListener(JFrame myGui)
{
this.myGui = myGui;
}
public void actionPerformed(ActionEvent e) {
// now you can access the frame from here using the myGui variable
System.out.println("Action Listener affected.");
}
}