0

I have this test code and I want the method to return a value when the button is pressed. What would be the best way to go about that?

public String test(){
    JFrame frame=new JFrame();
    frame.setSize(800,600);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    JButton button=new JButton("Click Me!");
    frame.add(button);
}

I have tried adding an ActionListener, but I see no way of returning a value from the parent method.

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        //A return here would not work
    }
});
Syd Lambert
  • 1,415
  • 14
  • 16
  • You can update objects in the form if they are global. Instead of a return, you update the object directly. – kevingreen Mar 28 '16 at 18:00
  • 1
    Instead of a `JFrame`, look into using a [`JOptionPane`](https://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html). It's designed for just this sort of task. – John Bollinger Mar 28 '16 at 18:01

1 Answers1

2

The local variable has to be final but nothing prevents it from being a Collection which could then be modified.

Look at the following code.

public String test(){
    // code
    final List<String> list = new ArrayList<>();
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            list.add("toBeReturned");
        }
    });
    frame.add(button);
    return list.get(0);
}
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89