Wednesday, 9 May 2018

Exercise1: JavaFX: Print multiplication table

Whenever user clicks on the button, display multiplication table of 2.

Find the below working application.

NumberUtil.java
package com.sample.demos;

public class NumberUtil {

 public static String getMultiplictionTable(int n, int until){
  StringBuilder builder = new StringBuilder();
  
  for(int i=1; i<until; i++){
   builder.append(n).append("*").append(i).append("=").append(n*i).append("\n");
  }
  
  return builder.toString();
 }
 
 public static String get2MultiplicationTable(){
  return getMultiplictionTable(2, 10);
 }
}

MultiplicationTableApp.java
package com.sample.demos;

import static javafx.geometry.Pos.CENTER;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class MultiplicationTableApp extends Application {

 @Override
 public void start(Stage primaryStage) {

  Button button = new Button();
  button.setText("Click Me to print multiplication table of 2");

  Text message = new Text();

  button.setOnAction(event -> {
   message.setText(NumberUtil.get2MultiplicationTable());
  });

  VBox vBox = new VBox(10, button, message);
  vBox.setAlignment(CENTER);

  Scene scene = new Scene(vBox, 600, 400);

  /* Set the scene to primaryStage, and call the show method */
  primaryStage.setTitle("Hello JavaFX Example");
  primaryStage.setScene(scene);
  primaryStage.show();
 }

}

TestFX.java
package com.sample.demos;

import javafx.application.Application;

public class TestFX {
 public static void main(String args[]) {
  Application.launch(MultiplicationTableApp.class, args);
 }
}

When you ran above application, you can able to see below window.




When you click on the button, user interface will change like below.






Previous                                                 Next                                                 Home

No comments:

Post a Comment