I'm trying to get a Method using Fibonacci to bind to a button, which will use a slider as the input value and then print the Fibonacci number in a textfield. I am running into trouble passing the value from my Fibonacci method to the textfield. Any help would be appreciated. This is what I've written so far:
public class Main extends Application {
private static Slider fibSlider = new Slider(0, 10, 0);
private static Label indexLabel = new Label();
private static Label fibNumLabel = new Label();
private static int colIndex = 0;
private static int rowIndex = 0;
private static int topIndex = 0;
private static int rightIndex = 0;
private static int leftIndex = 0;
private static int bottomIndex = 0;
private static TextField tfIndex;
private static TextField tfFibNum;
private static Button butCalcFib = new Button();
@Override
public void start(Stage primaryStage) {
fibSlider.setMajorTickUnit(1);
fibSlider.setMinorTickCount(0);
fibSlider.setShowTickLabels(true);
fibSlider.setShowTickMarks(true);
fibSlider.setSnapToTicks(true);
fibSlider.valueProperty().addListener(sl -> {
tfIndex.setText(Double.toString(fibSlider.getValue()));
});
indexLabel.setText("Index: ");
fibNumLabel.setText("Fibonacci #: ");
butCalcFib.setText("Calculate Fibonacci");
//tfFibNum.setText(long.toString(ComputeFibonacci()));
fibSlider.valueProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, Number newValue) {
if (newValue == null) {
tfIndex.setText("");
return;
}
tfIndex.setText(Math.round(newValue.intValue()) + "");
}
});
GridPane mainGPane = buildGPane();
Scene mainScene = new Scene(mainGPane, 500, 200);
primaryStage.setTitle(" - Fibonacci Calculator");
primaryStage.setScene(mainScene);
primaryStage.show();
}
private GridPane buildGPane() {
GridPane gPane = new GridPane();
gPane.setAlignment(Pos.CENTER);
gPane.setPadding(new Insets(topIndex = 10, rightIndex = 10,
bottomIndex = 10, leftIndex = 10));
gPane.setHgap(2);
gPane.setVgap(2);
gPane.add(fibSlider, colIndex = 1, rowIndex = 3);
gPane.add(indexLabel, colIndex = 1, rowIndex = 5);
gPane.add(tfIndex, colIndex = 2, rowIndex = 5);
gPane.add(butCalcFib, colIndex = 1, rowIndex = 6);
gPane.add(fibNumLabel, colIndex = 1, rowIndex = 7);
gPane.add(tfFibNum, colIndex = 2, rowIndex = 7);
return gPane;
}
public Main() {
tfIndex = new TextField();
tfFibNum = new TextField();
}
public static void ComputeFibonacci() {
double index = fibSlider.getValue();
// Find and display the Fibonacci number
fib((long) index);
}
/**
* The method for finding the Fibonacci number
*/
public static long fib(long index) {
if (index == 0) // Base case
{
return 0;
} else if (index == 1) // Base case
{
return 1;
} else // Reduction and recursive calls
{
return fib(index - 1) + fib(index - 2);
}
}
public static void main(String[] args) {
launch(args);
}
}