Thursday, October 29, 2015

JavaFx Tutorial For Beginners 6 - Events with JavaFX Scene Builder







package application;
 
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;


public class Main extends Application {
 @Override
 public void start(Stage primaryStage) {
  try {
   //BorderPane root = new BorderPane();

   Parent root = FXMLLoader.load(getClass().getResource("/application/Main.fxml"));
   Scene scene = new Scene(root,400,400);
   scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
   primaryStage.setScene(scene);
   primaryStage.show();
  } catch(Exception e) {
   e.printStackTrace();
  }
 }
 
 public static void main(String[] args) {
  launch(args);
 }
}







package application;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;

import java.util.Random;
public class MainController {
 @FXML
    private Label myMessage; 
 public void generateRandom(ActionEvent event) {
  Random rand = new Random();
  int myrand = rand.nextInt(50) + 1;
  myMessage.setText(Integer.toString(myrand));
  //System.out.println(Integer.toString(myrand));
 }
}







<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>


<AnchorPane prefHeight="300" prefWidth="500" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.40" fx:controller="application.MainController">
   <children>
      <Button fx:id="clickme" layoutX="213.0" layoutY="202.0" mnemonicParsing="false" onAction="#generateRandom" text="Click me" />
      <Label fx:id="myMessage" layoutX="116.0" layoutY="59.0" prefHeight="112.0" prefWidth="229.0" />
   </children>
</AnchorPane>




No comments:

Post a Comment