Puki Puki - 1 year ago 68
Java Question

Sending a variable from ActionListener, so another ActionListener can use it

I see there are some questions already asked about this topic but I haven't come up to an answer for my. I am writing a code where user types something in JTextField, and after clicking a button, his word is replaced with the number of asterisks with the same number of characters his word had e.g "table" would be replaced by "****". i did it this way:

ask.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String guess = "";
String given = textGive.getText();
for (int i=0; i<given.length(); i++){
String asterisk = "*";
guess += asterisk;


I know that I did not do this in a great way, but I did not know how to do it better. Any recommendations?

Now, I want somehow to save both Strings, the original word and the asterisk one outside the scope so I can access it in another ActionListener and modify it further.
Before writing first ActionListener i did write
String guess = ""
String given = ""
but it seems as it did not do anything.
So, in my second ActionListener i want to send him the string
I received when the user typed his word.

guess.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String attempt = textGuess.getText();
char att = attempt.charAt(0);
for (int i=0; i<5; i++){

if (given.charAt(i)==att){


Eclipse gives me error saying "Cannot refer to the non-final local variable given defined in an enclosing scope". I understand that I need to make
final in order to acces it further, but how to do that if the variable depends on text input from first ActionListener? Is there some other solution for this problem? I've recently started using java, so I do not know the language so well.

Answer Source

Anything that you want visible to class should be placed in instance fields, not in local variables. For instance, the given variable should be a private non-static field declared in the class, and not a variable buried within your listener's actionPerformed method.


public class Foo extends JPanel {
    private JButton ask = new JButton("Ask");
    private JTextField textGive = new JTextField(10);
    private String given = "";  // visible throughout the class

    public Foo() {
        ActionListener listener = e -> {
            String guess = "";
            // String given = textGive.getText(); //visible only within this method
            given = textGive.getText();
            guess = given.replaceAll("\\w", "*");

        textGive.addActionListener(listener);  // also give the same listener to the JTextField
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download