I have a class which contains a textfield and within that class an inner class containg the action performed method. On entering text and pressing enter, I would like the text to be assigned to a String “s” outside of the inner class that implements Action Listener. I want to use that string in another class.
public class Peaches extends JFrame {
private JTextField item1;
public Peaches() {
super("the title");
setLayout(new FlowLayout());
item1 = new JTextField(10);
add(item1);
thehandler handler = new thehandler(); //object of thehandler inner class
item1.addActionListener(handler);
// I want to use the textfield content here, or in other classes, updated
// with the new text everytime i hit enter after entering new text in the textfield
//String s = the content of the textfield
}
private class thehandler implements ActionListener { // inner class
@Override
public void actionPerformed(ActionEvent event) {
String string = "";
string = String.format(event.getActionCommand());
JOptionPane.showMessageDialog(null, string);
}
}
Is there any way of doing this? It must be possible to use the input of a text field in other parts of your program. I hope I make myself clear, thanks all.
EDIT
Thanks for the replies, so making the variable string a class variable instead of declaring it in the constructor allows the whole class to access it, simple but something i just didnt understand. Thanks Marko
I suggest you do it like this:
This uses an anonymous class, simpler than having dozens of inner classes around. Plus with these you can make closures (use local variables declared outside the anonymous class). And your string is there outside, so you can access it.