I need to use exception handling to capture incorrect numeric values when adding numbers. I have the code I created but I am not sure how to do this. can someone show me how it is properly done so i know for the future.
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.event.*;
import javafx.stage.Stage;
public class test33 extends Application {
private double num1 = 0, num2 = 0, result = 0;
#Override
// Override the start method in the Application class
public void start(Stage primaryStage) {
FlowPane pane = new FlowPane();
pane.setHgap(2);
TextField tfNumber1 = new TextField();
TextField tfNumber2 = new TextField();
TextField tfResult = new TextField();
tfNumber1.setPrefColumnCount(3);
tfNumber2.setPrefColumnCount(3);
tfResult.setPrefColumnCount(3);
pane.getChildren().addAll(new Label("Number 1: "), tfNumber1,
new Label("Number 2: "), tfNumber2, new Label("Result: "), tfResult);
// Create four buttons
HBox hBox = new HBox(5);
Button btAdd = new Button("Add");
hBox.setAlignment(Pos.CENTER);
hBox.getChildren().addAll(btAdd);
BorderPane borderPane = new BorderPane();
borderPane.setCenter(pane);
borderPane.setBottom(hBox);
BorderPane.setAlignment(hBox, Pos.TOP_CENTER);
// Create a scene and place it in the stage
Scene scene = new Scene(borderPane, 375, 150);
primaryStage.setTitle("Test33"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
btAdd.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
num1 = Double.parseDouble(tfNumber1.getText());
num2 = Double.parseDouble(tfNumber2.getText());
result = num1 + num2;
tfResult.setText(String.format("%.1f", result));
}
});
}
/**
* 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);
}
}
One aspect of the exception handling that should be present is in the .parseDouble(). I would suggest adding at a minimum NumberFormatException handling
public void handle(ActionEvent e) {
try {
num1 = Double.parseDouble(tfNumber1.getText());
num2 = Double.parseDouble(tfNumber2.getText());
result = num1 + num2;
tfResult.setText(String.format("%.1f", result));
}
catch (NumberFormatException nfe) {
tfResult.setText("Invalid input!");
}
}
One can get more fine-grained by catching the specific input that caused the error, etc. However, from a demonstration perspective of catching a bad number, this code is illustrative.
Related
How to set minimum diameter to jfxtras circularpane. For example take a look at following code,
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import jfxtras.scene.layout.*;
/**
* AssistiveBall
*/
public class AssistiveBall extends Application
{
#Override
public void start(Stage pStage) throws Exception
{
StackPane root = new StackPane();
CircularPane pane = new CircularPane();
Scene scene = new Scene(root, 800, 600);
Button btn = new Button("Center");
Button[] buttons = new Button[13];
for (int i = 0; i < buttons.length; i++)
{
buttons[i] = new Button("" + i);
}
pane.getChildren().addAll(buttons);
btn.setOnAction(e -> {
if(pane.isVisible())
{
pane.setVisible(false);
}
else
{
pane.setVisible(true);
}
});
root.getChildren().add(pane);
root.getChildren().add(btn);
pStage.setScene(scene);
pStage.setTitle("Assistive Ball");
pStage.show();
}
public static void main( String[] args )
{
AssistiveBall.launch(args);
}
}
Here here code if fine, but if i use just 3 buttons it starts appear one on another, So how to set minimum diameter or there is any another way to do this ?
Thanks.
Version 11-r3-SNAPSHOT has changed certain methods like computeChainDiameter and determineBeadDiameter to protected, so you can override them and tune the output.
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();
Mouse events and scroll events behave in different ways
Mouse Events:
The event is captured by mainStage
The event is captured by mainStage
The event is not captured
Scroll Events:
The event is captured by mainStage
The event is captured by secondStage
The event is not captured
Is there any way that transparent secondStage does not capture scroll events?
My code:
Pane mainPane = new Pane(new Label("Main Stage"));
mainPane.setPrefSize(300, 300);
mainStage.setScene(new Scene(mainPane));
Stage secondStage = new Stage();
Pane secondPane = new Pane(new Label("Second Stage"));
secondPane.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, CornerRadii.EMPTY, Insets.EMPTY)));
secondPane.setBorder(new Border(
new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID, CornerRadii.EMPTY, new BorderWidths(2))));
secondPane.setPrefSize(300, 300);
secondStage.setScene(new Scene(secondPane, Color.TRANSPARENT));
secondStage.initStyle(StageStyle.TRANSPARENT);
mainStage.getScene().setOnScroll(event -> System.out.println("Scroll in main stage"));
secondStage.getScene().setOnScroll(event -> System.out.println("Scroll in second stage"));
mainStage.getScene().setOnMouseClicked(event -> System.out.println("Click in main stage"));
secondStage.getScene().setOnMouseClicked(event -> System.out.println("Click in second stage"));
mainStage.show();
secondStage.show();
Java version: 1.8.0_201 (64 bits), Windows 10
edit:
The example is a simplification with only two windows. Fire the event programmatically implies discovering which stage is immediately lower and that is another problem in itself.
It might be a great coincidence, that we also came with the same solution of transparent window because of not having the feature of managing z-index of stages. And We encountered the exact same issue as yours. ie, scroll events not propagating to underlying Stages. We used the below approach, not sure whether this can help you:
Firstly, We constructed a Singleton class that keeps a reference of Node that is currently hovered on.
Then, when we create any normal stage, we include the below handlers to the scene of that new stage. The key thing here is that, the mouse events are still able to pass through the transparent stage to the underlying window, keep track of node which sits under the mouse.
scene.addEventFilter(MouseEvent.MOUSE_EXITED_TARGET, e -> {
hoverNode.set(null);
});
scene.addEventFilter(MouseEvent.MOUSE_MOVED, e -> {
hoverNode.set(e.getTarget());
});
In the scene of the transparent window, we included the below handlers to delegate the scroll events to the underlying node.
scene.addEventFilter(ScrollEvent.SCROLL, e -> {
if (hoverNode.get() != null) {
Event.fireEvent(hoverNode.get(), e);
}
});
scene.addEventHandler(ScrollEvent.SCROLL, e -> {
if (hoverNode.get() != null) {
Event.fireEvent(hoverNode.get(), e);
}
});
I am pretty sure this is not the most desired way. But this addressed our issue. :)
Below is the quick demo code of what I mean.
import javafx.application.Application;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.event.Event;
import javafx.event.EventTarget;
import javafx.geometry.Insets;
import javafx.geometry.Rectangle2D;
import javafx.scene.Cursor;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import java.util.stream.IntStream;
public class ScrollThroughTransparentStage_Demo extends Application {
#Override
public void start(Stage stage) throws Exception {
stage.setTitle("Main Window");
VBox root = new VBox(buildScrollPane());
root.setStyle("-fx-background-color:#888888;");
root.setSpacing(10);
root.setPadding(new Insets(10));
Button normalStageBtn = new Button("Normal Stage");
normalStageBtn.setOnAction(e -> {
Stage normalStage = new Stage();
normalStage.initOwner(stage);
Scene normalScene = new Scene(buildScrollPane(), 300, 300);
addHandlers(normalScene);
normalStage.setScene(normalScene);
normalStage.show();
});
CheckBox allowScrollThrough = new CheckBox("Allow scroll through transparency");
allowScrollThrough.setSelected(true);
HBox buttons = new HBox(normalStageBtn);
buttons.setSpacing(20);
root.getChildren().addAll(allowScrollThrough,buttons);
Scene scene = new Scene(root, 600, 600);
addHandlers(scene);
stage.setScene(scene);
stage.show();
/* Transparent Stage */
Stage transparentStage = new Stage();
transparentStage.initOwner(stage);
transparentStage.initStyle(StageStyle.TRANSPARENT);
Pane mainRoot = new Pane();
Pane transparentRoot = new Pane(mainRoot);
transparentRoot.setStyle("-fx-background-color:transparent;");
Scene transparentScene = new Scene(transparentRoot, Color.TRANSPARENT);
transparentStage.setScene(transparentScene);
transparentScene.addEventFilter(ScrollEvent.SCROLL, e -> {
if (allowScrollThrough.isSelected() && HoverNodeSingleton.getInstance().getHoverNode() != null) {
Event.fireEvent(HoverNodeSingleton.getInstance().getHoverNode(), e);
}
});
transparentScene.addEventHandler(ScrollEvent.SCROLL, e -> {
if (allowScrollThrough.isSelected() && HoverNodeSingleton.getInstance().getHoverNode() != null) {
Event.fireEvent(HoverNodeSingleton.getInstance().getHoverNode(), e);
}
});
determineStageSize(transparentStage, mainRoot);
transparentStage.show();
Button transparentStageBtn = new Button("Transparent Stage");
transparentStageBtn.setOnAction(e -> {
MiniStage miniStage = new MiniStage(mainRoot);
ScrollPane scrollPane = buildScrollPane();
scrollPane.setPrefSize(300, 300);
miniStage.setContent(scrollPane);
miniStage.show();
});
buttons.getChildren().add(transparentStageBtn);
}
private static void determineStageSize(Stage stage, Node root) {
DoubleProperty width = new SimpleDoubleProperty();
DoubleProperty height = new SimpleDoubleProperty();
DoubleProperty shift = new SimpleDoubleProperty();
Screen.getScreens().forEach(screen -> {
Rectangle2D bounds = screen.getVisualBounds();
width.set(width.get() + bounds.getWidth());
if (bounds.getHeight() > height.get()) {
height.set(bounds.getHeight());
}
if (bounds.getMinX() < shift.get()) {
shift.set(bounds.getMinX());
}
});
stage.setX(shift.get());
stage.setY(0);
stage.setWidth(width.get());
stage.setHeight(height.get());
root.setTranslateX(-1 * shift.get());
}
private void addHandlers(Scene scene) {
scene.addEventFilter(MouseEvent.MOUSE_EXITED_TARGET, e -> {
HoverNodeSingleton.getInstance().setHoverNode(null);
});
scene.addEventFilter(MouseEvent.MOUSE_MOVED, e -> {
HoverNodeSingleton.getInstance().setHoverNode(e.getTarget());
});
}
private ScrollPane buildScrollPane() {
VBox vb = new VBox();
vb.setSpacing(10);
vb.setPadding(new Insets(15));
IntStream.rangeClosed(1, 100).forEach(i -> vb.getChildren().add(new Label(i + "")));
ScrollPane scrollPane = new ScrollPane(vb);
return scrollPane;
}
class MiniStage extends Group {
private Pane parent;
double sceneX, sceneY, layoutX, layoutY;
protected BorderPane windowPane;
private BorderPane windowTitleBar;
private Label labelTitle;
private Button buttonClose;
public MiniStage(Pane parent) {
this.parent = parent;
buildRootNode();
getChildren().add(windowPane);
addEventHandler(MouseEvent.MOUSE_PRESSED, e -> toFront());
}
#Override
public void toFront() {
parent.getChildren().remove(this);
parent.getChildren().add(this);
}
public void setContent(Node content) {
// Computing the bounds of the content before rendering
Group grp = new Group(content);
new Scene(grp);
grp.applyCss();
grp.requestLayout();
double width = grp.getLayoutBounds().getWidth();
double height = grp.getLayoutBounds().getHeight() + 30; // 30 title bar height
grp.getChildren().clear();
windowPane.setCenter(content);
// Centering the stage
Rectangle2D screenBounds = Screen.getPrimary().getBounds();
setX(screenBounds.getWidth() / 2 - width / 2);
setY(screenBounds.getHeight() / 2 - height / 2);
}
public Node getContent() {
return windowPane.getCenter();
}
public void setX(double x) {
setLayoutX(x);
}
public void setY(double y) {
setLayoutY(y);
}
public void show() {
if (!parent.getChildren().contains(this)) {
parent.getChildren().add(this);
}
}
public void hide() {
parent.getChildren().remove(this);
}
private void buildRootNode() {
windowPane = new BorderPane();
windowPane.setStyle("-fx-border-width:2px;-fx-border-color:#444444;");
labelTitle = new Label("Mini Stage");
labelTitle.setStyle("-fx-font-weight:bold;");
labelTitle.setMaxHeight(Double.MAX_VALUE);
buttonClose = new Button("X");
buttonClose.setFocusTraversable(false);
buttonClose.setStyle("-fx-background-color:red;-fx-background-radius:0;-fx-background-insets:0;");
buttonClose.setOnMouseClicked(evt -> hide());
windowTitleBar = new BorderPane();
windowTitleBar.setStyle("-fx-border-width: 0 0 2px 0;-fx-border-color:#444444;-fx-background-color:#BBBBBB");
windowTitleBar.setLeft(labelTitle);
windowTitleBar.setRight(buttonClose);
windowTitleBar.setPadding(new Insets(0, 0, 0, 10));
windowTitleBar.getStyleClass().add("nonfocus-title-bar");
windowPane.setTop(windowTitleBar);
assignTitleBarEvents();
}
private void assignTitleBarEvents() {
windowTitleBar.setOnMousePressed(this::recordWindowLocation);
windowTitleBar.setOnMouseDragged(this::moveWindow);
windowTitleBar.setOnMouseReleased(this::resetMousePointer);
}
private final void recordWindowLocation(final MouseEvent event) {
sceneX = event.getSceneX();
sceneY = event.getSceneY();
layoutX = getLayoutX();
layoutY = getLayoutY();
getScene().setCursor(Cursor.MOVE);
}
private final void resetMousePointer(final MouseEvent event) {
// Updating the new layout positions
setLayoutX(layoutX + getTranslateX());
setLayoutY(layoutY + getTranslateY());
// Resetting the translate positions
setTranslateX(0);
setTranslateY(0);
getScene().setCursor(Cursor.DEFAULT);
}
private final void moveWindow(final MouseEvent event) {
double offsetX = event.getSceneX() - sceneX;
double offsetY = event.getSceneY() - sceneY;
setTranslateX(offsetX);
setTranslateY(offsetY);
event.consume();
}
}
}
/**
* Singleton class.
*/
class HoverNodeSingleton {
private static HoverNodeSingleton INSTANCE = new HoverNodeSingleton();
private EventTarget hoverNode;
private HoverNodeSingleton() {
}
public static HoverNodeSingleton getInstance() {
return INSTANCE;
}
public EventTarget getHoverNode() {
return hoverNode;
}
public void setHoverNode(EventTarget hoverNode) {
this.hoverNode = hoverNode;
}
}
I don't know that's right or not, but you can bind properties:
secondStage.getScene().onScrollProperty().bind(mainStage.getScene().onScrollProperty());
You can create a custom event dispatcher that will ignore events you don't want:
public class CustomEventDispatcher extends BasicEventDispatcher {
#Override
public Event dispatchEvent(Event event, EventDispatchChain tail) {
if(event instanceof ScrollEvent) {
return null;
} else {
return super.dispatchEvent(event, tail);
}
}
}
Then set that on your stage:
secondStage.setEventDispatcher(new CustomEventDispatcher());
I don't know how this works in the context of stages but for simple shapes it makes a difference whether you set the fill color to Color.TRANSPARENT or just null. Using any Color catches events, whereas null does not.
You can do so by ignoring the event on the second stage using event dispatcher using this answer by #Slaw you can understand everything about EventDispatcher
https://stackoverflow.com/a/51015783/5303683
Then you can fire your own event using this answer by DVarga
https://stackoverflow.com/a/40042513/5303683
Sorry I don't have time to try and make a full example of it
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();
}
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.