-
Notifications
You must be signed in to change notification settings - Fork 0
/
GpaController.java
304 lines (234 loc) · 9.45 KB
/
GpaController.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import java.net.URL;
import javafx.fxml.*;
import javafx.application.Platform;
import javafx.stage.Stage;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.*;
import java.util.*;
import javafx.collections.*;
import java.text.DecimalFormat;
public class GpaController implements Initializable {
private static final int DECIMAL_PRECISION = 2; //how many decimals to round to
private DecimalFormat numberFormatter = new DecimalFormat("0.00");
private static final int WINDOW_WIDTH = 591; //CSS is 571
private GpaModel model = new GpaModel();
private ArrayList<String> gradesOptions = new ArrayList<String>();
private ArrayList<Class> classes = new ArrayList<Class>();
private final int INITIAL_NUMBER_OF_CLASSES = 8;
private final int ROW_OFFSET = 1; //Row 1 defined in FXML for column headers
private int nextFreeClassRow = ROW_OFFSET; //next available row to insert a class
@FXML private GridPane classesPane;
@FXML private TextField currentGPA;
@FXML private Label currentGPAError;
@FXML private TextField currentCredits;
@FXML private Label currentCreditsError;
@FXML private Button addClassButton;
@FXML private Label gpaOverall;
public GpaController(){
gradesOptions.add("A+");
gradesOptions.add("A");
gradesOptions.add("A-");
gradesOptions.add("B+");
gradesOptions.add("B");
gradesOptions.add("B-");
gradesOptions.add("C+");
gradesOptions.add("C");
gradesOptions.add("C-");
gradesOptions.add("D+");
gradesOptions.add("D");
gradesOptions.add("D-");
gradesOptions.add("F");
}
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
for(int row=0+ROW_OFFSET; row<INITIAL_NUMBER_OF_CLASSES+ROW_OFFSET; row++){
Class newClass = addClass(row);
registerEventHandlers(newClass);
}
//Only allow decimal numbers
currentGPA.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
if (!newValue.matches("\\d*(\\.\\d*)?")) {
currentGPA.setText(oldValue);
}
}
});
addClassButton.setFocusTraversable(false);
currentCredits.textProperty().addListener(new PositiveIntegerTextFieldListener(currentCredits));
currentGPA.setOnAction(e -> calcGpa());
currentGPA.focusedProperty().addListener((observable, oldValue, newValue) -> {
calcGpa();
});
currentCredits.setOnAction(e -> calcGpa());
currentCredits.focusedProperty().addListener((observable, oldValue, newValue) -> {
calcGpa();
});
Platform.runLater(() -> classes.get(0).credits.requestFocus()); //Request focus must be AFTER he FXML is finished loading
}
private Class addClass(int row){
nextFreeClassRow++;
TextField title = new TextField();
title.getStyleClass().addAll("titleColumn");
Pane gradeContainer = new Pane();
gradeContainer.getStyleClass().addAll("gradeColumn");
ComboBox<String> gradeDropdown = new ComboBox<String>();
gradeDropdown.setItems(FXCollections.observableArrayList(gradesOptions));
gradeDropdown.setVisibleRowCount(gradesOptions.size());
gradeDropdown.setValue(gradesOptions.get(0));
gradeContainer.getChildren().addAll(gradeDropdown);
TextField credits = new TextField();
credits.getStyleClass().addAll("creditsColumn");
Pane qualityPointsContainer = new Pane();
qualityPointsContainer.getStyleClass().addAll("qualityPointsColumn");
Label qualityPoints = new Label();
qualityPointsContainer.getChildren().addAll(qualityPoints);
Button removeButton = new Button("Remove");
removeButton.getStyleClass().addAll("removeColumn");
removeButton.setFocusTraversable(false);
classesPane.add(title, 0, row);
classesPane.add(gradeContainer, 1, row);
classesPane.add(credits, 2, row);
classesPane.add(qualityPointsContainer, 3, row);
classesPane.add(removeButton, 4, row);
Class newClass = new Class(row, title, gradeDropdown, credits, qualityPoints, removeButton);
classes.add(newClass);
return newClass;
}
private void registerEventHandlers(Class newClass){
newClass.grade.setItems(FXCollections.observableArrayList(gradesOptions));
newClass.grade.setValue(gradesOptions.get(0));
newClass.grade.setOnAction(e -> validateAndCalculateClass(newClass));
newClass.credits.focusedProperty().addListener(new ClassTextFieldListener(newClass));
newClass.credits.setOnAction(e -> validateAndCalculateClass(newClass));
newClass.credits.textProperty().addListener(new PositiveIntegerTextFieldListener(newClass.credits));
newClass.removeButton.setOnAction(e -> removeClass(newClass.id));
}
private void removeClass(int row){
Set<Node> deleteNodes = new HashSet<Node>();
for (Node child : classesPane.getChildren()) {
Integer rowIndex = GridPane.getRowIndex(child); // get index from child
// handle null values for index=0
int r = rowIndex == null ? 0 : rowIndex;
if (r > row) { // decrement rows for rows after the deleted row
GridPane.setRowIndex(child, r-1);
}
else if (r == row) { // collect matching rows for deletion
deleteNodes.add(child);
}
}
classesPane.getChildren().removeAll(deleteNodes); // remove nodes from row
//decrement row IDs for Class objects BELOW the deleted row
for(int i=row; i<classes.size(); i++){
classes.get(i).id = classes.get(i).id -1;
}
classes.remove(row-1); //Remove from class list (-1 offset since GUI starts at row=1 & arrays count from 0)
nextFreeClassRow--; //decrement next available row since 1 was removed
resizeWindow();
calcGpa();
}
public void handleAddClassButton(ActionEvent event){
Class newClass = addClass(nextFreeClassRow); //add new class at current available row
registerEventHandlers(newClass);
resizeWindow();
}
private void resizeWindow(){
((Stage)classesPane.getScene().getWindow()).sizeToScene();
((Stage)classesPane.getScene().getWindow()).setWidth(WINDOW_WIDTH);
}
//Validates the class currently in focus (class that the grade/credits belong to) & calculates GPA if all classes are valid (setting appropriate error labels)
public void validateAndCalculateClass(Class classObj){
//Validate current class & only print error for current class (avoids printing a ton of errors at the beginning)
if(model.isClassValid(classObj)){
model.setQualityPoints(classObj);
classObj.qualityPointsLabel.getStyleClass().removeAll("errorLabel");
}
else{
classObj.qualityPointsLabel.setText("Credits can't be empty");
classObj.qualityPointsLabel.getStyleClass().addAll("errorLabel");
}
calcGpa();
}
public void calcGpa(){
//Clear existing error text
currentGPAError.setText("");
currentCreditsError.setText("");
//Display error if only 1 field has a value
if(GpaModel.isEmptyString(currentGPA.getText()) && !GpaModel.isEmptyString(currentCredits.getText())){
currentGPAError.setText("Current GPA required");
}
else if(!GpaModel.isEmptyString(currentGPA.getText()) && GpaModel.isEmptyString(currentCredits.getText())){
currentCreditsError.setText("Current Credits required");
}
else if(!GpaModel.isEmptyString(currentGPA.getText())){ //Else check number is in bounds
currentGPAError.setText(model.getGPAErrorIfInvalid(currentGPA.getText()));
}
model.calcGpaOverall(classes, currentGPA, currentCredits);
gpaOverall.setText(numberFormatter.format(roundDown(model.getGpaOverall(), DECIMAL_PRECISION)));
}
@FXML
public void handleResetButton(ActionEvent event){
model.reset();
for(Class c : classes){
c.title.setText("");
c.grade.setValue(gradesOptions.get(0));
c.credits.setText("");
c.qualityPointsLabel.setText("");
}
currentGPA.setText("");
currentGPAError.setText("");
currentCredits.setText("");
currentCreditsError.setText("");
gpaOverall.setText("0.00");
if(!classes.isEmpty()){
classes.get(0).credits.requestFocus();
}
}
class ClassTextFieldListener implements ChangeListener<Boolean> {
private Class classObj;
public ClassTextFieldListener(Class classObj) {
this.classObj=classObj;
}
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if(!newValue){ // check if focus gained or lost
validateAndCalculateClass(classObj);
}
}
}
class PositiveIntegerTextFieldListener implements ChangeListener<String> {
private TextField textField;
public PositiveIntegerTextFieldListener(TextField textField){
this.textField = textField;
}
@Override //Only allow positive integers
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
if (!newValue.matches("\\d*")) {
textField.setText(newValue.replaceAll("\\D", ""));
}
if(newValue.matches("0+")){
textField.setText(oldValue);
}
}
}
//auto-convert numbers to text for setting GUI elements
public static String numToText(double number){
return numToText(number + "");
}
//String parameter version just in case argument type changes
public static String numToText(String number){
return number;
}
public static double round(double number, int decimals){
double powerOfTen= Math.pow(10, decimals); //must be a double to avoid integer division truncation errors
return Math.round(number * powerOfTen ) / powerOfTen;
}
public static double roundDown(double number, int decimals){
double powerOfTen= Math.pow(10, decimals); //must be a double to avoid integer division truncation errors
return Math.floor(number * powerOfTen) / powerOfTen;
}
}