here is my first class client
package hwch33;
import java.net.*;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.io.*;
public class Client extends Application {
// IO streams
DataOutputStream toServer = null;
DataInputStream fromServer = null;
#Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Panel p to hold the label and text field
BorderPane paneForTextField = new BorderPane();
paneForTextField.setPadding(new Insets(5, 5, 5, 5));
paneForTextField.setStyle("-fx-border-color: green");
paneForTextField.setLeft(new Label("Enter a radius: "));
TextField tf = new TextField();
tf.setAlignment(Pos.BOTTOM_RIGHT);
paneForTextField.setCenter(tf);
BorderPane mainPane = new BorderPane();
// Text area to display contents
TextArea ta = new TextArea();
mainPane.setCenter(new ScrollPane(ta));
mainPane.setTop(paneForTextField);
// Create a scene and place it in the stage
Scene scene = new Scene(mainPane, 450, 200);
primaryStage.setTitle("Client"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
tf.setOnAction(e -> {
try {
// Get the radius from the text field
double radius = Double.parseDouble(tf.getText().trim());
// Send the radius to the server
toServer.writeDouble(radius);
toServer.flush();
// Get area from the server
double area = fromServer.readDouble();
// Display to the text area
ta.appendText("Radius is " + radius + "\n");
ta.appendText("Area received from the server is "
+ area + '\n');
}
catch (IOException ex) {
System.err.println(ex);
}
});
try {
// Create a socket to connect to the server
Socket socket = new Socket("localhost", 8000);
//Socket socket = new Socket("130.254.204.36", 8000);
//Socket socket = new Socket("drake.Armstrong.edu", 8000);
// Create an input stream to receive data from the server
fromServer = new DataInputStream(socket.getInputStream());
// Create an output stream to send data to the server
toServer = new DataOutputStream(socket.getOutputStream());
}
catch (IOException ex) {
ta.appendText(ex.toString() + '\n');
}
}
}
here is my second class server
package hwch33;
import java.io.*;
import java.net.*;
import java.util.Date;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
public class Server extends Application {
/**
*
* #param primaryStage
*/
#Override
public void start(Stage primaryStage) {
// Text area for displaying contents
TextArea ta = new TextArea();
// Create a scene and place it in the stage
Scene scene = new Scene(new ScrollPane(ta), 450, 200);
primaryStage.setTitle("Server"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
new Thread(() -> {
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
Platform.runLater(() ->
ta.appendText("Server started at " + new Date() + '\n'));
Socket socket = serverSocket.accept();
DataInputStream inputFromClient = new DataInputStream(
socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(
socket.getOutputStream());
while (true) {
double radius = inputFromClient.readDouble();
double area = radius * radius * Math.PI;
outputToClient.writeDouble(area);
Platform.runLater(() -> {
ta.appendText("Radius received from client: "
+ radius + '\n');
ta.appendText("Area is: " + area + '\n');
});
}
}
catch(IOException ex) {
ex.printStackTrace();
}
}).start();
}
}
Here is where i need to add the code to make it all work
/*
* 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 hwch33;
/**
*
* #author
*/
public class HWCH33 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
}
}
Not sure how to construct a main from here.
Ive been trying to form one but cannot get it right. I either get static error or it just doesnt work at all.
Any help is appreciated. Did not include any of my previous attempts because they are useless and I got rid of them all.
If the error is that a non-static variable is not compatible with a static method or something along those lines, just omit the word "static" from public static void main(String[] args){}.
Related
My assignment is to get this simple client/server program to run, it sends the radius of a circle to a server and the area is returned. I literally just copied and pasted the code and tried to run it but I get this error. I have included the code for both client and server side below. Thanks.
Error: Could not find or load main class Client_Server.Client_Side
Caused by: java.lang.NoClassDefFoundError: javafx/application/Application
package Client_Server;
import java.io.*;
import java.net.*;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class Client_Side extends Application
{
// IO streams
DataOutputStream toServer = null;
DataInputStream fromServer = null;
#Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Panel p to hold the label and text field
BorderPane paneForTextField = new BorderPane();
paneForTextField.setPadding(new Insets(5, 5, 5, 5));
paneForTextField.setStyle("-fx-border-color: green");
paneForTextField.setLeft(new Label("Enter a radius: "));
TextField tf = new TextField();
tf.setAlignment(Pos.BOTTOM_RIGHT);
paneForTextField.setCenter(tf);
BorderPane mainPane = new BorderPane();
// Text area to display contents
TextArea ta = new TextArea();
mainPane.setCenter(new ScrollPane(ta));
mainPane.setTop(paneForTextField);
// Create a scene and place it in the stage
Scene scene = new Scene(mainPane, 450, 200);
primaryStage.setTitle("Client"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
tf.setOnAction(e -> {
try {
// Get the radius from the text field
double radius = Double.parseDouble(tf.getText().trim());
// Send the radius to the server
toServer.writeDouble(radius);
toServer.flush();
// Get area from the server
double area = fromServer.readDouble();
// Display to the text area
ta.appendText("Radius is " + radius + "\n");
ta.appendText("Area received from the server is "
+ area + '\n');
}
catch (IOException ex) {
System.err.println(ex);
}
});
try {
// Create a socket to connect to the server
Socket socket = new Socket("localhost", 8000);
// Socket socket = new Socket("130.254.204.36", 8000);
// Socket socket = new Socket("drake.Armstrong.edu", 8000);
// Create an input stream to receive data from the server
fromServer = new DataInputStream(socket.getInputStream());
// Create an output stream to send data to the server
toServer = new DataOutputStream(socket.getOutputStream());
}
catch (IOException ex) {
ta.appendText(ex.toString() + '\n');
}
}
public static void main(String[] args) {
launch(args);
}
}
package Client_Server;
import java.io.*;
import java.net.*;
import java.util.Date;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
public class Server_Side extends Application {
#Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Text area for displaying contents
TextArea ta = new TextArea();
// Create a scene and place it in the stage
Scene scene = new Scene(new ScrollPane(ta), 450, 200);
primaryStage.setTitle("Server"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
new Thread( () -> {
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
Platform.runLater(() ->
ta.appendText("Server started at " + new Date() + '\n'));
// Listen for a connection request
Socket socket = serverSocket.accept();
// Create data input and output streams
DataInputStream inputFromClient = new DataInputStream(
socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(
socket.getOutputStream());
while (true) {
// Receive radius from the client
double radius = inputFromClient.readDouble();
// Compute area
double area = radius * radius * Math.PI;
// Send area back to the client
outputToClient.writeDouble(area);
Platform.runLater(() -> {
ta.appendText("Radius received from client: "
+ radius + '\n');
ta.appendText("Area is: " + area + '\n');
});
}
}
catch(IOException ex) {
ex.printStackTrace();
}
}).start();
}
public static void main(String[] args) {
launch(args);
}
}
If you are a Student you can get the Ultimate version of Intellij which simplifies settings for new projects..
Ijust tested your code and it works..
I created a new JFX project.. I added the right SDK.. for JFX is Java 11 the minimum.. so I downloaded it and created the project.. then I created 2 normal classes in the pre-created package one for Client_Side and one for Server_Side .. then run first the server class and it works
As you seem to manage compilation, your Runtime Environment misses an JavaFX-Distribution. You could either install an Runtime Environment with JavaFX, for example Liberica, Correto or Oracles 1.8-Runtime.
Otherwise, you may also run your class and add OpenJFX-JARs to your classpath. For more information about how to set the classpath, have a look at the Oracle Docs.
Another option is to install OpenJFX on your operating system. You can download the OpenJFX JARs from Maven repositories, as well. However, you must get the JARs for the correct platform (mac, linux or win classifier).
I'm learning some basic java networking stuff and I'm trying to make what I learned come to life, so when I run my server and client classes on the same computer it runs without errors, but when I take the client project to another computer and run the project after running the server it freezes and prints a connection timed out statement.
here is my server code
package sample;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
TextArea ta = new TextArea();
primaryStage.setTitle("server");
primaryStage.setScene(new Scene(new ScrollPane(ta), 450, 200));
primaryStage.show();
new Thread(()->{
try {
ServerSocket ss = new ServerSocket(8000);
Platform.runLater(() ->
ta.appendText("Server started at " + new Date() + '\n'));
Socket s = ss.accept();
DataInputStream inputFromClient = new DataInputStream(s.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(s.getOutputStream());
while (true) {
double radius = inputFromClient.readDouble();
double area = radius * radius * Math.PI;
outputToClient.writeDouble(area);
Platform.runLater(() -> {
ta.appendText("Radius received from client: "
+ radius + '\n');
ta.appendText("Area is: " + area + '\n');
});
}
} catch (Exception e){
e.printStackTrace();
}
}).start();
}
public static void main(String[] args) {
launch(args);
}
}
and this is my client
package sample;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Main extends Application {
DataOutputStream toServer = null;
DataInputStream fromServer = null;
public void start(Stage primaryStage) {
BorderPane pane = new BorderPane();
pane.setPadding(new Insets(5, 5, 5, 5));
pane.setStyle("-fx-border-color: green");
pane.setLeft(new Label("Enter a radius: "));
TextField tf = new TextField();
tf.setAlignment(Pos.BOTTOM_RIGHT);
pane.setCenter(tf);
BorderPane mainPane = new BorderPane();
TextArea ta = new TextArea();
mainPane.setCenter(new ScrollPane(ta));
mainPane.setTop(pane);
Scene scene = new Scene(mainPane, 450, 200);
primaryStage.setTitle("Client"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
tf.setOnAction(e -> {
try {
Socket socket = new Socket("server IP address", 8000);
fromServer = new DataInputStream(socket.getInputStream());
toServer = new DataOutputStream(socket.getOutputStream());
} catch (IOException ex) {
ta.appendText(ex.toString() + '\n');
}
try {
double radius = Double.parseDouble(tf.getText().trim());
toServer.writeDouble(radius);
toServer.flush();
double area = fromServer.readDouble();
ta.appendText("Radius is " + radius + "\n");
ta.appendText("Area received from the server is "
+ area + '\n');
} catch (IOException ex) {
System.err.println(ex);
}
});
}
}
problem solved
I just had to change the network settings on my server so that it will be discoverable on my network
Within the server class you create a server socket on the port 8000, which is fine for both internal and external connections. However your client class attempts to create a socket with no given IP Address
Socket socket = new Socket("server IP address", 8000);
By passing the string "Server ip address", you're essentially telling java to look for a local server, as you did not pass in a proper IP Address.
So when both classes are running on the same system only the port matters, but you need to identify the IP Address of the server for the client to know where to look for its connection if they're not on the same system.
I have to create Java program with GUI that simply is a text chat between a server and a client. I have referred to my professor's Powerpoint presentation and copied example code of a server and client program that where the client types a circle radius, and the server automatically calculates and returns the client the circle area (The example code did not have a textfield for input). I have changed up the example code into code where the server and client can chat with each other in text. My Client class works and I did not have to change anything in the Client class except that the text inputted stays as a string and not a double.
I tested my server. Why does my server freeze when I hit enter after inputting simple text?
Server:
import java.io.*;
import java.net.*;
import javafx.geometry.Insets;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.geometry.Insets;
import javafx.scene.layout.BorderPane;
import javafx.scene.control.Label;
import javafx.geometry.Pos;
public class Server extends Application {
#Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Text area for displaying contents
BorderPane paneForTextField = new BorderPane();
paneForTextField.setPadding(new Insets(5, 5, 5, 5));
paneForTextField.setStyle("-fx-border-color: green");
paneForTextField.setLeft(new Label("Type here: "));
TextField tf = new TextField();
tf.setAlignment(Pos.BOTTOM_RIGHT);
paneForTextField.setCenter(tf);
BorderPane mainPane = new BorderPane();
TextArea ta = new TextArea();
mainPane.setCenter(new ScrollPane(ta));
mainPane.setTop(paneForTextField);
// Create a scene and place it in the stage
Scene scene = new Scene(mainPane, 450, 200);
primaryStage.setTitle("Server"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
try {
Socket socket = new Socket("localhost", 8000);
// Socket socket = new Socket("130.254.204.36", 8000);
// Socket socket = new Socket("drake.Armstrong.edu", 8000);
// Create an input stream to receive data from the server
DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
// Create an output stream to send data to the server
DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
// Get the radius from the text field
String serverText = tf.getText();
// Send the radius to the server
outputToClient.writeBytes(serverText);
outputToClient.flush();
// Get area from the server
String clientText = inputFromClient.readLine();
// Display to the text area
ta.appendText("Client: " + clientText + "\n");
ta.appendText("Server: " + serverText + '\n');
}
catch (IOException ex) {
System.err.println(ex.toString() + '\n');
}
tf.setOnAction(e -> {
new Thread( () -> {
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
Platform.runLater(() ->
ta.appendText("Server is working" + '\n'));
// Listen for a connection request
Socket socket = serverSocket.accept();
// Create data input and output streams
DataInputStream inputFromClient = new DataInputStream(
socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(
socket.getOutputStream());
while (true) {
// Receive radius from the client
String clientText = inputFromClient.readLine();
String serverText = tf.getText();
// Compute area
// Send area back to the client
outputToClient.writeBytes("Server: " + serverText);
Platform.runLater(() -> {
ta.appendText("Client: " + clientText + '\n');
ta.appendText("Server: " + serverText + '\n');
});
}
}
catch(IOException ex) {
ex.printStackTrace();
}
}).start();
});
}
/**
* 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);
}
}
Client
import java.io.*;
import java.net.*;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class Client extends Application {
// IO streams
DataOutputStream toServer = null;
DataInputStream fromServer = null;
#Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Panel p to hold the label and text field
BorderPane paneForTextField = new BorderPane();
paneForTextField.setPadding(new Insets(5, 5, 5, 5));
paneForTextField.setStyle("-fx-border-color: green");
paneForTextField.setLeft(new Label("Type here: "));
TextField tf = new TextField();
tf.setAlignment(Pos.BOTTOM_RIGHT);
paneForTextField.setCenter(tf);
BorderPane mainPane = new BorderPane();
// Text area to display contents
TextArea ta = new TextArea();
mainPane.setCenter(new ScrollPane(ta));
mainPane.setTop(paneForTextField);
// Create a scene and place it in the stage
Scene scene = new Scene(mainPane, 450, 200);
primaryStage.setTitle("Client"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
tf.setOnAction(e -> {
try {
// Get the text from the text field
String clientText = tf.getText();
// Send the text to the server
toServer.writeBytes(clientText);
toServer.flush();
// Get text from the server
String serverText = fromServer.readLine();
// Display to the text area
ta.appendText("Client: " + clientText + "\n");
ta.appendText("Server: " + serverText + '\n');
}
catch (IOException ex) {
System.err.println(ex);
}
});
try {
// Create a socket to connect to the server
Socket socket = new Socket("localhost", 8000);
// Create an input stream to receive data from the server
fromServer = new DataInputStream(socket.getInputStream());
// Create an output stream to send data to the server
toServer = new DataOutputStream(socket.getOutputStream());
}
catch (IOException ex) {
ta.appendText(ex.toString() + '\n');
}
}
/**
* 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);
}
}
So the code you see below is from a powerpoint my professor gave us. It should be correct, because our textbook made these powerpoints. This code below is an example code of a client sending a circle radius to a server. The server calculates the circle's area. The issue is, I can't test the code, because I need both the server and client open simultaneously. How do I test the code if both can't be running? I am using JGRASP by the way.
Server Class
import java.io.*;
import java.net.*;
import java.util.Date;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
public class Server extends Application {
#Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Text area for displaying contents
TextArea ta = new TextArea();
// Create a scene and place it in the stage
Scene scene = new Scene(new ScrollPane(ta), 450, 200);
primaryStage.setTitle("Server"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
new Thread( () -> {
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
Platform.runLater(() ->
ta.appendText("Server started at " + new Date() + '\n'));
// Listen for a connection request
Socket socket = serverSocket.accept();
// Create data input and output streams
DataInputStream inputFromClient = new DataInputStream(
socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(
socket.getOutputStream());
while (true) {
// Receive radius from the client
double radius = inputFromClient.readDouble();
// Compute area
double area = radius * radius * Math.PI;
// Send area back to the client
outputToClient.writeDouble(area);
Platform.runLater(() -> {
ta.appendText("Radius received from client: "
+ radius + '\n');
ta.appendText("Area is: " + area + '\n');
});
}
}
catch(IOException ex) {
ex.printStackTrace();
}
}).start();
}
/**
* 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);
}
}
Client Class
import java.io.*;
import java.net.*;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class Client extends Application {
// IO streams
DataOutputStream toServer = null;
DataInputStream fromServer = null;
#Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Panel p to hold the label and text field
BorderPane paneForTextField = new BorderPane();
paneForTextField.setPadding(new Insets(5, 5, 5, 5));
paneForTextField.setStyle("-fx-border-color: green");
paneForTextField.setLeft(new Label("Enter a radius: "));
TextField tf = new TextField();
tf.setAlignment(Pos.BOTTOM_RIGHT);
paneForTextField.setCenter(tf);
BorderPane mainPane = new BorderPane();
// Text area to display contents
TextArea ta = new TextArea();
mainPane.setCenter(new ScrollPane(ta));
mainPane.setTop(paneForTextField);
// Create a scene and place it in the stage
Scene scene = new Scene(mainPane, 450, 200);
primaryStage.setTitle("Client"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
tf.setOnAction(e -> {
try {
// Get the radius from the text field
double radius = Double.parseDouble(tf.getText().trim());
// Send the radius to the server
toServer.writeDouble(radius);
toServer.flush();
// Get area from the server
double area = fromServer.readDouble();
// Display to the text area
ta.appendText("Radius is " + radius + "\n");
ta.appendText("Area received from the server is "
+ area + '\n');
}
catch (IOException ex) {
System.err.println(ex);
}
});
try {
// Create a socket to connect to the server
Socket socket = new Socket("localhost", 8000);
// Socket socket = new Socket("130.254.204.36", 8000);
// Socket socket = new Socket("drake.Armstrong.edu", 8000);
// Create an input stream to receive data from the server
fromServer = new DataInputStream(socket.getInputStream());
// Create an output stream to send data to the server
toServer = new DataOutputStream(socket.getOutputStream());
}
catch (IOException ex) {
ta.appendText(ex.toString() + '\n');
}
}
/**
* 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);
}
}
Run either one of them from the command line, and the other from jGRASP.
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();
}