$29
Question 1: Displaying Three Cards
Problem Description:
Display a frame that contains three labels. Each label displays a card, as shown in the figure below. The card image files are named 1.png, 2.png, ..., 54.png and stored in the image/card directory. All three cards are distinct and selected randomly.
The image icons can be found in the attached card folder.
Your Task:
1. Create three ImageView and set their icons using the images.
2. Display three images from 54 image cards randomly.
Your Code:
Copy-paste your code here:
/**
• Jefferson Xie
• 100619840
• Display 3 Cards
•
• Method to generate 3 unique integers to randomize cards was
• taken from stack overflow.
*
* */
//Import miscellaneous requirements
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.Collections;
//Main Class
public class DisplayThreeCards extends Application { Page 2 of 17
//Default generate
public static void main(String[] args) {
launch(args);
}
//Primary Stage
@Override
public void start(Stage primaryStage) {
//List of integers populated from 1-54 to reflect order of the deck ArrayList<Integer> deck = new ArrayList<>(); for (int i = 0; i < 54; i++) {
deck.add(i + 1);
}
//Using built in function to randomize order of the deck Collections.shuffle(deck);
Pane pane = new HBox(10);
pane.setPadding(new Insets(5,5,5,5));
//Add images to Hbox Layout
pane.getChildren().add(new ImageView(new Image("image/Cards/" + deck.get(0) + ".png")));
pane.getChildren().add(new ImageView(new Image("image/Cards/" + deck.get(1) + ".png")));
pane.getChildren().add(new ImageView(new Image("image/Cards/" + deck.get(2) + ".png")));
//Miscellaneous scene and stage settings Scene scene = new Scene(pane); primaryStage.setTitle("Q1: Display Three Cards"); primaryStage.setScene(scene); primaryStage.show();
}
}
Screen shots:
Include two screen shots here:
Page 3 of 17
Page 4 of 17
Question 2: Investment-Value calculator
Problem Description:
Write a program that calculates the future value of an investment at a given interest rate for a specified number of years. The formula for the calculation is as follows:
futureValue = investmentAmount * (1 + monthlyInterestRate)years*12
Your Task:
Use text fields for interest rate, investment amount, and years. Display the future amount in a text field when the user clicks the Calculate button, as shown in the figure.
Your Code:
/**
• Jefferson Xie
• 100619840
• Investment Value Calculator
•
•
• */
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class InvestmentValueCalc extends Application {
//Default Generate
public static void main(String[] args) {
launch(args);
Page 5 of 17
}
//Primary Stage
@Override
public void start(Stage primaryStage) {
//Basic Text Field Declarations TextField investField = new TextField(); TextField yearsField = new TextField(); TextField rateField = new TextField(); TextField futureVField = new TextField(); Button btCalculate = new Button("Calculate");
//Create Interface
GridPane pane = new GridPane();
pane.setPadding(new Insets(5,5,5,5));
pane.add(new Label("Investment Amount"),0,0);
pane.add(new Label("Years"),0,1);
pane.add(new Label("Annual Interest Rate"),0,2);
pane.add(new Label("Future Value"),0,3);
pane.add(investField,1,0);
pane.add(yearsField,1,1);
pane.add(rateField,1,2);
pane.add(futureVField,1,3);
• futureVField.setEditable(false); futureVField.setDisable(true);
pane.add(btCalculate,1,4);
//Calculate Future Value On Action (Auto anonymous lambda function, not exactly sure how IDE made this)
EventHandler<ActionEvent> event = e -> {
//Get Values From Text Fields
double amount = Double.parseDouble(investField.getText()); int years = Integer.parseInt(yearsField.getText());
double interestRate = Double.parseDouble(rateField.getText()) / (12*100); //To match sample, /1200
//Find Out Future Value
double futureValue = amount * Math.pow(1 + interestRate,
years*12);
futureVField.setText(String.format("%.2f", futureValue));
};
btCalculate.setOnAction(event);
//Miscellaneous scene and stage settings
Scene scene = new Scene(pane);
primaryStage.setTitle("Q2: Invest-Value Calculator");
primaryStage.setScene(scene);
primaryStage.show();
}
}
Page 6 of 17
Screen shots:
Include two screen shots here:
Page 7 of 17
Question 3: Dragging Points on a Circle
Problem Description:
Draw a circle with three random points on the circle. Connect the points to form a triangle. Display the angles in the triangle. Use the mouse to drag a point along the perimeter of the circle. As you drag it, the triangle and angles are redisplayed dynamically.
60
65
55
Here is the formula to compute angles:
x2, y2
a
B
c
C
A
x3, y3
b
x1, y1
A = acos((a * a - b * b - c * c) / (-2 * b * c))
B = acos((b * b - a * a - c * c) / (-2 * a * c))
C = acos((c * c - b * b - a * a) / (-2 * a * b))
Your Code:
Copy-paste your code here:
/**
• Jefferson Xie
• 100619840
• Drag Points On a Circle
• Idea on how to keep dragging point along the circle was taken from stackoverflow
•
*/
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
Page 8 of 17
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class CircleDragging extends Application {
public static void main(String[] args) {
launch(args);
}
//Base Pane Declaration
Pane pane = new Pane();
//Main Circle
Circle c = new Circle();
//Sub Circles, Lines, and Text
Circle[] p = new Circle[3];
Line[] lines = new Line[3];
Label[] labels = new Label[3];
//Pane Size
double width = 500;
double height = 500;
@Override
public void start(Stage primaryStage) {
//Big Circle Properties
c.setCenterX(width/2);
c.setCenterY(height/2);
c.setRadius(height/2 - 50);
pane.getChildren().add(c);
c.setFill(Color.TRANSPARENT);
c.setStroke(Color.BLACK);
//Populate Lists
for (int i = 0; i < 3; i++) {
p[i] = new Circle();
lines[i] = new Line();
labels[i] = new Label();
}
//List properties
for (int i = 0; i < 3; i++) {
p[i].setRadius(5);
p[i].setCenterX(c.getCenterX() + c.getRadius() * Math.cos(i*i)); p[i].setCenterY(c.getCenterY() - c.getRadius() * Math.sin(i*i)); p[i].setFill(Color.RED);
p[i].setStroke(Color.BLACK);
declareAction(p[i]);
//Perhaps there is a better way to do this
if (i != 2){
lines[i].startXProperty().bind(p[i].centerXProperty());
Page 9 of 17
lines[i].startYProperty().bind(p[i].centerYProperty()); lines[i].endXProperty().bind(p[i+1].centerXProperty()); lines[i].endYProperty().bind(p[i+1].centerYProperty());
} else {
lines[i].startXProperty().bind(p[i].centerXProperty()); lines[i].startYProperty().bind(p[i].centerYProperty()); lines[i].endXProperty().bind(p[0].centerXProperty()); lines[i].endYProperty().bind(p[0].centerYProperty());
}
labels[i].layoutXProperty().bind(p[i].centerXProperty().add(5)); labels[i].layoutYProperty().bind(p[i].centerYProperty().add(5));
}
//Immediately give values to labels
update();
//Populate pane
pane.getChildren().addAll(lines);
pane.getChildren().addAll(labels);
pane.getChildren().addAll(p);
//Populate stage
primaryStage.setScene(new Scene(pane, width, height)); primaryStage.setTitle("Dragging Points On A Circle"); primaryStage.show();
}
//Method to control mouse drag
private void declareAction(Circle circle) { circle.setOnMouseDragged(e -> {
double alpha = Math.PI / 2 - Math.atan2(e.getX() - c.getCenterX(), e.getY() - c.getCenterY());
circle.setCenterX(c.getCenterX() + c.getRadius() * Math.cos(alpha));
circle.setCenterY(c.getCenterY() + c.getRadius() * Math.sin(alpha));
update();
});
}
//Method to update labels
public void update() {
double a = length(p[0], p[1]);
double b = length(p[1], p[2]);
double c = length(p[2], p[0]);
double A = Math.toDegrees(Math.acos((a * a - b * b - c * c) / (-2 * b
* c)));
double B = Math.toDegrees(Math.acos((b * b - a * a - c * c) / (-2 * a
* c)));
double C = Math.toDegrees(Math.acos((c * c - b * b - a * a) / (-2 * a
* b)));
labels[0].setText(String.valueOf(Math.round(B))); labels[1].setText(String.valueOf(Math.round(C))); labels[2].setText(String.valueOf(Math.round(A)));
Page 10 of 17
}
//Method To return distance between two circles private double length(Circle c1, Circle c2) {
return Math.sqrt(Math.pow(c1.getCenterX() - c2.getCenterX(), 2) + Math.pow(c1.getCenterY() - c2.getCenterY(), 2));
}
}
Screen shots:
Include two screen shots here:
Page 11 of 17
Page 12 of 17
Question 4: Histogram
Problem Description:
Develop a program that displays a histogram to show the occurrences of each letter in a text area. The histogram should show the occurrences of each letter in a text file, as shown in the following figure. Assume that the letters are not case sensitive.
Your Task:
• Place a pane that will display the histogram in the center of the frame.
• Place a label and a text field in a panel, and put the panel in the south side of the frame. The text file will be entered from this text field.
• Pressing the Enter key on the text field causes the program to count the occurrences of each letter and display the count in a histogram.
Your Code:
Copy-paste your code here:
/**
• Jefferson Xie
• 100619840
• Histogram
*
• Inspiration on how to count individual letters in a file was taken from stackoverflow
•
• */
//Generic Imports
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
Page 13 of 17
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
//Main Class
public class Histogram extends Application {
//Default generate
public static void main(String[] args) {
launch(args);
}
//Objects required to be outside of main stage in order for methods to
work
BorderPane mainPane = new BorderPane();
TextField txtFileName = new TextField();
CategoryAxis xAxis = new CategoryAxis();
NumberAxis yAxis = new NumberAxis();
BarChart barChart = new BarChart(xAxis, yAxis);
@Override
public void start(Stage primaryStage) throws Exception {
//Array of int to contain number of characters int[] counts = new int[26];
//Label, txtFile, and button for main UI
Label lFileName = new Label("Filename:", txtFileName); lFileName.setContentDisplay(ContentDisplay.RIGHT); txtFileName.setPrefColumnCount(20); txtFileName.setPromptText("sample2.txt");
Button btView = new Button("View");
//HBox to contain label, textfield and button HBox hBox = new HBox(lFileName, btView); hBox.setSpacing(5);
//Axis labels for histogram
xAxis.setLabel("Characters");
yAxis.setLabel("Count");
//Histogram Default size
barChart.setPrefHeight(300);
barChart.setPrefWidth(800);
//Update histogram with empty characters
updateData(counts);
//Method to respond to user pressing enter key
Page 14 of 17
txtFileName.setOnKeyPressed((event) -> { if(event.getCode() == KeyCode.ENTER) {
fileSearch(txtFileName.getText(), counts);
}
});
//Vbox to contain histogram/bar chart
VBox vBox = new VBox(barChart);
mainPane.setBottom(hBox);
mainPane.setCenter(vBox);
//Method to respond to view being pressed
btView.setOnAction(e -> {
fileSearch(txtFileName.getText(), counts);
});
//Main Scene Setup
Scene scene = new Scene(mainPane);
primaryStage.setScene(scene);
primaryStage.setTitle("Q4: Histogram");
vBox.requestFocus();
primaryStage.show();
}
//Method to find file. If file not found, display in console. TODO: Add prompt in UI for file missing
public void fileSearch(String filename, int[] counts) { try (Scanner input = new Scanner(new File(filename))) {
//Reset values in count
Arrays.fill(counts, 0);
//Read text, check character count, update counts while(input.hasNext()) {
String word = input.next();
for(int i = 0; i < word.length(); i++) {
char c = Character.toUpperCase(word.charAt(i)); if (c >= 'A' && c <= 'Z')
counts[c - 'A']++;
}
}
updateData(counts);
} catch(FileNotFoundException ex) {
System.out.println("Incorrect file name/File not found");
}
}
//Method to update the data inside of the barchart/histogram public void updateData(int[] counts){
XYChart.Series dataSeries = new XYChart.Series(); for (int i = 'A'; i <= 'Z'; i++){
dataSeries.getData().add(new
XYChart.Data(Character.toString((char)i), counts[i-'A']));
}
barChart.getData().clear();
barChart.getData().add(dataSeries);
Page 15 of 17
}
}
Screen shots:
Include two screen shots here:
Page 16 of 17
Remember:
You need to complete this file and submit it in related drop box on Blackboard, in addition to uploading your codes in your git repository, before deadline.
Page 17 of 17