问题
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
回答1:
To call void function in action handler, lambda expression is usefull. Like this:
buttonForLoad.setOnAction(e -> loadFootage());
buttonForSave.setOnAction(e -> saveFootage());
...
回答2:
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
}
});
...
}
来源:https://stackoverflow.com/questions/43724002/set-button-on-action-within-method-java