In my last Post which is the beginning of this one, I created a SOAP-based web service by exposing an EJB as a web service. In this part, we shall be creating JAVAFX UI to consume the Web service.

In this post, We demonstrated how to use scene builder to create JavaFx UI but for this post we shall be using another approach i.e creating the UI programming by making use of the JavaFX Main Class. JavaFX Main Classes extends Application class.

STEPS:

  • Create a new JavaFX project if you have not. I created a new project named Car Rental Customer.
  • Create a new Java package inside the Car Rental Customer named car.ws
  • From the car.ws package node, right-click and choose NEW, then JavaFX Main Class. Provide the class name as WsViewCars.
  • Delete all the unneeded generated codes inside till it looks like this.
package car.ws;

/**
 *
 * @author STEINACOZ-PC
 */
public class WsViewCars extends Application {
  

    @Override
    public void start(Stage primaryStage) throws IOException {
        
    }
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

   }
  • From the car.ws package node, right-click and choose NEW, then Web Service client. Choose the package and location of WSDL file. From my last post,  WSDL can found at: WILDFLY_HOME/standalone/data/wsdl/CarRental-ejb.jar. Then Click on finish.

ws4

  • When Netbeans is through with creating the web service client, your project tree should look like these images with the generated classes. You can see the allCars webMethod in the tree. Refer to the part 1 of this post, if you missed the WebMethod part.

ws5 ws6

  • Now, highlight the allCars method which is under the RentalBeanPort and drag into WsViewCars class to get this output (check the highlighted portion of the code):
package car.ws;

/**
 *
 * @author STEINACOZ-PC
 */
public class WsViewCars extends Application {

     
    
    @Override
    public void start(Stage primaryStage) throws IOException {
        
        
    }
    
    

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

    private static java.util.List<car.ws.Info> allCars() {
        car.ws.RentalWS service = new car.ws.RentalWS();
        car.ws.RentalBean port = service.getRentalBeanPort();
        return port.allCars();
    }
}
  • Now, you can complete the code:
package car.ws;

import car.btnrent.RentBtnFXMLController;
import car.dashborad.CustomerDashFXMLController;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javax.imageio.ImageIO;

/**
 *
 * @author STEINACOZ-PC
 */
public class WsViewCars extends Application {
    
GetGris gGrid = new GetGris(); //creates a new GetGris Service Class
     
    
    @Override
    public void start(Stage primaryStage) throws IOException {
        
             
        ScrollPane scp = gGrid.getScroll(); //creates a new Scrollpane from the getScroll() of the Service class
      
        gGrid.start(); //starts the concurrent service
        
        
     Scene scene = new Scene(scp, 1000, 900); //creates new Scene with its dimenensions and also as the scrollpane as its root
        
        
        primaryStage.setTitle("Car Garage");
        primaryStage.setFullScreen(false);
        
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

    private static java.util.List<car.ws.Info> allCars() {
        car.ws.RentalWS service = new car.ws.RentalWS();
        car.ws.RentalBean port = service.getRentalBeanPort();
        return port.allCars();
    }
    
//the concurrent service class connects to the server, loads the data from webservice
//into the gridpane while the scene and stage is loading
//it stops the connection from blocking the JavaFX main thread 
  public  class GetGris extends Service{
        
        ScrollPane sPane = new ScrollPane();//creates a scrollpane that will be returned to the main thread
        
       
        
        public void createGrid(ScrollPane scPane) throws IOException{ //this method creates & populates the gridpane
               sPane = scPane;  
               sPane.setPadding(new Insets(10,10,10,10));

               GridPane gb = new GridPane(); //creates a new gridpane
               gb.setHgap(5);
               gb.setVgap(5);
     
               gb.setGridLinesVisible(true); //set this to false, it is only used for debugging
               gb.setPadding(new Insets(10,10,10,10));
               gb.setPrefSize(800, 1000);
      
      int imgCol = 0; //initializes the gridpane column
      int imgRow = 0; //initializes the gridpane row
      
    //creates arraylists to store data from web service
      ArrayList<String> fileArray = new ArrayList<>();
      ArrayList<String> refArray = new ArrayList<>();
       ArrayList<String> nameArray = new ArrayList<>();
       ArrayList<String> modelArray = new ArrayList<>();
       ArrayList<String> manuArray = new ArrayList<>();
       ArrayList<String> cateArray = new ArrayList<>();
       ArrayList<Float> priceArray = new ArrayList<>();
       ArrayList<String> availArray = new ArrayList<>();
       ArrayList<String> yearArray = new ArrayList<>();
    
      //new ImageView contrl to hold the car images
      ImageView img;
      
      for(car.ws.Info inf : allCars()){ //loop to add the data
          fileArray.add(inf.getImage());
          refArray.add(inf.getRef());
          nameArray.add(inf.getCarname());
          modelArray.add(inf.getCarmodel());
          manuArray.add(inf.getManufacturer());
          cateArray.add(inf.getCategory());
          priceArray.add(inf.getPrice());
          availArray.add(inf.getAvailable());
          yearArray.add(inf.getYear());
      }
      
    for(int i = 0; i < fileArray.size(); i++){
        
    //converts the filepath into a bufferedImage
    BufferedImage bi;
    bi = ImageIO.read(new File(fileArray.get(i)));
    String imgPath = fileArray.get(i);

    //converts the bufferedimage to Image
    Image image = SwingFXUtils.toFXImage(bi, null);
                
     
     img = new ImageView();
     img.setFitHeight(150);
     img.setFitHeight(150);
     img.setPreserveRatio(false);
     
     //sets the Image on the imageView     
     img.setImage(image);
      
     //creates Text to hold various data
     Text nameText = new Text();
     Text modelText = new Text();
     Text refText = new Text();
     Text priceText = new Text(); 
     Text availText = new Text();
     Text manuText = new Text();
     Text categoryText = new Text();
     Text yearText = new Text();
       
      
     //sets the Text according to the data from the arrays
     categoryText.setText(cateArray.get(i));
     Text carCat = new Text();
     carCat.setText("Category: ");
     
     yearText.setText(yearArray.get(i));
     Text carYear = new Text();
     carYear.setText("Year: ");
  
     refText.setText(refArray.get(i));
     Text carRef = new Text();
     carRef.setText("Ref Number: ");
      
     
     nameText.setText(nameArray.get(i));
     Text carName = new Text();
     carName.setText("Car Name: ");
     
     
     modelText.setText(modelArray.get(i));
     Text carModel = new Text();
     carModel.setText("Car Model: ");
     
   
     manuText.setText(manuArray.get(i));
     Text carManu = new Text();
     carManu.setText("Manufacturer: ");
     
     
     priceText.setText(String.valueOf(priceArray.get(i)));
     Text carPrice = new Text();
     carPrice.setText("Car Price : ");
     
     
     availText.setText(availArray.get(i));
     Text carAvail = new Text();
     carAvail.setText("Available: ");
     
     //creates a circle that will be painted green if Car is available
     //and painted red if it is not available
     Circle circle = new Circle();
     circle.setRadius(10.0);
     
     if (availArray.get(i).equals("YES")){
         circle.setFill(Color.GREEN);
     }else if(availArray.get(i).equals("NO")){
         circle.setFill(Color.RED);
     }else{
         circle.setFill(Color.ORCHID);
    }
     
    //creates a button that will open the Rent Car page
    //the car information is passed along to the rent Car page.
     Button btnRent = new Button("Rent this Car");
     
      if(availArray.get(i).equals("NO")){
         btnRent.setVisible(false);
     }else if(availArray.get(i).equals("YES")){
         btnRent.setVisible(true);
     }
    
     btnRent.setOnAction(new EventHandler(){
             @Override
             public void handle(Event event)  {
                 try{
        Stage stage1 = new Stage();           
        
        FXMLLoader loader =  new FXMLLoader(getClass().getResource("/car/btnrent/RentBtnFXML.fxml"));
        AnchorPane root1 = loader.load();
           
        RentBtnFXMLController rbfc = loader.<RentBtnFXMLController>getController();
       System.out.println(refText.getText());
        Scene scene1 = new Scene(root1);
         rbfc.setUI(nameText.getText(), modelText.getText(), manuText.getText(), String.valueOf(priceText.getText()), availText.getText(), refText.getText(),imgPath, categoryText.getText(), yearText.getText());
                
        
        stage1.setScene(scene1);
        stage1.show();
             
             }catch(IOException e){
         
     }
             }
         
     });

     //opens the search and rent car page.
     Button btnSearch = new Button("Search Others");
     btnSearch.setOnAction(new EventHandler(){
        @Override
        public void handle(Event event) {
             try{
        Stage st = new Stage();           
        
        FXMLLoader l =  new FXMLLoader(getClass().getResource("/car/btnrent/hireFXML.fxml"));
        AnchorPane root = l.load();
           
 
        Scene sc = new Scene(root);
                      
        
        st.setScene(sc);
        st.show();
             
             }catch(IOException e){
         
     }
        }
         
     });
     
      VBox vb = new VBox();
      vb.setPrefSize(300, 250);
      
      //creates Hbox(s) and add various controls to them as children
      HBox hboxName = new HBox();
      hboxName.getChildren().addAll(carName,nameText);
      
       HBox hboxModel = new HBox();
      hboxModel.getChildren().addAll(carModel,modelText);
      
       HBox hboxManu = new HBox();
      hboxManu.getChildren().addAll(carManu,manuText);
      
       HBox hboxPrice = new HBox();
      hboxPrice.getChildren().addAll(carPrice,priceText);
      
       HBox hboxAvail = new HBox();
      hboxAvail.getChildren().addAll(carAvail,availText);
      
       HBox hboxRef = new HBox();
      hboxRef.getChildren().addAll(carRef,refText);
      
      HBox hb = new HBox();
      hb.getChildren().addAll(btnRent,btnSearch);

     //all the Hbox(s) are added as children to the VBox
      vb.getChildren().addAll(img,hboxName,hboxModel, hboxManu, hboxPrice,hboxAvail, hboxRef, circle,hb);
      
     //the VBox is added to a Pane
     Pane grid = new Pane();
     grid.setStyle("-fx-background-color: blue;");
     grid.setPrefSize(600, 300);
     grid.getChildren().add(vb);
      
     //the Pane is added to the GridPane with the rows and columns 
     gb.add(grid, imgCol, imgRow);
      
     //the Gridpane is set as a content to the scrollpane
      sPane.setContent(gb);
      imgCol++;
      
      if(imgCol >3){
            
          //if the column is up to four, it will be resetted to zero
          imgCol =0;
          
          imgRow++;
      }
         
    }
        
  setScroll(sPane);
        
       
        }
        
        
public ScrollPane getScroll(){
    return sPane;
}

public void setScroll(ScrollPane ssPane){
    sPane = ssPane;
}
        @Override
        protected Task<Void> createTask() {
            return new Task<Void>(){
                @Override
                protected Void call() throws Exception {
                    Platform.runLater(new Runnable(){//updates the UI later
                        @Override
                        public void run() {
                            try{
                          createGrid(sPane);
                            }catch(IOException e){
                                
                            }
                        }
                        
                    });
                   return null;
                }
                
            };
        }
        
    }

}

Run the application to get this output:

ws1

In the next post, we will be populating JavaFX TabelView with WebService. You can add CSS to the UI to make it fanciful, refer to this post how to style JavaFX UI with CSS.

LEAVE A REPLY

Please enter your comment!
Please enter your name here