Chris A
Chris A

Reputation: 1090

Pass an argument into an action listener

Background

I'm trying to write a program in which the user types in a formula of format

A?B:C?(X-1):D?(Y-3):(Z*3)

and then the code will guide the user through a series of yes/no questions to determine what would be returned under certain conditions.

Problem

I have written a findTrue code which will extract the true part of this kind of formula. I want my yesListener's action to ask another question if the true part of the user's input has more question marks in it. If not, it will return the answer.

        ActionListener yesListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String formula = textArea.getText();
                int i = StringUtils.countMatches(formula, "?");
               if  (i>1) {
                    String newFormula = "";
                    newFormula = findTrue(formula);
                    questionLabel.setText(askQuestion(newFormula));
                }
               else {questionLabel.setText("The formula will return" + findTrue(formula));}
            }};

The first time I run the code it works fine, but the second time it runs the getText() again from the original input. So, I figure the best way is if I can pass the string into the actionPerformed rather than evaluating it inside. However I'm still pretty new to java and I'm struggling to see how I could make this happen.

Upvotes: 0

Views: 184

Answers (2)

Forketyfork
Forketyfork

Reputation: 7810

As far as I understand, your ActionListener is created in the scope of some class. It's hard to propose the best way to refactor the code without seeing the whole code of the class.

But to achieve your goal, you could save the original value of getText() in a class instance field, and then update it in each new invokation of the listener:

public class Main {

    private String formula;


    ActionListener yesListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (formula == null) {
                formula = textArea.getText();
            }
            int i = StringUtils.countMatches(formula, "?");
            if (i > 1) {
                formula = findTrue(formula);
                questionLabel.setText(askQuestion(formula));
            } else {
                questionLabel.setText("The formula will return" + findTrue(formula));
            }
        }

    };

Upvotes: 1

Tanveer Hasan
Tanveer Hasan

Reputation: 343

U cant directly pass arguments to anonymous function. But this link might help u to do that how-to-pass-parameters-to-anonymous-class

Upvotes: 0

Related Questions