Saturday, November 14, 2015

JavaFx Sqlite Database Tutorial 2 - How Connect Sqlite to JavaFx







package application;

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

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;

public class LoginController implements Initializable {
 public LoginModel loginModel = new LoginModel();
 
 
   @FXML
   private Label isConnected;
 @Override
 public void initialize(URL location, ResourceBundle resources) {
  // TODO Auto-generated method stub
  if (loginModel.isDbConnected()) {
   isConnected.setText("Connected");
  } else {

   isConnected.setText("Not Connected");
  }
 }
  
}




package application;
import java.sql.*;
public class LoginModel {
  Connection conection;
  public LoginModel () {
   conection = SqliteConnection.Connector();
   if (conection == null) {

   System.out.println("connection not successful");
    System.exit(1);}
  }
  
  public boolean isDbConnected() {
   try {
  return !conection.isClosed();
 } catch (SQLException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  return false;
 }
}
}



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 {
   Parent root = FXMLLoader.load(getClass().getResource("/application/Login.fxml"));
   Scene scene = new Scene(root);
   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 java.sql.*;
public class SqliteConnection {
  public static Connection Connector() {
 try {
  Class.forName("org.sqlite.JDBC");
  Connection conn =DriverManager.getConnection("jdbc:sqlite:EmployeeDb.sqlite");
  return conn;
 } catch (Exception e) {
  System.out.println(e);
  return null;
  // TODO: handle exception
 }
}
}



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

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

<AnchorPane prefHeight="300.0" prefWidth="300.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.LoginController">
   <children>
      <Label fx:id="isConnected" layoutX="54.0" layoutY="35.0" prefHeight="46.0" prefWidth="192.0" text="Status" textFill="#cd1313">
         <font>
            <Font size="18.0" />
         </font>
      </Label>
   </children>
</AnchorPane>