Monday, January 19, 2015

How to use ControlsFX Autocomplete

First, lets create Fxml file which is the view layer

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

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

<GridPane prefHeight="164.0" prefWidth="403.0" xmlns="http://javafx.com/javafx/8"
          xmlns:fx="http://javafx.com/fxml/1" fx:controller="tj.daqiq.operations.controller.ReceiptController">
  <columnConstraints>
    <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
    <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
  </columnConstraints>
  <rowConstraints>
    <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
    <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
    <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
  </rowConstraints>
   <children>
      <Label prefHeight="15.0" prefWidth="72.0" text="From" />
      <Label text="To" GridPane.rowIndex="1" />
      <TextField fx:id="txtAuto" prefHeight="18.0" prefWidth="71.0" GridPane.columnIndex="1" />
      <TextField GridPane.columnIndex="1" GridPane.rowIndex="1" />
   </children>
</GridPane>

Here we placed TextField.


Next in the controller we will bind ControlsFX autocomplete

package tj.daqiq.operations.controller;

import java.net.URL;
import java.util.ResourceBundle;

import org.controlsfx.control.textfield.TextFields;

import tj.daqiq.warehouse.services.BatchService;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;

public class ReceiptController implements Initializable {

    @FXML
    private TextField txtAuto;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        BatchService service = new BatchService();

        TextFields.bindAutoCompletion(txtAuto, t-> {
            return service.getSuggestions("code", t.getUserText());
        });
    }
}

The following code will get records from database using hibernate

    @SuppressWarnings("unchecked")
    @Override
    public List<String> getSuggestions(String fieldName, String searchString) {
        logger.info("Getting batch list for autocomplete");
        List<String> list = null;
        HibernateUtil.getSessionFactory().openSession().close();
        Session s = HibernateUtil.getSessionFactory().openSession();
        try {
            s.beginTransaction();
            Query query = s.createQuery("select B." + fieldName + " from Batch B where B."+fieldName + " LIKE :search");
            list = query.setParameter("search", "%"+searchString+"%").setMaxResults(10).list();
            s.getTransaction().commit();
        } catch (Exception ex) {
            logger.error("Other exception {}", ex);
        } finally {
            s.close();
        }      
        return list;
    }

Thats all!