Javafx Validation User Input Username & Password [duplicate] - java

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

Related

Error: Unable to initialize main class FileChooser_1 Caused by: java.lang.NoClassDefFoundError: Stage [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 12 months ago.
Improve this question
Here I have written the following code. I can't run the program, and the error mentioned below keeps appearing. I tried many probable solutions but in vain.
import java.beans.EventHandler;
import java.io.File;
import javafx.application.Application;
import javafx.collections.*;
import javafx.event.ActionEvent;
import javafx.geometry.*;
import javafx.scene.Scene;
import javafx.scene.canvas.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.scene.text.*;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
public class FileChooser_1 extends Application {
// launch the application
public void start(Stage stage) {
try {
// title
stage.setTitle("Filechooser");
//File chooser create
FileChooser file_chooser = new FileChooser();
// define Label
Label lab = new Label("select file");
// Button new
Button b = new Button("open dialog");
// create Event Handler
EventHandler<ActionEvent> eve
= new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
// get file
File file = file_chooser.showOpenDialog(stage);
if (file != null) {
lab.setText(file.getAbsolutePath()
+ " selected");
}
}
};
b.setOnAction(event);
// create Button
Button b1 = new Button("save");
// Event Handler
EventHandler<ActionEvent> eve1
= new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
// get file
File file = file_chooser.showSaveDialog(stage);
if (file != null) {
lab.setText(file.getAbsolutePath()
+ " selected");
}
}
};
b1.setOnAction(eve1);
// VBox
VBox vbox = new VBox(30, label, button, button1);
// set Alignment
vbox.setAlignment(Pos.CENTER);
// create scene
Scene scene = new Scene(vbox, 800, 500);
// scene
stage.setScene(scene);
stage.show();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
// Main Method
public static void main(String args[]) {
launch(args);
}
}
I am getting the following error:
Error: Unable to initialize main class FileChooser_1
Caused by: java.lang.NoClassDefFoundError: Stage
It will be really nice if you can help me with this.
With some attention to detail, your code works. In particular, especially when just starting out,
Use Java naming conventions.
Use meaningful names; for example, instead of Button b, try Button openButton.
When using detailed comments, keep them up to date; note how meaningful names make some comments superfluous.
Use constants for consistency.
As #jewelsea notes, your program imports java.beans.EventHandler; it should import javafx.event.EventHandler.
As #jewelsea notes, "Only import classes you use."
Let the layout do the work.
I can't explain the error in your question; I see errors related to the incorrect import for EventHandler. If you're using an IDE, it may be reporting errors from a different compilation unit. When in doubt, do a clean build, move the code to a new file, or move to a different development environment, e.g. the command line. As a concrete example, this simple VersionCheck illustrates both a minimal ant script, invoked as ant run, and a simple shell script, invoked as .run.sh:
#!/bin/sh
JFX="--module-path /Users/Shared/javafx-sdk-17.0.1/lib --add-modules ALL-MODULE-PATH"
javac $JFX *.java && java $JFX VersionCheck
import javafx.event.EventHandler;
import java.io.File;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
public class FileChooser1 extends Application {
private static final int PADDING = 32;
#Override
public void start(Stage stage) {
// title
stage.setTitle("FileChooser");
//File chooser create
FileChooser fileChooser = new FileChooser();
// define Label
Label label = new Label("Select a file to open or save:");
// open Button
Button openButton = new Button("Open");
// open Event Handler
EventHandler<ActionEvent> openHandler = new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
// get file name
File file = fileChooser.showOpenDialog(stage);
if (file != null) {
label.setText(file.getName() + " selected");
}
}
};
openButton.setOnAction(openHandler);
// create save button
Button saveButton = new Button("Save");
// save Event Handler
EventHandler<ActionEvent> saveHandler = new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
// save file
File file = fileChooser.showSaveDialog(stage);
if (file != null) {
label.setText(file.getName() + " selected");
}
}
};
saveButton.setOnAction(saveHandler);
// VBox
VBox vBox = new VBox(PADDING, label, openButton, saveButton);
// set Alignment
vBox.setAlignment(Pos.CENTER);
vBox.setPadding(new Insets(PADDING));
// create scene
Scene scene = new Scene(vBox);
// scene
stage.setScene(scene);
stage.show();
}
public static void main(String args[]) {
launch(args);
}
}

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

Trying to assign an alarm with javafx

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

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

JavaFX thread issues

I really do my best to not ask for help here unless i am desperate to the point of school assignment failure, being a new coder. That being said, i have spent the last 3 days trying to figure out the issue with threading. I am trying to instantiate a javafx class thats in a separate package, and keep running into the dreaded "java.lang.IllegalStateException: This operation is permitted on the event thread only; currentThread = main" exception.
I have tried calling theGamePreBoard.start(new Stage()), which doesnt work, and i have also tried calling its start method during construction of that object with a new Stage() passed in during construction. Please help!!!
How can i instantiate this PreBoard() class and get it's start method to run without throwing this?
main class:
/*
* 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.stage.Stage;
/**
*
* #author foolishklown
*/
public class MainApp {
Player player1;
Player player2;
Board board1;
Board board2;
BattleshipGame theGame;
PreBoard theGamePreBoard;
public void go() {
theGame = new BattleshipGame();
theGamePreBoard = new PreBoard();
theGamePreBoard.start(new Stage());
System.out.println(theGamePreBoard);
theGamePreBoard.setBattleshipGame(theGame);
}
public static void main(String[] args) {
MainApp app = new MainApp();
app.go();
}
}
PreBoard class:
/*
* PreBoard object. This is the starter class for the different JavaFX stages (different windows - username screen,
* and each players window)
* After first username input, this class hides and calls on a new P1Board object
*/
package battleship.viewcon;
import battleship.model.*;
import javafx.geometry.Insets;
import javafx.application.Application;
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;
/**
*
*
* #author c-dub
*/
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 Stage theStage;
#Override
public void start(Stage primaryStage) {
turn = false;
p1B = new P1Board();
p2B = new P2Board();
controller = new ViewCon();
controller.setp1(p1B);
controller.setp2(p2B);
controller.setPreB(this);
this.game = controller.getBattleshipGame();
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 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;
}
controller.setPlayer1(player);
game.setPlayer1(player);
turn = true;
Stage stage = new Stage();
p1B.start(stage);
grid.getChildren().remove(userTextField);
userText = new TextField();
userText.setId("text-field2");
grid.add(userText, 0, 2);
hideBtn.fire();
} else {
String temp2 = userText.getText();
if(temp2.equals("")) {
player = "Player2";
} else {
player = temp2;
}
controller.setPlayer2(player);
game.setPlayer2(player);
Stage stage2 = new Stage();
p2B.start(stage2);
hideBtn.fire();
}
}
});
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();
}
public void setLink(ViewCon v) {
this.controller = v;
}
public static void main(String[] args) {
Application.launch(args);
}
public void setBattleshipGame(BattleshipGame b) {
this.game = b;
}
}
I don't think this has anything at all to do with threading: I don't see any reason why you would ever create another thread in this application. The part you seem to be missing is the actual life-cycle of a JavaFX application. (There's a little you could need to know about how JavaFX manages threading, but it is a bit incidental here.)
The Application class represents an entire application. Your application should typically have just one Application subclass, and one instance of that class. The instance is created for you by JavaFX when you call the static Application.launch() method (or when you execute your Application subclass from the command line, which effectively calls launch for you).
When launch is invoked, the JavaFX toolkit (including the FX Application Thread) is started. An instance of theApplication subclass is created for you, and then start(...) is invoked on that instance on the FX Application Thread.
So what that means is that the start(...) method is the entry point (startup) for your JavaFX application. Since the most common thing to do here is to display something in a window, a window (Stage) is passed into this method for your convenience: however you can ignore it and just create your own if you like.
A typical start(...) method should be quite short, and will usually just create some UI (maybe defined in another class or in an FXML file), put that UI in a scene, and display the scene in a stage. In a more complex application, you will create an instance of your model class here, create some views and controllers, give the controllers references to the model, and assemble the views.
For a simple structural example, see my answer to Java: How do I start a standalone application from the current one when both are in the same package? (which is a similar question, I think).

Categories