-2

I have already built an interface with labels, buttons and text fields. I want to atleast handle an event on one button that will print a string or sentence to the console. I don't know how to use the event handler, any piece of relevant code will help. Am just starting java. please help...

Marvin Nyalik
  • 51
  • 1
  • 3
  • 3
    Try this here: https://stackoverflow.com/questions/30446996/javafx-begginers-simple-calculator-event-handling?rq=1. If that doesn´t help I would advise to read a couple tutorials from oracle about event handling in javafx. – Alexander Heim Oct 06 '17 at 09:21
  • When you post a question, make a practice to include what you done so far on that topic. SO is not place where you will get complete solution.! – Akhil Mathew Oct 06 '17 at 09:46

2 Answers2

0

In order to respond to click of a button you need to attach an event listener to the button object

button.setOnAction(new EventHandler() {
    @Override
    public void handle(ActionEvent actionEvent) {
        //... do something in here.
    }
});

For more you visit these links i hope you find your solution http://tutorials.jenkov.com/javafx/button.html#button-events and this http://tutorials.jenkov.com/java/lambda-expressions.html

Raheel
  • 210
  • 2
  • 9
0

Since you are just beginning your adventure with javafx you will most likely stumble across what Raheel wrote in another form, namely, a lambda expression. The same code snippet would then look like so:

button.setOnAction((event) -> {
//... do sth here
});
gourmej
  • 3
  • 1
  • 6
  • Isn't this supposed to override an existing method? I cant see the public void handle ()method being overridden!! Maybe you can elaborate.. – Marvin Nyalik Oct 06 '17 at 10:28
  • Raheel uses EventHandler interface which has one method https://docs.oracle.com/javase/8/javafx/api/javafx/event/EventHandler.html In order to use it he has to override it. There is no limit to what method is going to be used as the handler. You can as well create your own eventHandlerMethod and use it like so: button.SetOnAction(this::eventHandlerMethod) – gourmej Oct 06 '17 at 10:36