Professional Documents
Culture Documents
UNIT 1:
Introducing JavaFX GUI Programming
JavaFX Basic Concepts:
✓ JavaFX simplifies rendering of objects because it handles repainting automatically
✓ JavaFX elements are contained in packages that begin with javafx prefix
✓ javafx.application
✓ javafx.stage
✓ javafx.scene
✓ javafx.scene.layout
Layouts:
✓ In JavaFX layout panes manage the process of placing elements in a scene
✓ Layout panes are packaged in javafx.scene.layout
// Create a scene.
Scene myScene = new Scene(rootNode, 300,
200);
// Set the scene on the stage.
myStage.setScene(myScene);
// Show the stage and its scene.
myStage.show();
}
LABEL:
A label just displays a text message
✓ JavaFX label is an instance of Label class packaged in javafx.scene.control
✓ Label inherits Labeled and Control classes
✓ Labeled class provides features that are common to all labelled elements
✓ Control class provides features that are related to controls
JavaFX TextField
example where the user is shown the two text boxes and prompted to fill its user-id and password.
1. package application;
2. import javafx.application.Application;
3. import javafx.scene.Scene;
4. import javafx.scene.control.Button;
5. import javafx.scene.control.Label;
6. import javafx.scene.control.TextField;
7. import javafx.scene.layout.GridPane;
8. import javafx.stage.Stage;
9. public class TextFieldTest extends Application {
10.
11.
12. public static void main(String[] args) {
13. launch(args);
14. }
15.
16. @Override
17. public void start(Stage primaryStage) throws Exception {
18. // TODO Auto-generated method stub
19. Label user_id=new Label("User ID");
20. Label password = new Label("Password");
21. TextField tf1=new TextField();
22. TextField tf2=new TextField();
23. Button b = new Button("Submit");
24. GridPane root = new GridPane();
25. root.addRow(0, user_id, tf1);
26. root.addRow(1, password, tf2);
27. root.addRow(2, b);
28. Scene scene=new Scene(root,800,200);
29. primaryStage.setScene(scene);
30. primaryStage.setTitle("Text Field Example");
31. primaryStage.show();
32. }
33. }
Output:
Play Video
Play
Unmute
Current Time 0:12
Duration 4:57
Loaded: 100.00%
Â
Fullscreen
1. package application;
2. import javafx.application.Application;
3. import javafx.scene.Scene;
4. import javafx.scene.control.Button;
5. import javafx.scene.control.Label;
6. import javafx.scene.control.TextField;
7. import javafx.scene.layout.GridPane;
8. import javafx.stage.Stage;
9. public class TextFieldExample extends Application {
10.
11.
12. public static void main(String[] args) {
13. launch(args);
14. }
15.
16. @Override
17. public void start(Stage primaryStage) throws Exception {
18. // TODO Auto-generated method stub
19. Label user_id=new Label("User ID");
20. Label password = new Label("Password");
21. TextField tf1=new TextField();
22. TextField tf2=new TextField();
23. Button b = new Button("Submit");
24. b.setOnAction(e->System.out.println("You entered: User_ID: "+tf1.getText()+""+"Password:
"+tf2.getText()));
25. GridPane root = new GridPane();
26. root.addRow(0, user_id, tf1);
27. root.addRow(1, password, tf2);
28. root.addRow(2, b);
29. Scene scene=new Scene(root,300,200);
30. primaryStage.setScene(scene);
31. primaryStage.setTitle("Text Field Example");
32. primaryStage.show();
33. }
34. }
Output:
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Registration Form");
// Show stage
primaryStage.show();
}
}
PROGRAM TO FIND MIN MAX AND ASC ORDER OF AN ARRAY LIST USING STREAMS:
public static void main(String[] args) {
// Initialize ArrayList with sample values
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(5);
arrayList.add(1);
arrayList.add(3);
arrayList.add(8);
arrayList.add(2);
import java.util.function.Function;
// Using lambda expressions to define the function to change the case of a string
Function<String, String> toUpperCase = (str) -> str.toUpperCase();
Function<String, String> toLowerCase = (str) -> str.toLowerCase();
import java.util.ArrayList;
import java.util.List;
list1.add("Hello");
list1.add("world");
list2.add("HELLO");
list2.add("WORLD");
compare(list1, list2);
public static <T extends CharSequence> void compare(List<? extends T> list1, List<? extends T> list2) {
if (list1.size() != list2.size()) {
return;
T str1 = list1.get(i);
T str2 = list2.get(i);
if (!str1.toString().equalsIgnoreCase(str2.toString())) {
} else {
}
}
In this program, the compare method is defined with two type parameters T that are bounded by
the CharSequence class and are using wildcard characters ?. This means that the method can only be
used with lists of subtypes of CharSequence, such as String .
In the main method, the compare method is used to compare two lists of strings. The method
compares the elements of both lists and prints appropriate messages when the elements are not
equal.
This way it demonstrates that the type parameter T is bounded by the CharSequence class and using
wildcard characters ?, so it only works with subtypes of CharSequence and it compares the elements
of both lists and prints appropriate messages when the elements are not equal.
PROGRAM:
package com.javacodegeeks.examples;
import java.util.concurrent.Phaser;
public class PhaserExample
System.out.println("Phasecount is "+phasecount);
//now that all threads are initiated, we will de-register main thread
phaser.arriveAndDeregister();
Thread.sleep(10000);
phasecount = phaser.getPhase();
System.out.println("Phasecount is "+phasecount);
phaser.register();
new Thread(){
@Override
try
System.out.println(Thread.currentThread().getName()+" arrived");
Thread.sleep(sleepTime);
}
catch (InterruptedException e)
e.printStackTrace();
}.start();
WORKING OF PHASER:
A Phaser is a reusable synchronization barrier in the Java Concurrent package. It is similar to a
CyclicBarrier and a CountDownLatch, but provides more flexibility and control over the execution
of concurrent threads.
A Phaser works by dividing a set of threads into multiple "parties". Each party is required to reach
the barrier point (or "phase") before the next phase can begin. The Phaser class provides methods
for registering, deregistering, and awaiting parties, as well as methods for controlling the flow of
execution.
For example, consider a Phaser used to coordinate the execution of three tasks in parallel:
import java.util.concurrent.Phaser;
As you can see all the tasks are starting phase 1 at the same time, and once all the parties have arrived,
Phaser moves to the next phase, and all parties are released to proceed.
Phasers are useful in situations where you need to coordinate the execution of multiple threads and you need
more control over the execution flow than what is provided by a CyclicBarrier or a CountDownLatch.
Q.The program should print the name of the thread in
the phaser and registered and unregistered parties and
phase level
Sure, here's an example of a program that demonstrates the use of a Phaser, including printing the name of the
thread in the Phaser, registered and unregistered parties, and the current phase level:
import java.util.concurrent.Phaser;
while (!phaser.isTerminated()) {
phaser.arriveAndAwaitAdvance();
}
class Task extends Thread {
this.phaser = phaser;
setName(name);
phaser.register();
phaser.arriveAndDeregister();
In this program, the main method creates a Phaser with 1 initial party. Three tasks are created,
started, and registered with the Phaser. Each task represents a party, which calls the
arriveAndAwaitAdvance() and arriveAndDeregister() method on the Phaser when it reaches a barrier
point. The arriveAndAwaitAdvance() method tells the Phaser that the party has arrived and is waiting
for the other parties to arrive. Once all parties have arrived, the Phaser moves to the next phase,
and all parties are released to proceed.
Here's an example of a Java program that illustrates the use of a CountDownLatch to print even
numbers between 1 to 10 and odd numbers between 11 to 20:
import java.util.concurrent.CountDownLatch;
evenThread.start();
oddThread.start();
latch.await(); // main thread waits for evenThread and oddThread to complete
In this example, the main method creates a CountDownLatch with a count of 2. Two threads are
created, one for printing even numbers and the other for printing odd numbers. The main thread
calls the await() method on the CountDownLatch, which causes it to wait until the count reaches
zero.
The two worker threads, evenThread and oddThread, perform their respective operations and then
call the countDown() method on the CountDownLatch, which decrements the count. Once both
threads have finished and the count reaches zero, the main thread is released from the await() call
and continues execution.
Even number: 2
Even number: 4
Even number: 6
Even number: 8
Even number: 10
Odd number: 11
Odd number: 13
Odd number: 15
Odd number: 17
Odd number: 19
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Map;
In this example, the DomainNameServer class creates an RMI server that implements the DomainName interface. The
interface has a single method, getDomainName(), that takes a URL as a parameter and returns the domain name
using the URL class. The server exports the object and binds it to the RMI registry so that it can be located by
clients.
The DomainNameClient class creates an RMI client that looks up the DomainName object on the RMI registry
Server Side:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
while (true) {
Socket socket = serverSocket.accept();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hello, client!");
out.close();
socket.close();
}
}
}
Client Side:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
Server Side:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
while (true) {
Socket socket = serverSocket.accept();
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
Client Side:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
Java program that demonstrates how to implement a student database using information such as
name, USN, and CGPA, with the corresponding datatype varchar(20), varchar(10) and double, and
display the content in a table format using JDBC:
import java.sql.*;
try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Create a statement
statement = connection.createStatement();
try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Create a statement
statement = connection.createStatement();
JDBC EX:
import java.sql.*;
try{
//Step1: load the driver
Class.forName(driver);
if(conn==null){
System.out.println("Error!!");
}
else{
System.out.println("Connected!!!");
}
//Step3: Create a STMT obj for handling query
//Do it using CONN obj
Statement stmt=conn.createStatement();
//ResultSet rs=stmt.executeUpdate(sql);
/*while(rs.next()){
System.out.println(rs.getString(1)+" "+
rs.getString(2));
}*/
insertQuery
import java.sql.*;
Connection conn=DriverManager.getConnection
(dbURL, user, password);
Statement stmt=conn.createStatement();
String sql="insert into employee values(2,'xyz')";
String sql1="update employee set id=3 where name='xyz'";
String sql2="delete from employee where id=1";
stmt.executeUpdate(sql2);
conn.close();
}catch(Exception e){
System.out.println(e);
}
}
printBooks:
import java.sql.*;
public class printBooks {
public static void main(String[] args) {
final String url="com.mysql.jdbc.Driver";
final String dbURL="jdbc:mysql://localhost/bookDB";
final String user="root";
final String password="";
try{
Class.forName(url);
Connection conn=DriverManager.getConnection
(dbURL, user, password);
Statement stmt=conn.createStatement();
int res=stmt.executeUpdate(sql);
int res1=stmt.executeUpdate(sql2);
if(res<0 || res1<0) {
System.out.println("Insertion cannot be done");
System.exit(0);
}
ResultSet rs=stmt.executeQuery(sql1);
while(rs.next()) {
System.out.println(rs.getString(1));
}
}catch(Exception e) {
System.out.println(e);
}
}
}
SELECT EX:
import java.sql.*;
class selectEx{
public static void main(String args[]){
final String url="jdbc:mysql://localhost:3306/logindb";
final String user="root";
final String pwd="";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.
getConnection(url,user,pwd);
Statement stmt=con.createStatement();
con.close();
}catch(Exception e){ System.out.println(e);
}
}
}
Open with
selectQuery:
import java.sql.*;
Connection conn=DriverManager.getConnection
(dbURL, user, password);
Statement stmt=conn.createStatement();
String sql="select * from employee";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getInt(1)+" "
+rs.getString(2));
}
conn.close();
}catch(Exception e){
System.out.println(e);
}
Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.
As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP translator.
The JSP translator is a part of the web server which is responsible for translating the JSP page into
Servlet. After that, Servlet page is compiled by the compiler and gets converted into the class file.
Moreover, all the processes that happen in Servlet are performed on JSP later like initialization,
committing response to the browser and destroy.
index.jsp
Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in the JSP
page. We will learn scriptlet tag later.
1. <html>
2. <body>
3. <% out.print(2*5); %>
4. </body>
5. </html>
o scriptlet tag
o expression tag
o declaration tag
1. <% java source code %>
Example of JSP scriptlet tag
In this example, we are displaying a welcome message.
Play Video
1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>
File: index.html
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
File: welcome.jsp
1. <html>
2. <body>
3. <%
4. String name=request.getParameter("uname");
5. out.print("welcome "+name);
6. %>
7. </form>
8. </body>
9. </html>
1. <html>
2. <body>
3. <%= "welcome to jsp" %>
4. </body>
5. </html>
Note: Do not end your statement with semicolon in case of expression tag.
1. <html>
2. <body>
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4. </body>
5. </html>
Example of JSP expression tag that prints the user name
In this example, we are printing the username using the expression tag. The index.html file gets the
username and sends the request to the welcome.jsp file, which displays the username.
File: index.jsp
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname"><br/>
5. <input type="submit" value="go">
6. </form>
7. </body>
8. </html>
File: welcome.jsp
1. <html>
2. <body>
3. <%= "Welcome "+request.getParameter("uname") %>
4. </body>
5. </html>
The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.
1. <%! field or method declaration %>
Difference between JSP Scriptlet tag and Declaration tag
Jsp Scriptlet Tag Jsp Declaration Tag
The jsp scriptlet tag can only declare The jsp declaration tag can declare variables as well as methods.
variables not methods.
The declaration of scriptlet tag is The declaration of jsp declaration tag is placed outside the
placed inside the _jspService()
_jspService() method.
method.
index.jsp
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>
index.jsp
1. <html>
2. <body>
3. <%!
4. int cube(int n){
5. return n*n*n*;
6. }
7. %>
8. <%= "Cube of 3 is:"+cube(3) %>
9. </body>
10. </html>
@Override
public void init() {
Button button = new Button("OPEN");
VBox vBox = new VBox();
vBox.setSpacing(8);
vBox.setPadding(new Insets(10,10,10,10));
vBox.getChildren().addAll(
new Label("Your Name"),
new TextField(),
new Label("Your Username"),
new TextField(),
new Label("Your Password"),
new PasswordField(),
new Label("Confirm Password"),
new PasswordField(),
new Button("REGISTER"));
root.getChildren().addAll(vBox);
button.setOnAction(actionEvent-> {
if(stage!=null){
stage.requestFocus();
return;
}
stage = new Stage();
StackPane stackPane = new StackPane();
stage.setScene(new Scene(stackPane, 200,200));
stage.show();
});
}
@Override
public void start(Stage primaryStage) {
Scene scene = new Scene(root,400,600);
primaryStage.setScene(scene);
primaryStage.show();
primaryStage.setTitle("Registration Example JavaFX");
primaryStage.setAlwaysOnTop(true);
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h3>Cookie Name: " + cookieName + "</h3>");
out.println("<h3>Cookie Value: " + cookieValue + "</h3>");
}
}
OR
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h3>Cookie Name: " + cookieName + "</h3>");
out.println("<h3>Cookie Value: " + cookieValue + "</h3>");
out.println("<h3>Max Age: " + maxAge + "</h3>");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Iterate through the student list and display only those with less than 20 marks in CIE
for (Student student : studentList) {
if (student.getCieMarks() < 20) {
out.println("<tr>");
out.println("<td>" + student.getName() + "</td>");
out.println("<td>" + student.getUsn() + "</td>");
out.println("<td>" + student.getCieMarks() + "</td>");
out.println("</tr>");
}
}
}
a Java program that demonstrates how to use JavaServer Pages (JSP) to display a list of students
who scored less than 20 marks in CIE:
<html>
<head>
<title>Students with Less than 20 marks in CIE</title>
</head>
<body>
<h2>Students with Less than 20 marks in CIE</h2>
<table border="1">
<tr>
<th>Name</th>
<th>USN</th>
<th>CIE Marks</th>
</tr>
<%
ArrayList<Student> studentList = new ArrayList<>();
studentList.add(new Student("John Doe", "1MS17IS001", 15));
studentList.add(new Student("Jane Smith", "1MS17IS002", 18));
studentList.add(new Student("Bob Johnson", "1MS17IS003", 22));
// Iterate through the student list and display only those with less than 20 marks in
CIE
for (Student student : studentList) {
if (student.getCieMarks() < 20) {
%>
<tr>
<td><%= student.getName() %></td>
<td><%= student.getUsn() %></td>
<td><%= student.getCieMarks() %></td>
</tr>
<%
}
}
%>
</table>
</body>
</html>
In this example, a JSP page is used to display a table of students with less than 20 marks in CIE. The student data
is stored in an ArrayList of Student objects, which is initialized in the JSP page using scriptlet tags. The JSP page
uses a for loop to iterate through the student list, displaying only those students with less than 20 marks in CIE.
Note that JSP is a technology that is depreciated, JavaServer Faces (JSF) is recommended for building web
applications in Java.
Q
Here's an example of a Java program that demonstrates how to use a generic functional interface
and lambda expressions to find the reverse of a given string and the factorial of a given number:
import java.util.function.Function;
return sb.reverse().toString();
};
int result = 1;
result *= i;
return result;
};
int inputNumber = 5;
Q.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
int n = 100;
writer.close();
// Sort and write the entire list of sorted integers into another file named "sortedIntegers.txt"
Collections.sort(sortedIntegers);
try {
sortedWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
});