user7775333
user7775333

Reputation:

set button on action within method java

How could I set the action of a button within the same method I am creating the buttons?

My desired method would be something like this:

private void buttonsCreation() {
        //----------------creation of interactive buttons with text-----------------
        Button buttonForLoad = new Button("Load footage file");
        Button buttonForSave = new Button("Save footage file");
        Button buttonForSaveAs = new Button("Save as footage file");
        ButtonbuttonForRun = new Button("Run footage animation");
        Button buttonForTerminate = new Button("Stop footage animation");
        Button buttonForEditMenu = new Button("Edit current footage");
        //---------------setting the interaction of the buttons---------------------
        buttonForLoad.setOnAction(loadFootage());
        buttonForSave.setOnAction(saveFootage());
        buttonForSaveAs.setOnAction(saveAs());
        buttonForRun.setOnAction(runAnimation());
        buttonForTerminate.setOnAction(terminateAnimatino());
        buttonForEditMenu.setOnAction(editMenu());
    }

I would like the attributes of setOnAction to call those methods, but I receive this error. setOnAction in ButonBase can not be applied to void.

I am aware I can create a void handle with an ActionEvent as a parameter and make it work, but my desired function will be in one function, and if it is possible with as least lines of code as possible.

Thanks very much

Upvotes: 1

Views: 3303

Answers (2)

monolith52
monolith52

Reputation: 884

To call void function in action handler, lambda expression is usefull. Like this:

buttonForLoad.setOnAction(e -> loadFootage());
buttonForSave.setOnAction(e -> saveFootage());
...

Upvotes: 1

Vasyl Lyashkevych
Vasyl Lyashkevych

Reputation: 2222

Maybe did you mean the action listener for example:

private void buttonsCreation() {
//------------creation of interactive buttons with text---------------

Button buttonForLoad = new Button("Load footage file");
buttonForLoad.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // to do something
            }
        });

...
}

Upvotes: 0

Related Questions