I am new to javafx. Created an application with three elements: a text box for entering a number, a "confirm" button and a label for displaying the result.

The listener is tied to the "confirm" button, in which the result is calculated by the formula.

The question is: how can I use this GUI alone for many applications with other formulas in the listener's body? Of course, you can simply copy and paste the code by rewriting the formula in the listener's body, but I'm looking for an object-oriented method.

  • To score in the program a few formulas. For example in HashMap . The key will be the name of the formula, and the value of some class with the processor of the formula. All handlers will have a base type, for example Formula and from it create PriceFormula classes, etc. On gui create a combobox with a choice of some kind of formula. If in the future we plan to add fields, then it will be more difficult. I suggest that you make your own components, which themselves know their formula and their fields. - Tsyklop pm
  • make a pluggable library of it. then wherever you need this form, you connect this ready-made module to the project and use it as if it were in the project, but for such small ones as your example, it is not customary to make a library. Here, a snippet is more appropriate, modern IDEs allow you to create a dynamic template, which contains code and sections dynamically substituted by use, you only need to enter changeable parameters in the usage window and everything like File and code templates (for classes) or Live Templates ( for methods and the like inside a class) in IDEA - pavlofff

1 answer 1

You can create an abstract class:

 public abstract class MyPane extends Pane{ private TextField textFld; private Button btn; private Label lbl; public MyPane(){ textFld = new TextField(); btn = new Button("ok"); lbl = new Label("answer"); this.getChildren().addAll(textFld,btn,lbl); btn.setOnAction(event->{ String res = formula(textFld.getText()); lbl.setText(res); }); } protected abstract String formula(String text); } 

Further inheriting from this class, it will be necessary to redefine the method formula (String val) for each successor.