I would like to make a String return type method which will return specific value when the button is pressed, I have come up with the code below which unfortunately does not work. Could anyone suggest how to fix my code or if there is any better way to get what I want? I have defined the Button b as a Class variable. I added an error that I get as a comment in the code.
public String sample() {
String retString = null;
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
retString = "return String";
//Local variable retString defined in an enclosing scope must be final or effectively final
}
});
return retString;
}
Your function will not work because .addActionListener doesn't wait until someone presses a button. Imagine you're telling java when you add the ActionListener "Hey when I press this button could you write it down on a piece of paper?". Once a button is pressed, only then the piece of paper won't be empty. This is called adding a callback. So how can you get around it? The easiest way (albeit not the best) is to just wait until that piece of paper isn't null. In this case it's your string, because only when a button is pressed, only when your function is called, only when your function changes retString, only then retString isn't null.
while (retString == null) {}
System.out.println(retString);
Why is this not good? When you do this, you're stopping code from being executed on the thread that you're executing the while loop in until you press a button.
A better solution
Implement what you're doing in the callback eg.
button.addActionListener(e -> {
System.out.println("Button pressed!");
});
You don't need to create the callback inside the .addActionListener(). In fact you can make a class that implements ActionListener, allowing for the same callback functionality across different components. For example
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CustomCallback implements ActionListener {
int amountOfTimesCalled = 0;
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Callback called by " + e.getSource());
amountOfTimesCalled++;
if (amountOfTimesCalled > 5) {
System.exit(0);
}
}
}
You could have this across multiple buttons eg
final CustomCallback callback = new CustomCallback();
button1.addActionListener(callback);
button2.addActionListener(callback);