Search code examples
javabuttonappletawttextfield

Java: I want to get TextField value when I clicked a button. How to do it?


public Monster createCharacterScene() {
    String name;
    TextField nameTextField = new TextField();
    nameTextField.setLocation(65, 50);
    nameTextField.setSize(60, 10);
    Button myButton = new Button("OK");
    myButton.setLocation(25, 50);
    myButton.setSize(30, 40);
    add(myButton);
    add(nameTextField);
    myButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            name = nameTextField.getText();
        }
    });
    return null;
}

I can't do it like this. They says "local variables referenced from an inner class must be final or effectively final". Is there alternative way to do it?

Thanks a lot.

PS. I using applet.


Solution

  • You cannot read this value directly in createCharacterScene() method. Because it's unknown yet. The only thing you can do is to define a eventHandler, that will be triggered, on key press.

    Consumer<String> nameConsumer = text -> { /*You will handle event here*/};
    myButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                nameConsumer.apply(nameTextField.getText());
            }
        });
    

    The cheaper version would be to use a small workaround for final modifier:

    final String[] nameHolder = new String[1];
    myButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                nameHolder[0] = nameTextField.getText();
            }
        });
    

    Here nameHolder will initially hold null, but when someone will trigger the event, it's value will be set, so you need to check if value is set or not.