Test 2 Reflection

Reflective Property

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by ydvma4-15 on 2017/05/12.
 */
public class ReflectiveProperty<T> {

    private Object obj;
    private Method getter = null;
    private Method setter = null;

    private Method getGetter(Object object, String propertyName, Class propertyType){
        Class clazz = object.getClass();
        propertyName = propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
        Method method;
        try {
            method = clazz.getDeclaredMethod("get" + propertyName,new Class<?>[0]);
            //check that the return types are equal
            if(method.getReturnType() != propertyType){
                method = null;
            }
        } catch (NoSuchMethodException e) {
            method = null;
        }
        return method;
    }

    private Method getSetter(Object object, String propertyName, Class propertyType){
        Class clazz = object.getClass();
        propertyName = propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
        Method method;
        try {
            method = clazz.getDeclaredMethod("set" + propertyName, propertyType);
        } catch (NoSuchMethodException e) {
            method = null;
        }
        return method;
    }

    public ReflectiveProperty(Object object, String propertyName, Class propertyType){
        obj = object;
        setter = getSetter(obj, propertyName, propertyType);
        getter = getGetter(obj, propertyName, propertyType);
    }

    public void set(T value){
        if(setter != null){
            try {
                setter.invoke(obj, value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    public T get(){
        if(getter != null){
            try {
                return (T)getter.invoke(obj);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public boolean isReadable(){
        return getter != null;
    }

    public boolean isWriteable(){
        return setter != null;
    }
}

Reflective Test

public class ReflectiveTest {

    public static void main(String[] args) {
        Tester tester = new Tester();

        System.out.println("Creating the reflective property objects");
        ReflectiveProperty<String> testerName = new ReflectiveProperty<>(tester, "name", String.class);
        ReflectiveProperty<Integer> testerAge = new ReflectiveProperty<>(tester, "age", Integer.class);
        System.out.println();

        // display whether readable and/or writeable
        System.out.println("Reflective property objects' readability and writeability");
        System.out.println("Name is readable = " + testerName.isReadable());
        System.out.println("Name is writeable = " + testerName.isWriteable());
        System.out.println("Age is readable = " + testerAge.isReadable());
        System.out.println("Age is writeable = " + testerAge.isWriteable());
        System.out.println();

        // set the property values using the reflective property
        System.out.println("Set property values using reflective property objects");
        testerName.set("Bob");
        testerAge.set(30);
        System.out.println();

        // get the property values using the reflective property
        System.out.println("Displaying property values using the reflective property objects");
        System.out.println("Tester's name = " + testerName.get());
        System.out.println("Tester's age = " + testerAge.get());
        System.out.println();

        // get the values using the methods provided by the tester class
        System.out.println("Displaying the property values using the tester class methods");
        System.out.println("Tester's getName = " + tester.getName());
        System.out.println("Tester's getAge = " + tester.getAge());
    }
}

Tester

public class Tester {
    // field storing the 'name' property's value
    private String name;

    // property called 'name' that is reable and writeable
    public void setName(String name) { this.name = name; }
    public String getName() { return name; }

    // property called 'age' that is only readable
    public Integer getAge() { return 20; }
}

Test 2 Database

View

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Line;
import javafx.stage.Stage;

/**
 * Created by ydvma4-15 on 2017/05/12.
 */
public class View extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    private Scene createScene() {
        HBox surnameBox = new HBox(10);
        Label lblSurname = new Label("Surname");
        Region r1 = new Region();
        TextField tfSurname = new TextField();
        tfSurname.setId("surname");
        surnameBox.getChildren().addAll(lblSurname, r1, tfSurname);
        HBox.setHgrow(r1, Priority.ALWAYS);
        surnameBox.setPadding(new Insets(0,10,0,10));

        HBox nameBox = new HBox(10);
        Label lblName = new Label("First Names");
        Region r2 = new Region();
        TextField tfName = new TextField();
        tfName.setId("name");
        nameBox.getChildren().addAll(lblName, r2, tfName);
        HBox.setHgrow(r2, Priority.ALWAYS);
        nameBox.setPadding(new Insets(0,10,0,10));

        HBox addressBox = new HBox(10);
        Label lblAdd = new Label("Address");
        Region r3 = new Region();
        TextField tfAdd = new TextField();
        tfAdd.setId("address");
        addressBox.getChildren().addAll(lblAdd, r3, tfAdd);
        HBox.setHgrow(r3, Priority.ALWAYS);
        addressBox.setPadding(new Insets(0,10,0,10));

        HBox cityBox = new HBox(10);
        Label lblCity = new Label("City");
        Region r4 = new Region();
        TextField tfCity = new TextField();
        tfCity.setId("city");
        cityBox.getChildren().addAll(lblCity, r4, tfCity);
        HBox.setHgrow(r4, Priority.ALWAYS);
        cityBox.setPadding(new Insets(0,10,0,10));

        HBox postBox = new HBox(10);
        Label lblPost = new Label("Postal Code");
        Region r5 = new Region();
        TextField tfPost = new TextField();
        tfPost.setId("post");
        postBox.getChildren().addAll(lblPost, r5, tfPost);
        HBox.setHgrow(r5, Priority.ALWAYS);
        postBox.setPadding(new Insets(0,10,0,10));

        HBox cardBox = new HBox(10);
        Label lblCard = new Label("Credit Card Number");
        Region r6 = new Region();
        TextField tfCard = new TextField();
        tfCard.setId("card");
        cardBox.getChildren().addAll(lblCard, r6, tfCard);
        HBox.setHgrow(r6, Priority.ALWAYS);
        cardBox.setPadding(new Insets(0,10,0,10));

        CheckBox cbChanged = new CheckBox("Values Changed");
        cbChanged.setPadding(new Insets(10));
        cbChanged.setId("changed");

        HBox navBox = new HBox(10);
        Button btnPrev = new Button("     Prev     ");
        btnPrev.setId("prev");
        Region r7 = new Region();
        Label lblIndex = new Label("X of Y");
        lblIndex.setId("index");
        Region r8 = new Region();
        Button btnNext = new Button("     Next     ");
        btnNext.setId("next");
        navBox.getChildren().addAll(btnPrev, r7, lblIndex, r8, btnNext);
        HBox.setHgrow(r7, Priority.ALWAYS);
        HBox.setHgrow(r8, Priority.ALWAYS);
        navBox.setPadding(new Insets(0,10,0,10));

        Separator line = new Separator();

        HBox bottomBox = new HBox(10);
        Button btnConnect = new Button("  Connect  ");
        btnConnect.setId("connect");
        Region r9 = new Region();
        Button btnCommit = new Button("  Commit  ");
        btnCommit.setId("commit");
        bottomBox.getChildren().addAll(btnConnect, r9, btnCommit);
        HBox.setHgrow(r9, Priority.ALWAYS);
        bottomBox.setPadding(new Insets(0,10,0,10));

        VBox root = new VBox(10);
        root.setPadding(new Insets(10,0,10,0));
        root.getChildren().addAll(surnameBox, nameBox, addressBox, cityBox, postBox, cardBox, cbChanged, navBox, line, bottomBox);
        return new Scene(root);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Scene scene = createScene();
        Controller controller = new Controller();
        controller.connectToUI(scene);
        primaryStage.setTitle("Customer Database");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

CustomerModel

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

/**
 * Created by ydvma4-15 on 2017/05/12.
 */
public class CustomerModel {
    private String id;
    private StringProperty surname = new SimpleStringProperty();
    private StringProperty firstNames = new SimpleStringProperty();
    private StringProperty address = new SimpleStringProperty();
    private StringProperty city = new SimpleStringProperty();
    private StringProperty postalCode = new SimpleStringProperty();
    private StringProperty ccNo = new SimpleStringProperty();        //not a number, since no calculates will be performed on it

    public CustomerModel(String id,String surname, String firstNames, String address, String city, String postalCode, String ccNo){
        this.id =id;
        this.surname.set(surname);
        this.firstNames.set(firstNames);
        this.address.set(address);
        this.city.set(city);
        this.postalCode.set(postalCode);
        this.ccNo.set(ccNo);
    }

    public String getId() {
        return id;
    }

    public String getSurname() {
        return surname.get();
    }

    public StringProperty surnameProperty() {
        return surname;
    }

    public String getFirstNames() {
        return firstNames.get();
    }

    public StringProperty firstNamesProperty() {
        return firstNames;
    }

    public String getAddress() {
        return address.get();
    }

    public StringProperty addressProperty() {
        return address;
    }

    public String getCity() {
        return city.get();
    }

    public StringProperty cityProperty() {
        return city;
    }

    public String getPostalCode() {
        return postalCode.get();
    }

    public StringProperty postalCodeProperty() {
        return postalCode;
    }

    public String getCcNo() {
        return ccNo.get();
    }

    public StringProperty ccNoProperty() {
        return ccNo;
    }

    public CustomerModel clone(){
        return new CustomerModel(id, surname.get(), firstNames.get(), address.get(), city.get(), postalCode.get(), ccNo.get());
    }
}

Controller

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;

import javax.xml.transform.Result;
import java.sql.*;
import java.util.ArrayList;

/**
 * Created by ydvma4-15 on 2017/05/12.
 */
public class Controller {
    private Property<CustomerModel> curCustomer = new SimpleObjectProperty<>();
    private ArrayList<CustomerModel> customers = new ArrayList<>();
    private IntegerProperty curIndex = new SimpleIntegerProperty(-1);
    private IntegerProperty curSize = new SimpleIntegerProperty(0);

    private ArrayList<CustomerModel> updatedCustomers = new ArrayList<>();
    private CustomerModel original;
    private TextField lblSurname;
    private TextField lblName;
    private TextField lblAdd;
    private TextField lblCity;
    private TextField lblPost;
    private TextField lblCard;
    private Label lblIndex;
    private CheckBox cbChanged;
    private Button btnprev;
    private Button btnNext;
    private Button btnConnect;
    private Button btnCommit;
    private ChangeListener listener = ((observable, oldValue, newValue) -> cbChanged.setSelected(true));

    public void connectToDB() {
        try {
            String connectionString = "jdbc:sqlserver://OPENBOX\\WRR;databaseName=WRAP301XM1";

            Connection con = DriverManager.getConnection(connectionString, "T2017", "1");
            Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
            ResultSet resultSet = stmt.executeQuery("SELECT * FROM CUSTOMERS");
            while (resultSet.next()) {

                String id = resultSet.getString("pID");
                String surname = resultSet.getString("surname");
                String firstNames = resultSet.getString("firstNames");
                String address = resultSet.getString("address");
                String city = resultSet.getString("city");
                String postalCode = resultSet.getString("postalCode");
                String ccNo = resultSet.getString("creditCardNumber");

                CustomerModel toAdd = new CustomerModel(id, surname, firstNames, address, city, postalCode, ccNo);
                customers.add(toAdd);
            }
            resultSet.close();
            curSize.set(customers.size());
            if (customers.size() > 0) {
                curIndex.set(0);
            }
            stmt.close();
            con.close();

            //also, add a listener to the checkbox
            cbChanged.selectedProperty().addListener((observable, oldValue, newValue) -> {
                if(newValue == true){
                    if(!updatedCustomers.contains(curCustomer.getValue())){
                        updatedCustomers.add(curCustomer.getValue());
                    }
                }
            });
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public Controller() {
        setupProperties();
    }

    private void setupProperties() {

        curIndex.addListener((observable, oldValue, newValue) -> {
            curCustomer.setValue(customers.get(curIndex.get()));
        });

        curCustomer.addListener((observable, oldValue, newValue) -> {
            rebind(oldValue, newValue);
            original = newValue.clone();
            cbChanged.setSelected(updatedCustomers.contains(curCustomer.getValue()));
        });
    }

    private void rebind(CustomerModel oldValue, CustomerModel newValue) {

        if (oldValue != null) {
            //unbind
            lblSurname.textProperty().unbindBidirectional(oldValue.surnameProperty());
            lblName.textProperty().unbindBidirectional(oldValue.firstNamesProperty());
            lblAdd.textProperty().unbindBidirectional(oldValue.addressProperty());
            lblCity.textProperty().unbindBidirectional(oldValue.cityProperty());
            lblPost.textProperty().unbindBidirectional(oldValue.postalCodeProperty());
            lblCard.textProperty().unbindBidirectional(oldValue.ccNoProperty());

            //remove listeners
            lblSurname.textProperty().removeListener(listener);
            lblName.textProperty().removeListener(listener);
            lblAdd.textProperty().removeListener(listener);
            lblCity.textProperty().removeListener(listener);
            lblPost.textProperty().removeListener(listener);
            lblCard.textProperty().removeListener(listener);
        }

        if (newValue != null) {
            //bind
            lblSurname.textProperty().bindBidirectional(newValue.surnameProperty());
            lblName.textProperty().bindBidirectional(newValue.firstNamesProperty());
            lblAdd.textProperty().bindBidirectional(newValue.addressProperty());
            lblCity.textProperty().bindBidirectional(newValue.cityProperty());
            lblPost.textProperty().bindBidirectional(newValue.postalCodeProperty());
            lblCard.textProperty().bindBidirectional(newValue.ccNoProperty());

            //add listeners
            lblSurname.textProperty().addListener(listener);
            lblName.textProperty().addListener(listener);
            lblAdd.textProperty().addListener(listener);
            lblCity.textProperty().addListener(listener);
            lblPost.textProperty().addListener(listener);
            lblCard.textProperty().addListener(listener);
        }
    }

    private void next() {
        if (curIndex.get() < customers.size() - 1) {
            curIndex.set(curIndex.get() + 1);
        }
    }

    private void prev() {
        if (curIndex.get() > 0) {
            curIndex.set(curIndex.get() - 1);
        }
    }

    private void update() {
        try {
            String connectionString = "jdbc:sqlserver://OPENBOX\\WRR;databaseName=WRAP301XM1";
            Connection con = DriverManager.getConnection(connectionString, "T2017", "1");
            Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
            for (CustomerModel cur : updatedCustomers) {
                String id = cur.getId();
                String surname = cur.getSurname();
                String firstNames = cur.getFirstNames();
                String address = cur.getAddress();
                String city = cur.getCity();
                String postalCode = cur.getPostalCode();
                String ccNo = cur.getCcNo();

                String sql = "UPDATE CUSTOMERS SET SURNAME = '" + surname + "', FIRSTNAMES = '" + firstNames + "'," +
                        "ADDRESS = '" + address + "', CITY = '" + city + "', POSTALCODE = '" + postalCode + "', " +
                        "CREDITCARDNUMBER = '" + ccNo + "' WHERE PID = '" + id + "'";
                stmt.execute(sql);
            }
            updatedCustomers = new ArrayList<>();
            cbChanged.setSelected(false);
            stmt.close();
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void revert() {
        updatedCustomers.remove(curCustomer.getValue());
        curCustomer.setValue(original.clone());
    }

    public void connectToUI(Scene scene) {

        lblSurname = (TextField) scene.lookup("#surname");
        lblName = (TextField) scene.lookup("#name");
        lblAdd = (TextField) scene.lookup("#address");
        lblCity = (TextField) scene.lookup("#city");
        lblPost = (TextField) scene.lookup("#post");
        lblCard = (TextField) scene.lookup("#card");
        lblIndex = (Label) scene.lookup("#index");
        cbChanged = (CheckBox) scene.lookup("#changed");
        btnprev = (Button) scene.lookup("#prev");
        btnNext = (Button) scene.lookup("#next");
        btnConnect = (Button) scene.lookup("#connect");
        btnCommit = (Button) scene.lookup("#commit");

        cbChanged.setOnAction(event -> {
            if (cbChanged.isSelected() == false) {
                revert();
            }
        });
        btnprev.setOnAction(event -> prev());
        btnNext.setOnAction(event -> next());
        btnConnect.setOnAction(event -> connectToDB());
        btnCommit.setOnAction(event -> update());

        lblIndex.textProperty().bind((curIndex.add(1)).asString().concat(" of ").concat(curSize.asString()));
    }
}

Short Binding Q

Main

package sample;

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

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

Controller

package sample;

import javafx.beans.binding.Bindings;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableArray;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.util.StringConverter;
import javafx.util.converter.NumberStringConverter;

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

public class Controller implements Initializable{
    public TextField txt1st;
    public TextField txt2nd;
    public Label lbl1st;
    public Label lbl2nd;
    public ListView lbx;

    public ArrayList<String>items=new ArrayList<String>();
    public ObservableList<String>observableItems= FXCollections.observableArrayList(items);

    public IntegerProperty int1st=new SimpleIntegerProperty(0);

    public void addClicked(ActionEvent actionEvent) {

        observableItems.add(txt1st.getText());
        txt1st.clear();
        System.out.println("Added..."+txt1st.getText());
    }

    public void removeClicked(ActionEvent actionEvent) {
        System.out.println("Removed");
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        lbx.setItems(observableItems);
        int1st.addListener((observable,newValue,oldValue)->{
            System.out.println(".....");
        });
        txt1st.textProperty().bindBidirectional(int1st, new NumberStringConverter());

        /*lbl1st.textProperty().bind(
            txt1st.textProperty()
        );*/
        lbl1st.textProperty().bind(
                Bindings.concat("Value = ",int1st)
        );

        lbl2nd.textProperty().bind(
                Bindings.concat("Selected = ",lbx.getSelectionModel().selectedItemProperty())
        );
    }
}

FXML

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

<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>


<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
   <children>
      <TextField fx:id="txt1st" />
      <TextField fx:id="txt2nd" />
      <Label fx:id="lbl1st" text="Label" />
      <Label fx:id="lbl2nd" text="Label" />
      <ListView fx:id="lbx" prefHeight="200.0" prefWidth="200.0" />
      <HBox prefHeight="100.0" prefWidth="200.0">
         <children>
            <Button fx:id="btn1st" mnemonicParsing="false" onAction="#addClicked" text="Add" />
            <Button fx:id="btn2nd" mnemonicParsing="false" onAction="#removeClicked" text="Remove" />
         </children>
      </HBox>
   </children>
</VBox>

GitHub – LadySith

Sith

Lusaka, Zambia

Computer Science student and a bunch of other things.