set button on action within method java

爱⌒轻易说出口 提交于 2019-12-11 08:51:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!