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>

Flipping Cards

Main

package nmmu.wrap301.cardflip;

import javafx.animation.*;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.geometry.Insets;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.GaussianBlur;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.transform.Rotate;
import javafx.util.Duration;

import java.util.Random;

public class Cards extends BorderPane {
    private static Image[] cards = null;

    //add the card properties and a set of booleans matching the state of each card
    private boolean faceup;
    private boolean dragging;
    private IntegerProperty suite = new SimpleIntegerProperty(0);
    private IntegerProperty value = new SimpleIntegerProperty(0);

    //location of card/borderpane
    private double AnchorX, AnchorY;

    //add animations and blur
    private DropShadow shadow;
    private Timeline animation;

    public int getSuite() {
        return suite.get();
    }

    public IntegerProperty suiteProperty() {
        return suite;
    }

    public void setSuite(int suite) {
        this.suite.set(suite);
    }

    public int getValue() {
        return value.get();
    }

    public IntegerProperty valueProperty() {
        return value;
    }

    public void setValue(int value) {
        this.value.set(value);
    }

    public Cards()
    {
        super();

        loadcards();
        newCard();
        SetUpAnimations();
        SetOnClicks();
        SetOnDragBehavior();

        SetShadows();

    }

    private void loadcards()
    {
        if(cards == null)
        {
            cards = new Image[19];
            cards[0] = new Image(Cards.class.getResourceAsStream("/back.png"));
            for(int i = 1; i <= 13; i++)
            {
                cards[i] = new Image(Cards.class.getResourceAsStream("/" + i + ".png"));


            }
            System.out.println("loaded numbers correctly");

            cards[14] = new Image(Cards.class.getResourceAsStream("/club.png"));
            cards[15] = new Image(Cards.class.getResourceAsStream("/diamond.png"));
            cards[16] = new Image(Cards.class.getResourceAsStream("/heart.png"));
            cards[17] = new Image(Cards.class.getResourceAsStream("/spade.png"));
        }
    }

    private void newCard()
    {
        setWidth(183);
        setHeight(275);
        flipCardDown();
    }

    private void flipCardDown()
    {
        ImageView back = new ImageView(cards[0]);


        value.setValue(value.get());
        suite.setValue(suite.get());

        back.setFitWidth(183);
        back.setFitHeight(275);

        this.setPadding(new Insets(0,0,0,0));
        this.setBottom(null);
        this.setTop(null);
        this.setCenter(back);
        this.toFront();
        faceup = false;


    }

    private void SetOnClicks()
    {
        setOnMouseClicked(event -> {
            if(event.getButton() == MouseButton.PRIMARY && (event.getClickCount() == 2))
            {

                animation.play();


                //if you want to spin or rotate the cards continuesly

                /*RotateTransition rotator = new RotateTransition(Duration.millis(10000), this);
                rotator.setAxis(Rotate.Y_AXIS);
                rotator.setFromAngle(0);
                rotator.setToAngle(360);
                rotator.setInterpolator(Interpolator.LINEAR);
                rotator.setCycleCount(1);
                rotator.playFromStart();*/



            }
        });
    }

    private void SetOnDragBehavior()
    {
        setOnMousePressed(event -> {
            AnchorX = event.getScreenX() - this.getLayoutX();
            AnchorY = event.getScreenY() - this.getLayoutY();
        });

        setOnMouseDragged(event -> {
            if(event.getButton() == MouseButton.PRIMARY)
            {
                this.setLayoutX(event.getSceneX() - 92); //select middle of card
                this.setLayoutY(event.getSceneY() - 137);
                 if(!dragging)
                 {
                     setScaleX(1.1);
                     setScaleY(1.1);
                 }
                 dragging = true;

            }

        });

        setOnMouseReleased(event -> {
            if(dragging &&(event.getButton() == MouseButton.PRIMARY))
            {
                setScaleX(1);
                setScaleY(1);

                dragging = false;
            }
        });
    }

    private void SetUpAnimations()
    {
        animation = new Timeline();
        for(int x = 0; x <= 5; x++)
        {
            int end = x;
            KeyFrame key = new KeyFrame(new Duration(x*50), event -> {
                this.setScaleX(1 - end * (0.2));
                shadow.setRadius(10 * end);
            });
            animation.getKeyFrames().add(key);
        }
        KeyFrame flipcard = new KeyFrame(Duration.millis(500), event -> {flipCard();} );
        animation.getKeyFrames().add(flipcard);
        for(int x = 0; x <= 5; x++)
        {
            int end = x;
            KeyFrame key = new KeyFrame(new Duration(250 + x*50), event -> {
                this.setScaleX(end * (0.2));
                shadow.setRadius(50 - 5*end);
            });
            animation.getKeyFrames().add(key);
        }

    }

    private void flipCard()
    {
        this.getChildren().removeAll();
        if(faceup)
        {
            flipCardDown();
        }
        else
        {
            setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY,Insets.EMPTY)));


            faceup = true;
            this.toFront();
            setCard(cards[suite.get()], cards[value.get()]);
        }
    }

    private void setCard(Image suite, Image number)
    {
        getChildren().removeAll();

        ImageView view = new ImageView(suite);
        ImageView numTop = new ImageView(number);
        ImageView numBot = new ImageView(number);

        view.setFitWidth(163);
        view.setFitHeight(190);
        numTop.setFitHeight(30);
        numBot.setFitHeight(30);

        AnchorPane pane = new AnchorPane();
        pane.getChildren().add(numTop);
        pane.setRightAnchor(numTop,0.0);
        this.setPadding(new Insets(10));
        this.setTop(pane);
        this.setCenter(view);
        this.setBottom(numBot);
    }

    public void SetShadows()
    {
        shadow = new DropShadow();
        shadow.setColor(Color.BLACK);
        shadow.setRadius(0);
        shadow.setOffsetX(5);
        shadow.setOffsetY(5);
        setEffect(shadow);
    }


}

Card

package nmmu.wrap301.cardflip;

import javafx.animation.*;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.geometry.Insets;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.GaussianBlur;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.transform.Rotate;
import javafx.util.Duration;

import java.util.Random;

public class Cards extends BorderPane {
    private static Image[] cards = null;

    //add the card properties and a set of booleans matching the state of each card
    private boolean faceup;
    private boolean dragging;
    private IntegerProperty suite = new SimpleIntegerProperty(0);
    private IntegerProperty value = new SimpleIntegerProperty(0);

    //location of card/borderpane
    private double AnchorX, AnchorY;

    //add animations and blur
    private DropShadow shadow;
    private Timeline animation;

    public int getSuite() {
        return suite.get();
    }

    public IntegerProperty suiteProperty() {
        return suite;
    }

    public void setSuite(int suite) {
        this.suite.set(suite);
    }

    public int getValue() {
        return value.get();
    }

    public IntegerProperty valueProperty() {
        return value;
    }

    public void setValue(int value) {
        this.value.set(value);
    }

    public Cards()
    {
        super();

        loadcards();
        newCard();
        SetUpAnimations();
        SetOnClicks();
        SetOnDragBehavior();

        SetShadows();

    }

    private void loadcards()
    {
        if(cards == null)
        {
            cards = new Image[19];
            cards[0] = new Image(Cards.class.getResourceAsStream("/back.png"));
            for(int i = 1; i <= 13; i++)
            {
                cards[i] = new Image(Cards.class.getResourceAsStream("/" + i + ".png"));


            }
            System.out.println("loaded numbers correctly");

            cards[14] = new Image(Cards.class.getResourceAsStream("/club.png"));
            cards[15] = new Image(Cards.class.getResourceAsStream("/diamond.png"));
            cards[16] = new Image(Cards.class.getResourceAsStream("/heart.png"));
            cards[17] = new Image(Cards.class.getResourceAsStream("/spade.png"));
        }
    }

    private void newCard()
    {
        setWidth(183);
        setHeight(275);
        flipCardDown();
    }

    private void flipCardDown()
    {
        ImageView back = new ImageView(cards[0]);


        value.setValue(value.get());
        suite.setValue(suite.get());

        back.setFitWidth(183);
        back.setFitHeight(275);

        this.setPadding(new Insets(0,0,0,0));
        this.setBottom(null);
        this.setTop(null);
        this.setCenter(back);
        this.toFront();
        faceup = false;


    }

    private void SetOnClicks()
    {
        setOnMouseClicked(event -> {
            if(event.getButton() == MouseButton.PRIMARY && (event.getClickCount() == 2))
            {

                animation.play();


                //if you want to spin or rotate the cards continuesly

                /*RotateTransition rotator = new RotateTransition(Duration.millis(10000), this);
                rotator.setAxis(Rotate.Y_AXIS);
                rotator.setFromAngle(0);
                rotator.setToAngle(360);
                rotator.setInterpolator(Interpolator.LINEAR);
                rotator.setCycleCount(1);
                rotator.playFromStart();*/



            }
        });
    }

    private void SetOnDragBehavior()
    {
        setOnMousePressed(event -> {
            AnchorX = event.getScreenX() - this.getLayoutX();
            AnchorY = event.getScreenY() - this.getLayoutY();
        });

        setOnMouseDragged(event -> {
            if(event.getButton() == MouseButton.PRIMARY)
            {
                this.setLayoutX(event.getSceneX() - 92); //select middle of card
                this.setLayoutY(event.getSceneY() - 137);
                 if(!dragging)
                 {
                     setScaleX(1.1);
                     setScaleY(1.1);
                 }
                 dragging = true;

            }

        });

        setOnMouseReleased(event -> {
            if(dragging &&(event.getButton() == MouseButton.PRIMARY))
            {
                setScaleX(1);
                setScaleY(1);

                dragging = false;
            }
        });
    }

    private void SetUpAnimations()
    {
        animation = new Timeline();
        for(int x = 0; x <= 5; x++)
        {
            int end = x;
            KeyFrame key = new KeyFrame(new Duration(x*50), event -> {
                this.setScaleX(1 - end * (0.2));
                shadow.setRadius(10 * end);
            });
            animation.getKeyFrames().add(key);
        }
        KeyFrame flipcard = new KeyFrame(Duration.millis(500), event -> {flipCard();} );
        animation.getKeyFrames().add(flipcard);
        for(int x = 0; x <= 5; x++)
        {
            int end = x;
            KeyFrame key = new KeyFrame(new Duration(250 + x*50), event -> {
                this.setScaleX(end * (0.2));
                shadow.setRadius(50 - 5*end);
            });
            animation.getKeyFrames().add(key);
        }

    }

    private void flipCard()
    {
        this.getChildren().removeAll();
        if(faceup)
        {
            flipCardDown();
        }
        else
        {
            setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY,Insets.EMPTY)));


            faceup = true;
            this.toFront();
            setCard(cards[suite.get()], cards[value.get()]);
        }
    }

    private void setCard(Image suite, Image number)
    {
        getChildren().removeAll();

        ImageView view = new ImageView(suite);
        ImageView numTop = new ImageView(number);
        ImageView numBot = new ImageView(number);

        view.setFitWidth(163);
        view.setFitHeight(190);
        numTop.setFitHeight(30);
        numBot.setFitHeight(30);

        AnchorPane pane = new AnchorPane();
        pane.getChildren().add(numTop);
        pane.setRightAnchor(numTop,0.0);
        this.setPadding(new Insets(10));
        this.setTop(pane);
        this.setCenter(view);
        this.setBottom(numBot);
    }

    public void SetShadows()
    {
        shadow = new DropShadow();
        shadow.setColor(Color.BLACK);
        shadow.setRadius(0);
        shadow.setOffsetX(5);
        shadow.setOffsetY(5);
        setEffect(shadow);
    }


}

GitHub – LadySith

Yaa

Lusaka, Zambia

Computer Science student and a bunch of other things.