Trying to assign an alarm with javafx - java

Hello there brilliant minds of stack overflow!
I am currently working on a personal program that should ultimately function as a reminder every 20 or so minutes to do another task(one of those productivity-boosting things) as well as a basic timer that will tell me when my shift is over # work.
I am having difficulty parsing the appropriate textfields into an int to place in the timers I am making(aswell as the profile object).
I know there are probably a couple ways to go about this please let me know your thoughts, here is my code so far:
package javafxneoalarm;
import java.util.Timer;
import java.util.TimerTask;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
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.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
/**
*
* #author Hvd
*/
public class JavaFXNeoAlarm extends Application {
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Neo Alarm");
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(25, 25, 25, 25));
Text sceneTitle = new Text("Welcome! \nPlease Enter Name &\nThe Hour/Minute of your Alarm");
sceneTitle.setFont(Font.font("Helvetica", FontWeight.NORMAL, 20));
grid.add(sceneTitle, 0, 0, 2, 1);
Button btn = new Button("Lets go!");
HBox hbBtn = new HBox(10);
hbBtn.setAlignment(Pos.BOTTOM_RIGHT);
hbBtn.getChildren().add(btn);
grid.add(hbBtn, 1, 4);
final Text actiontarget = new Text();
grid.add(actiontarget, 1, 6);
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e){
actiontarget.setFill(Color.FIREBRICK);
actiontarget.setText("Count-down initiated \nMay the force be with you");
}
});
Label userName = new Label("Name: \n");
grid.add(userName, 0, 1);
TextField userTextField = new TextField();
grid.add(userTextField, 1, 1);
Label a1 = new Label("Alarm1: \n");
grid.add(a1, 0, 2);
TextField a1BoxHr = new TextField();
grid.add(a1BoxHr, 1, 2);
TextField a1BoxMin = new TextField();
grid.add(a1BoxMin, 2, 2);
Label a2 = new Label("Alarm2: \n");
grid.add(a2, 0, 3);
TextField a2BoxHr = new TextField();
grid.add(a2BoxHr, 1, 3);
TextField a2BoxMin = new TextField();
grid.add(a2BoxMin, 2, 3);
Scene scene = new Scene(grid, 300, 275);
primaryStage.setScene(scene);
primaryStage.show();
// double 1BoxHr = Double.parseDouble(a1BoxHr);
// profileOne = new Profile(userTextField, (((a1BoxHr*60)+a1BoxMin)*60), (((a2BoxHr*60)+a2BoxMin)*60));
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
Timer alarmA1 = new Timer();
Timer alarmA2 = new Timer();
TimerTask task = new TimerTask()
{
public void run(){
// when timer goes off
}
};
Profile profileOne;
}
}
And the profile class:
package javafxneoalarm;
/**
*
* #author Hvd
*/
public class Profile {
// declare instance variables
private String user;
private double alarm1;
private double alarm2;
// constructor (overloaded, has new instance variable or parameter to apply maths through)
public Profile(String newUser, double newAlarm1, double newAlarm2){
user = newUser;
alarm1 = newAlarm1;
alarm2 = newAlarm2;
}
// getters
public String getUser(){
return user;
}
public double getAlarm1(){
return alarm1;
}
public double getAlarm2(){
return alarm2;
}
// setters
public void setUser(String newUser){
user = newUser;
}
public void setAlarm1(double newAlarm1){
alarm1 = newAlarm1;
}
public void setAlarm2(double newAlarm2){
alarm2 = newAlarm2;
}
}
So basically how do I assign the inputs to an alarm that will go off after x amount of time, also I would like the window to close/minimize to tray after inputting/submitting the profile information and re-open when the alarm goes off but that might be a challenge for another day.
Thanks a lot guys, I look forward to continuing this creative endeavor :)

Here's how to assign a double depending on the input in the textfield, I should be placing the assignment inside the button click:
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e){
actiontarget.setFill(Color.FIREBRICK);
actiontarget.setText("Count-down initiated \nMay the force be with you");
String BUser = userTextField.getText(); // sets variable BUser from inputs
double BAlarm1Hrs = Double.parseDouble(a1BoxHr.getText());
double BAlarm1Min = Double.parseDouble(a1BoxMin.getText());
double BAlarm1 = (((BAlarm1Hrs * 60) * 60) + (BAlarm1Min * 60)); // sets BAlarm1 to seconds of hrs and minutes inputted
double BAlarm2Hrs = Double.parseDouble(a2BoxHr.getText());
double BAlarm2Min = Double.parseDouble(a2BoxMin.getText());
double BAlarm2 = (((BAlarm2Hrs * 60) * 60) + (BAlarm2Min * 60));
Profile profileA = new Profile(BUser, BAlarm1, BAlarm2);
}
});

Related

Application will not display when JavaFX code is ran

I'm working on a very small, brief application to calculate charges for an upcoming conference. The app displayed fine when I ran the code until I added my event handler. Everything seems to be in check so I am unsure of what is happening. Any insight would be much appreciated.
//JavaFX imports
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ConferenceRegistration extends Application {
// Create radio buttons for conference event options
RadioButton generalAdmissionButton, studentAdmissionButton, keynoteDinnerButton, eCommerceButton, webFutureButton,
advancedJavaButton, securityButton;
Label labelAdmission, labelOptionalEvents, totalChargesLabel;
Button totalCharges;
public static void main(String[] args) {
// launch the application
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
// Label for admission type selection
labelAdmission = new Label("Please select your Admission type: ");
// mandatory selection for conference
generalAdmissionButton = new RadioButton("General Admission: $895");
studentAdmissionButton = new RadioButton("Student Admission: $495");
// Create toggle group for either admission group
ToggleGroup optionalEvents = new ToggleGroup();
generalAdmissionButton.setToggleGroup(optionalEvents);
studentAdmissionButton.setToggleGroup(optionalEvents);
// Label for optional conference events
labelOptionalEvents = new Label("Please Select All Optional Events You Will Be Attending: ");
// set values for optional conference events
keynoteDinnerButton = new RadioButton("Keynote Speech Dinner: $30");
eCommerceButton = new RadioButton("Introduction to E-commerce: $295");
webFutureButton = new RadioButton("The Future of the Web: $295");
advancedJavaButton = new RadioButton("Advanced Java Programming: $395");
securityButton = new RadioButton("Network Security: $395");
// Button for calculating total Conference charges
totalCharges = new Button("Calculate Total");
totalCharges.setOnAction(new TotalChargesCalculator());
// create Vbox container and add all labels, buttons
VBox vbox = new VBox(10, labelAdmission, generalAdmissionButton, studentAdmissionButton, labelOptionalEvents,
keynoteDinnerButton, eCommerceButton, webFutureButton, advancedJavaButton, securityButton, totalCharges,
totalChargesLabel);
// format vbox
vbox.setAlignment(Pos.CENTER);
vbox.setPadding(new Insets(20));
// create and set scene
Scene scene = new Scene(vbox);
stage.setTitle("Conference Registration");
stage.setScene(scene);
// show stage
stage.show();
}
class TotalChargesCalculator implements EventHandler<ActionEvent> {
#Override
public void handle(ActionEvent arg0) {
int result = 0;
try {
// check which radio buttons are selected
if (generalAdmissionButton.isSelected()) {
result = result + 895;
}
if (studentAdmissionButton.isSelected()) {
result = result + 495;
}
if (keynoteDinnerButton.isSelected()) {
result = result + 295;
}
if (eCommerceButton.isSelected()) {
result = result + 295;
}
if (webFutureButton.isSelected()) {
result = result + 295;
}
if (advancedJavaButton.isSelected()) {
result = result + 395;
}
if (securityButton.isSelected()) {
result = result + 395;
}
totalChargesLabel.setText(String.valueOf(result));
} catch (Exception e) {
if (generalAdmissionButton.isSelected() == false || studentAdmissionButton.isSelected() == false) {
totalChargesLabel.setText("Please Select Admission Type.");
}
}
}
}
}
Thanks for your time. I look forward to learning what I am overlooking.
You are not initializing totalChargesLabel.
Initialize it to an empty Label before adding it to the VBox:
totalChargesLabel = new Label();

Javafx Validation User Input Username & Password [duplicate]

This question already has answers here:
Reading a plain text file in Java
(31 answers)
Closed 5 years ago.
I have a program called "AddUser" that allows the user to type in their username and password, which will add this info to user.txt file. I also have a program called "Login" that takes the information the user inputs, username and password, and verifies the input against the user.txt file.
However, I cannot figure out how to validate the input for the Login program. I have found several other posts here, but not from validating from a text file. Any help or guidance would be GREATLY appreciated.
Program Add User
import javax.swing.JOptionPane;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.geometry.HPos;
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;
import java.io.*;
public class AddUser extends Application {
private TextField tfUsername = new TextField();
private TextField tfPassword = new TextField();
private Button btAddUser = new Button("Add User");
private Button btClear = new Button("Clear");
#Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Create UI
GridPane gridPane = new GridPane();
gridPane.setHgap(5);
gridPane.setVgap(5);
gridPane.add(new Label("Username:"), 0, 0);
gridPane.add(tfUsername, 1, 0);
gridPane.add(new Label("Password:"), 0, 1);
gridPane.add(tfPassword, 1, 1);
gridPane.add(btAddUser, 1, 3);
gridPane.add(btClear, 1, 3);
// Set properties for UI
gridPane.setAlignment(Pos.CENTER);
tfUsername.setAlignment(Pos.BOTTOM_RIGHT);
tfPassword.setAlignment(Pos.BOTTOM_RIGHT);
GridPane.setHalignment(btAddUser, HPos.LEFT);
GridPane.setHalignment(btClear, HPos.RIGHT);
// Process events
btAddUser.setOnAction(e -> writeNewUser());
btClear.setOnAction(e -> {
tfUsername.clear();
tfPassword.clear();
});
// Create a scene and place it in the stage
Scene scene = new Scene(gridPane, 300, 150);
primaryStage.setTitle("Add User"); // Set title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
public void writeNewUser() {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("users.txt", true))) {
bw.write(tfUsername.getText());
bw.newLine();
bw.write(tfPassword.getText());
bw.newLine();
}
catch (IOException e){
e.printStackTrace();
}
}
/**
* The main method is only needed for the IDE with limited
* JavaFX support. Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
}
Program Login
import javax.swing.JOptionPane;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.geometry.HPos;
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;
import java.io.*;
public class Login extends Application {
private TextField tfUsername = new TextField();
private TextField tfPassword = new TextField();
private Button btAddUser = new Button("Login");
private Button btClear = new Button("Clear");
#Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Create UI
GridPane gridPane = new GridPane();
gridPane.setHgap(5);
gridPane.setVgap(5);
gridPane.add(new Label("Username:"), 0, 0);
gridPane.add(tfUsername, 1, 0);
gridPane.add(new Label("Password:"), 0, 1);
gridPane.add(tfPassword, 1, 1);
gridPane.add(btAddUser, 1, 3);
gridPane.add(btClear, 1, 3);
// Set properties for UI
gridPane.setAlignment(Pos.CENTER);
tfUsername.setAlignment(Pos.BOTTOM_RIGHT);
tfPassword.setAlignment(Pos.BOTTOM_RIGHT);
GridPane.setHalignment(btAddUser, HPos.LEFT);
GridPane.setHalignment(btClear, HPos.RIGHT);
// Process events
btClear.setOnAction(e -> {
tfUsername.clear();
tfPassword.clear();
});
// Create a scene and place it in the stage
Scene scene = new Scene(gridPane, 300, 150);
primaryStage.setTitle("Login"); // Set title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
/**
* The main method is only needed for the IDE with limited
* JavaFX support. Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
}
Consider this Example (Explanation in Comments):
// create boolean variable for final decision
boolean grantAccess = false;
// get the user name and password when user press on login button
// you already know how to use action listener
// (i.e wrap the following code with action listener block of login button)
String userName = tfUsername.getText();
String password = tfPassword.getText();
File f = new File("users.txt");
try {
Scanner read = new Scanner(f);
int noOfLines=0; // count how many lines in the file
while(read.hasNextLine()){
noOfLines++;
}
//loop through every line in the file and check against the user name & password (as I noticed you saved inputs in pairs of lines)
for(int i=0; i<noOfLines; i++){
if(read.nextLine().equals(userName)){ // if the same user name
i++;
if(read.nextLine().equals(password)){ // check password
grantAccess=true; // if also same, change boolean to true
break; // and break the for-loop
}
}
}
if(grantAccess){
// let the user continue
// and do other stuff, for example: move to next window ..etc
}
else{
// return Alert message to notify the deny
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

JavaFX. How to change value of a label. Error: variable needs to be final or effectively final

I have a simple window with a button correctBut and a label Label pointsLbl = new Label("0") . I want the text of the pointsLbl to change everytime i hit the button. Initially the text of pointsLbl is "0". Then when I hit the button it should be "1";
So I created an additional variable int points, which is also initially 0. I thought I could add +1 to the value of points in the EventHandler, and than convert it to string and set it as a new text.
String newValStr = points.toString();
pointsLbl.setText(newValStr);
But I get the following Error: "variable points is accessed from within an inner class, needs to be final or effectively final".
So, how should have written the code, so that I could change values and then setText to the pointsLbl?
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.layout.GridPane;
import javafx.stage.Stage;
public class QuickGameWindow {
public static void display() {
Stage window = new Stage();
int points = 0;
String parsedPoints = "";
window.setTitle("New Window");
GridPane grid = new GridPane();
grid.setPadding(new Insets(10,10,10,10));
grid.setVgap(20);
grid.setHgap(10);
Button correctBut = new Button("Correct");
Label textLbl = new Label("Points - ");
Label pointsLbl = new Label("0");
correctBut.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
//Here comes the problem. I cannot change the value of points.
points++;
String newValStr = points.toString();
pointsLbl.setText(newValStr);
}
});
GridPane.setConstraints(correctBut, 3, 3);
GridPane.setConstraints(pointsLbl, 1, 5);
GridPane.setConstraints(textLbl, 3, 5);
grid.getChildren().addAll(correctBut,pointsLbl,textLbl);
Scene scene = new Scene(grid, 300, 200);
window.setScene(scene);
window.show();
}
}
As you are you using a lambda expression for your event handler all variable defined in the outer scope must be either final or member variables.
This leaves you with tow options:
1) Make the counter points a member variable:
private int points = 0;
2) Use a locale IntegerProperty instead of an int:
IntegerProperty points = new SimpleIntegerProperty(0);
...
correctBut.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
points.set(points.get() + 1);
String newValStr = points.toString();
pointsLbl.setText(newValStr);
}
});

too many different javafx stages

I have 2 sides of the MVC. on the model side, is where i have my main class for the entire battleship program. It instantiates the view/controller side of things, which consists of 3 different windows(classes that extend Application): a PreBoard, which gets both players names, and then one player board each (P1Board, P2Board). In all 3 of these separate classes, they extend Application, and all have a start(Stage primaryStage) method.
Since ive been reading about javaFX threading for the last 48 hours i am still barely understanding where the javaFX application thread starts. Does the javaFX Application thread start the very first time that Application.launch() is called, even if you have 3 seperate classes that extend Application and have their own start methods?
My original intentions were to have a window where players can enter their names, then a separate window with their own board, and i have failed MISERABLY because im getting more and more exceptions the longer the whole program runs.
So the question is, where the hell does the javaFX Application thread start?
Main class, on the model side
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package battleship.model;
import battleship.viewcon.*;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;
/**
*
* #author foolishklown
*/
public class MainApp {
Player player1;
Player player2;
BattleshipGame theGame;
PreBoard theGamePreBoard;
ViewCon viewConnector;
public void go() {
theGamePreBoard = new PreBoard();
theGamePreBoard.setMainAppConnection(this);
viewConnector = theGamePreBoard.getVcon();
}
public void startBsGame(String[] names) {
theGame = new BattleshipGame(names[0], names[1]);
viewConnector.setGame(theGame);
}
public BattleshipGame getGame() {
return theGame;
}
public void setConnection(ViewCon vc) {
this.viewConnector = vc;
}
public static void main(String[] args) {
MainApp app = new MainApp();
app.go();
}
}
PreBoard code, which instantiates 2 other classes that extend Application and have their own start methods......
package battleship.viewcon;
import battleship.model.*;
import javafx.geometry.Insets;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
/**
* PreBoard class, used for getting user input for players names
* #author Chris Wilson
* #author Bob McHenry
* #author Mario Rodriguez De la Raza en la casa!
* #author Jessy Bernoudi
*/
public class PreBoard extends Application {
private boolean turn; // field to determine which players name to put into which board
private String player;
private Button hideBtn;
private Button showBtn;
private TextField userText;
private ViewCon controller;
private P1Board p1B;
private P2Board p2B;
private BattleshipGame game;
private String[] playerNames;
private MainApp mainApp;
/**
* Application class override method, where javaFX stage starts
* #param primaryStage
*/
#Override
public void start(Stage primaryStage) {
playerNames = new String[2];
turn = false;
p1B = new P1Board();
p2B = new P2Board();
controller = new ViewCon();
controller.setPreB(this);
controller.setp1(p1B);
controller.setp2(p2B);
controller.setMain();
primaryStage.setTitle("Battleship setup"); //Main stage (window container)
//Gridpane for using rows/columns for child node placement
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER_LEFT);
grid.setHgap(10);
grid.setVgap(5);
grid.setPadding(new Insets(100, 25, 25, 25));
// label in window
Text sceneTitle = new Text("Setup");
sceneTitle.setId("setup-text");
grid.add(sceneTitle, 0, 0, 2, 1);
// label and textfield
Label userName = new Label("Enter Player1 UserName:");
userName.setId("user-name");
grid.add(userName, 0, 1);
TextField userTextField = new TextField();
userTextField.setId("text-field");
grid.add(userTextField, 0, 2);
// button for setup, with actionListener to save player name or default if its left blank
Button setupBtn = new Button("Setup Board");
HBox hbBtn = new HBox(10);
hbBtn.setAlignment(Pos.BOTTOM_LEFT);
hbBtn.getChildren().add(setupBtn);
grid.add(hbBtn, 0, 3);
setupBtn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
// determine which player name to use to pass into which player board
if(turn == false) {
String temp1 = userTextField.getText();
if(temp1.equals("")) {
player = "Player1";
} else {
player = temp1;
}
playerNames[0] = player;
controller.setPlayer1(player);
turn = true;
p1B.start(new Stage());
grid.getChildren().remove(userTextField);
userText = new TextField();
userText.setId("text-field");
grid.add(userText, 0, 2);
userName.setText("Enter Player2 username:");
} else {
String temp2 = userText.getText();
if(temp2.equals("")) {
player = "Player2";
} else {
player = temp2;
}
playerNames[1] = player;
controller.startGame(playerNames);
controller.setPlayer2(player);
p2B.start(new Stage());
p1B.primeShow();
}
}
});
hideBtn = new Button();
hideBtn.setId("hideBtn");
hideBtn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
primaryStage.hide();
}
});
showBtn = new Button();
showBtn.setId("showBtn");
showBtn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
primaryStage.show();
}
});
controller.setPreShowBtn(showBtn);
controller.setPreHideBtn(hideBtn);
// Add the entire scene into the main window(stage) after setting the scene dimensions
Scene scene = new Scene(grid, 580, 200);
primaryStage.setScene(scene);
// Attach css stylesheet
scene.getStylesheets().add(PreBoard.class.getResource("styles/PreBoardStyle.css").toExternalForm());
// Show this window(stage) upon instantiation
primaryStage.show();
}
/**
*
* #param v
*/
public void setLink(ViewCon v) {
this.controller = v;
}
/**
*
* #param b
*/
public void setBattleshipGame(BattleshipGame b) {
this.game = b;
}
/**
*
* #param main
*/
public void setMainAppConnection(MainApp main) {
this.mainApp = main;
}
/**
*
* #return
*/
public MainApp getMainConnection() {
return mainApp;
}
/**
*
* #return
*/
public ViewCon getVcon() {
return controller;
}
public void exitPre() {
Platform.exit();
}
public static void main(String[] args) {
Application.launch(args);
}
}

Button Click to Send User to Start of Program

I have an equations program that I'm working on, which randomly selects one of 50 equations, then takes the user through a series of scenes in order to solve it. Once the user solves the equation, they're asked if they want another equation. If they answer no, the program closes. If they answer yes, the program is supposed to randomly select another equation, then take them through the scenes to solve that one.
The program works just as I want it to the first time through. However, if the user selects "yes" for another equation, the program displays the END of the first scene, showing them the previous problem that they've already solved.
How can I send the user to the beginning of the scene, so that a new equation is randomly selected?
Here’s the relevant code for Scene 1:
package Equations;
import java.util.Random;
import javafx.application.*;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import javafx.scene.control.*;
import javafx.event.*;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
public class equationsapp extends Application
implements EventHandler<ActionEvent> {
public static void main(String[] args) {
launch(args);
}
#Override public void start(Stage primaryStage) {
stage = primaryStage;
Random eqrdmzr = new Random();
int randomNumber = eqrdmzr.nextInt(3) + 1;
if (randomNumber == 1) {
isolCounterCoeff = 2;
isolVrblb = new Label("+");
isolCounter1a = 7;
isolCounter2a = 17;
slvCoeff = 2;
slvEqVrblTerm = new Text("2n");
slvEqWhlNmbrInt = 10;
slvEqWhlNmbr = new Text("10");
}
if(randomNumber == 2) {
isolCounterCoeff = 2;
isolVrblb = new Label("+");
isolVrblb.setVisible(false);
isolCounter1a = -18;
isolCounter2a = 4;
slvCoeff = 2;
slvEqVrblTerm = new Text("2n");
slvEqWhlNmbrInt = 22;
slvEqWhlNmbr = new Text("22");
}
if(randomNumber == 3) {
isolCounterCoeff = 3;
isolVrblb = new Label("+");
isolVrblb.setVisible(false);
isolCounter1a = -5;
isolCounter2a = 19;
slvCoeff = 3;
slvEqVrblTerm = new Text("3n");
slvEqWhlNmbrInt = 24;
slvEqWhlNmbr = new Text("24");
}
//Build Scene 1 - Top BorderPane
Text isolText = new Text("Isolate the Variable Term");
isolText.setStyle("-fx-font-size: 16pt");
//Build Scene 1 - Center BorderPane
Label isolCoeff = new Label();
isolCoeff.setStyle("-fx-font-size: 24pt;");
isolCoeff.setText(Integer.toString(isolCounterCoeff));
Label isolVrbl = new Label("n");
isolVrbl.setStyle("-fx-font-size: 24pt;");
isolVrblb.setStyle("-fx-font-size: 24pt;");
isolVrblb.managedProperty().bind(isolVrblb.visibleProperty());
Label isolEqIntLeft = new Label();
isolEqIntLeft.setStyle("-fx-font-size: 24pt;");
isolEqIntLeft.setPadding(new Insets(0, 10, 0, 0));
isolEqIntLeft.setText(Integer.toString(isolCounter1a));
isolEqIntLeft.managedProperty().bind(isolEqIntLeft.visibleProperty());
Label isolEqualSign = new Label("=");
isolEqualSign.setStyle("-fx-font-size: 24pt;");
Label isolEqIntRight = new Label();
isolEqIntRight.setStyle("-fx-font-size: 24pt;");
isolEqIntRight.setPadding(new Insets(0, 0, 0, 10));
isolEqIntRight.setText(Integer.toString(isolCounter2a));
//Build Scene 1 - Bottom BorderPane
Label isolLbl1 = new Label();
isolLbl1.setStyle("-fx-font-size: 22pt;");
isolEqIntLeft.setText(Integer.toString(isolCounter1a));
isolLbl1.setText(Integer.toString(isolCounter1b));
//Create GridPanes and Fill Them
GridPane isolGridPane1 = new GridPane();
isolGridPane1.setAlignment(Pos.CENTER);
isolGridPane1.add(isolText, 0, 0);
GridPane isolGridPane2 = new GridPane();
isolGridPane2.setAlignment(Pos.CENTER);
isolGridPane2.add(isolCoeff, 0, 0);
isolGridPane2.add(isolVrbl, 1, 0);
isolGridPane2.add(isolVrblb, 2, 0);
isolGridPane2.add(isolEqIntLeft, 3, 0);
isolGridPane2.add(isolEqualSign, 4, 0);
isolGridPane2.add(isolEqIntRight, 5, 0);
GridPane isolGridPane3 = new GridPane();
isolGridPane3.setAlignment(Pos.CENTER);
isolGridPane3.setHgap(25.0);
isolGridPane3.setVgap(10.0);
isolGridPane3.setPadding(new Insets(0, 0, 20, 0));
isolGridPane3.add(isolbtn1, 0, 0);
isolGridPane3.add(isolLbl1, 1, 0);
isolGridPane3.add(isolBtn2, 2, 0);
isolGridPane3.add(isolBtn3, 4, 0);
isolGridPane3.add(isolLbl2, 5, 0);
isolGridPane3.add(isolBtn4, 6, 0);
isolGridPane3.add(isolContinueBtn, 3, 1);
//Add GridPane to BorderPane
BorderPane isolBorderPane = new BorderPane();
isolBorderPane.setTop(isolGridPane1);
isolBorderPane.setCenter(isolGridPane2);
isolBorderPane.setBottom(isolGridPane3);
//Add BorderPane to Scene
scene1 = new Scene(isolBorderPane, 500, 300);
//Add the scene to the stage, set the title and show the stage
primaryStage.setScene(scene1);
primaryStage.setTitle("Equations");
primaryStage.show();
Here’s the event handler that’s supposed to send them back to the start of Stage 1:
Button yesBtn = new Button("Yes");
yesBtn.setStyle("-fx-font-size: 12pt;");
yesBtn.setOnAction(new EventHandler<ActionEvent>() {
public void handle (ActionEvent event) {
if (event.getSource() == yesBtn) {
stage.setScene(scene1);
}
}
});
Just setting the scene on the stage doesn't reload the contents of the scene..
How to resolve this.. ?
As far as I see, you do not need to change scene. Create a simple method called loadMainDisplay(), which creates the BorderPane isolBorderPane by the adding the grid to it with all the required controls.
BorderPane loadMainDisplay() {
...
}
You can call it initially while loading the contents. Later, when the user selects YES for another equation, call this method, again.
yesBtn.setOnAction(event -> {
if (event.getSource() == yesBtn) {
scene.setRoot(loadMainDisplay());
}
});
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class ChangePaneExample extends Application{
/**
* #param args
*/
public static void main( String[] args ){
launch( args );
}
int screenNumber = 1;
private GridPane root;
private Scene rootScene;
private StackPane changingPane;
/**
* #see javafx.application.Application#start(javafx.stage.Stage)
* #param primaryStage
* #throws Exception
*/
#Override
public void start( Stage primaryStage ) throws Exception{
root = new GridPane();
rootScene = new Scene( root );
primaryStage.setScene( rootScene );
changingPane = new StackPane();
changeScreen();
Button changeBtn = new Button();
changeBtn.setText( "Change Screen" );
changeBtn.setOnAction( new EventHandler<ActionEvent>(){
#Override
public void handle( ActionEvent arg0 ){
changeScreen();
}
} );
root.addRow( 1, changeBtn );
root.addRow( 2, changingPane );
primaryStage.show();
}
/**
*/
private void changeScreen(){
if( screenNumber > 2 ) screenNumber = 1;
changingPane.getChildren().clear();
changingPane.getChildren().add( getDisplayPane( screenNumber + "" ) );
screenNumber++;
}
public static Pane getDisplayPane( String uniqueIdOfScreen ){
switch( uniqueIdOfScreen ){
case "1":
return getIsoletedGridPane2();
case "2":
return getIsoletedGridPane1();
default:
break;
}
return null;
}
public static Pane getIsoletedGridPane2(){
GridPane isolGridPane3 = new GridPane();
Label label = new Label();
label.setText( "this is isolated GridPane--------------- 2 ----------------------" );
isolGridPane3.getChildren().add( label );
return isolGridPane3;
}
public static Pane getIsoletedGridPane1(){
HBox isolGridPane3 = new HBox();
Label label = new Label();
label.setText( "this is isolated HBox --------------------------- 1 ----------------------------" );
isolGridPane3.getChildren().add( label );
return isolGridPane3;
}
}
This is one example of changing the Panes on the scene.
Changing the entire scene is not recommended way.

Categories