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);
    }


}

TableView Exam Question

Main

package nmmu.wrap301.Question2;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;



public class MainQ2 {
    static Connection conn = null;
    static Statement stmt = null;
    public static void main(String[] args) {
        connectToDB();
    }

    public static <T> ArrayList<T> extract(Class<T> rowClass, ResultSet rs) throws SQLException, IllegalAccessException, InstantiationException {
        ArrayList<T> temp = new ArrayList<T>();

        while(rs.next()){
            //Retrieve by column name
            int pid = rs.getInt("pID");
            String lname = rs.getString("surname");
            String fname = rs.getString("firstNames");
            String address = rs.getString("address");
            String city = rs.getString("city");
            String pcode = rs.getString("postalCode");
            String creditNr = rs.getString("creditCardNumber");


            //add to list or display values
            Customer c = (Customer)rowClass.newInstance();

            c.pID = pid;
            c.surname = lname;
            c.firstNames = fname;
            c.address = address;
            c.city = city;
            c.postalCode = pcode;
            c.creditCardNumber = creditNr;

            temp.add((T)c);

        }

       return temp;
    }

    public static void connectToDB()
    {
        try{
            //establish connection to database
           Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

            System.out.println("Connecting to database");
            conn = DriverManager.getConnection("jdbc:sqlserver://OPENBOX.nmmu.ac.za\\WRR;databaseName=WRAP301XM1", "XM1User" ,"June2016");

            System.out.println("Creating statement");
            stmt = conn.createStatement();  //extra input required?

            //Get Resultant set
            ResultSet rs = stmt.executeQuery("SELECT * FROM customers");

            //extract data from resultant set
            ArrayList<Customer> customers = extract(Customer.class, rs);

            // display object list
            for(Customer customer : customers) {
                System.out.println(customer);
            }

            //close everything
            rs.close();
            stmt.close();
            conn.close();

        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Customer

package nmmu.wrap301.Question2;


public class Customer {
    public Integer pID;
    public String surname;
    public String firstNames;
    public String address;
    public String city;
    public String postalCode;
    public String creditCardNumber;

    @Override
    public String toString() {
        return String.format("%s: %s, %s at %s, %s, %s, CCN = %s",
                pID, surname, firstNames, address, city, postalCode, creditCardNumber);
    }
}

FXML Binding

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("FXML Example");
        primaryStage.setScene(new Scene(root));
        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.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.util.converter.NumberStringConverter;

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

public class Controller implements Initializable {
    // controls initialised using reflection. name of field MUST be the same as the fx:id
    public TextField txtX;
    public TextField txtY;
    public Label lblResult;
    public Button btnCalculate;
    public Label lblProduct;

    // custom properties
    public IntegerProperty xProperty = new SimpleIntegerProperty(0);
    public IntegerProperty yProperty = new SimpleIntegerProperty(0);

    // event method linked using reflection. name of method MUST match the onAction field
    public void btnCalculateClicked(ActionEvent actionEvent) {
        int x = Integer.parseInt(txtX.getText());
        int y = Integer.parseInt(txtY.getText());
        int result = x + y;
        lblResult.setText("Sum = " + result);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // bind text fields to integer properties
        txtX.textProperty().bindBidirectional(xProperty, new NumberStringConverter());
        txtY.textProperty().bindBidirectional(yProperty, new NumberStringConverter());

        // bind label's text property to product of x and y properties
        lblProduct.textProperty().bind(
                Bindings.concat("Product = ", xProperty.multiply(yProperty).asString())
        );
    }
}

FXML

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

<?import javafx.geometry.*?>
<?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?>

<GridPane alignment="center" hgap="10" vgap="10" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
          fx:controller="sample.Controller">
    <children>
        <Label text="X" GridPane.columnIndex="1"/>
        <TextField fx:id="txtX" promptText="Enter integer" GridPane.columnIndex="2"/>
        <TextField fx:id="txtY" promptText="Enter integer" GridPane.columnIndex="2" GridPane.rowIndex="2"/>
        <Label text="Y" GridPane.columnIndex="1" GridPane.rowIndex="2"/>
        <Label fx:id="lblResult" maxWidth="1.7976931348623157E308" prefHeight="21.0" prefWidth="58.0" text="Sum = ?"
               GridPane.columnIndex="1" GridPane.columnSpan="2" GridPane.hgrow="ALWAYS" GridPane.rowIndex="3"/>
        <Button fx:id="btnCalculate" maxWidth="1.7976931348623157E308" mnemonicParsing="false"
                onAction="#btnCalculateClicked" text="Calculate Sum" GridPane.columnIndex="2"
                GridPane.columnSpan="2147483647" GridPane.hgrow="ALWAYS" GridPane.rowIndex="5"/>
        <Label fx:id="lblProduct" text="Product =" GridPane.columnIndex="1" GridPane.columnSpan="2"
               GridPane.rowIndex="4"/>
    </children>
    <columnConstraints>
        <ColumnConstraints/>
        <ColumnConstraints/>
        <ColumnConstraints/>
        <ColumnConstraints/>
        <ColumnConstraints/>
        <ColumnConstraints/>
    </columnConstraints>
    <rowConstraints>
        <RowConstraints/>
        <RowConstraints/>
        <RowConstraints/>
        <RowConstraints/>
        <RowConstraints/>
        <RowConstraints/>
    </rowConstraints>
    <padding>
        <Insets bottom="10.0" left="5.0" right="5.0" top="10.0"/>
    </padding>
</GridPane>

GitHub – LadySith

Sith

Lusaka, Zambia

Computer Science student and a bunch of other things.