In: Computer Science
Java
Write a JavaFX application that displays a button and
a number. Every time the button is pushed, change the number
to a random value between 1 and 100.
Thank you and can you show a picture of the result as well
import java.util.Random;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class DisplayRandom extends Application {
@Override
public void start(Stage primaryStage) {
Button btn = new Button("Generate Random");
Random rand = new Random();
int num = rand.nextInt((100-1)+1)+1;
Label l1 = new Label(""+num);
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
l1.setText("");
int num = rand.nextInt((100-1)+1)+1;
l1.setText(""+num);
}
});
Pane root = new Pane();
btn.setLayoutX(100);
btn.setLayoutY(100);
l1.setLayoutX(150);
l1.setLayoutY(50);
root.getChildren().add(btn);
root.getChildren().add(l1);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Generate Random");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
/* OUTPUT */