0% found this document useful (0 votes)
10 views14 pages

Viva Answers

The document contains multiple Java programming examples demonstrating various GUI components and functionalities using AWT and Swing, including creating a menu bar, displaying a tree structure, using JTable for student data, implementing a progress bar, handling key events, user authentication, and network programming with sockets. Each example includes code snippets that illustrate how to implement the respective features. Additionally, there are examples for retrieving IP addresses, URL information, and creating chat applications using both TCP and UDP protocols.

Uploaded by

rohankharade897
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views14 pages

Viva Answers

The document contains multiple Java programming examples demonstrating various GUI components and functionalities using AWT and Swing, including creating a menu bar, displaying a tree structure, using JTable for student data, implementing a progress bar, handling key events, user authentication, and network programming with sockets. Each example includes code snippets that illustrate how to implement the respective features. Additionally, there are examples for retrieving IP addresses, URL information, and creating chat applications using both TCP and UDP protocols.

Uploaded by

rohankharade897
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

1-Write a program using AWT to create a menu bar where menu bar contains menu items such as File,

Edit, View and create a submenu under the File menu: New and Open

import java.awt.*;
import java.awt.event.*;

public class MenuBarExample extends Frame {


public MenuBarExample() {
// Set title and layout
setTitle("Menu Bar Example");
setLayout(new FlowLayout());
setSize(400, 300);

// Create menu bar


MenuBar menuBar = new MenuBar();

// Create menus
Menu fileMenu = new Menu("File");
Menu editMenu = new Menu("Edit");
Menu viewMenu = new Menu("View");

// Create submenus for File


MenuItem newFile = new MenuItem("New");
MenuItem openFile = new MenuItem("Open");
fileMenu.add(newFile);
fileMenu.add(openFile);

// Add menus to menu bar


menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(viewMenu);

// Set the menu bar to the frame


setMenuBar(menuBar);

// Add a window listener to close the application


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});

// Make the frame visible


setVisible(true);
}
public static void main(String[] args) {
new MenuBarExample();
}
}

2-Write a Itree program to show root directory and its subFolders of your System.

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;

class TreeExample extends JFrame {


DefaultMutableTreeNode root, folder1, folder2, file1, file2, file3;
JScrollPane scrollPane;

TreeExample() {
// Initialize tree nodes
root = new DefaultMutableTreeNode("Root");
folder1 = new DefaultMutableTreeNode("Folder 1");
folder2 = new DefaultMutableTreeNode("Folder 2");
file1 = new DefaultMutableTreeNode("File 1.txt");
file2 = new DefaultMutableTreeNode("File 2.txt");
file3 = new DefaultMutableTreeNode("File 3.txt");

// Build tree structure


root.add(folder1);
root.add(folder2);
folder1.add(file1);
folder1.add(file2);
folder2.add(file3);

// Create JTree with the root node


JTree tree = new JTree(root);

// Use JScrollPane for JTree


scrollPane = new JScrollPane(tree);

// Set layout and add components


setLayout(null);
scrollPane.setBounds(50, 50, 300, 200);
add(scrollPane);

// Frame settings
setTitle("Tree Example");
setSize(400, 300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {


new TreeExample();
}
}

3-Write a Java program to create a table of Name of Student, Percentage and Grade of 10 students using
JTable.

import java.awt.*;
import javax.swing.*;

class StudentTableExample extends JFrame {

StudentTableExample() {
// Column names for the table
String[] columnNames = {"Name of Student", "Percentage", "Grade"};

// Data for the table


String[][] data = {
{"Alice", "85%", "A"},
{"Bob", "78%", "B"},
{"Charlie", "92%", "A+"},
{"David", "67%", "C"},
{"Eve", "88%", "A"},
{"Frank", "74%", "B"},
{"Grace", "81%", "B+"},
{"Hank", "90%", "A+"},
{"Ivy", "95%", "A+"},
{"Jack", "69%", "C"}
};

// Create JTable with the data and column names


JTable table = new JTable(data, columnNames);

// Add JTable to a JScrollPane


JScrollPane scrollPane = new JScrollPane(table);

// Set layout and add components


setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);

// Frame settings
setTitle("Student Table Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String[] args) {


new StudentTableExample();
}
}

4-Write a Program using JProgressBar to show the progress of Progressbar when user clicks on JButton.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class ProgressBarExample extends JFrame {

JProgressBar progressBar;
JButton startButton;

ProgressBarExample() {
// Frame properties
setTitle("JProgressBar Example");
setSize(400, 200);
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Initialize progress bar


progressBar = new JProgressBar(0, 100); // Min = 0, Max = 100
progressBar.setValue(0);
progressBar.setStringPainted(true); // Show progress as a percentage

// Initialize button
startButton = new JButton("Start Progress");

// Add action listener to the button


startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Start a thread to update the progress bar
new Thread(() -> {
for (int i = 0; i <= 100; i++) {
try {
Thread.sleep(50); // Simulate a task taking time
} catch (InterruptedException ex) {
ex.printStackTrace();
}
progressBar.setValue(i); // Update progress bar value
}
}).start();
}
});

// Add components to frame


add(progressBar, BorderLayout.CENTER);
add(startButton, BorderLayout.SOUTH);

setVisible(true);
}

public static void main(String[] args) {


new ProgressBarExample();
}
}

5-Write a program to generate KeyEvent when a key is pressed and display "Key Pressed" message.

import java.awt.*;
import java.awt.event.*;

class SimpleKeyEventExample extends Frame implements KeyListener {

Label label;

SimpleKeyEventExample() {
// Frame properties
setTitle("KeyEvent Example");
setSize(300, 200);
setLayout(new BorderLayout());
setDefaultCloseOperation();

// Initialize Label
label = new Label("Type something...");
label.setAlignment(Label.CENTER);

// Add KeyListener to Frame


addKeyListener(this);

// Add Label to Frame


add(label, BorderLayout.CENTER);

// Make Frame Visible


setVisible(true);
}

@Override
public void keyPressed(KeyEvent e) {
// Display "Key Pressed" message
label.setText("Key Pressed");
}

@Override
public void keyReleased(KeyEvent e) {
// No action needed
}

@Override
public void keyTyped(KeyEvent e) {
// No action needed
}

public void setDefaultCloseOperation() {


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

public static void main(String[] args) {


new SimpleKeyEventExample();
}
}

6-Write a program using JPasswordField and JTextField to demonstrate the use of user authentication.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class UserAuthentication extends JFrame {

JLabel userLabel, passLabel, messageLabel;


JTextField userField;
JPasswordField passField;
JButton loginButton;

UserAuthentication() {
// Frame properties
setTitle("User Authentication");
setSize(350, 200);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Initialize components
userLabel = new JLabel("Username:");
passLabel = new JLabel("Password:");
userField = new JTextField();
passField = new JPasswordField();
loginButton = new JButton("Login");
messageLabel = new JLabel("");

// Set bounds for components


userLabel.setBounds(30, 30, 80, 25);
userField.setBounds(120, 30, 150, 25);
passLabel.setBounds(30, 70, 80, 25);
passField.setBounds(120, 70, 150, 25);
loginButton.setBounds(120, 110, 80, 30);
messageLabel.setBounds(30, 150, 300, 25);

// Add action listener to the login button


loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Authentication logic
String username = userField.getText();
String password = new
String(passField.getPassword()); // Convert char[] to String

if (username.equals("admin") &&
password.equals("password123")) {
messageLabel.setText("Login Successful!");
messageLabel.setForeground(Color.GREEN);
} else {
messageLabel.setText("Invalid username or
password.");
messageLabel.setForeground(Color.RED);
}
}
});

// Add components to frame


add(userLabel);
add(userField);
add(passLabel);
add(passField);
add(loginButton);
add(messageLabel);

// Make frame visible


setVisible(true);
}

public static void main(String[] args) {


new UserAuthentication();
}
}

7-Write a program to demonstrate the use of WindowAdapter class.

import java.awt.*;
import java.awt.event.*;
class WindowAdapterExample extends Frame {

WindowAdapterExample() {
// Frame properties
setTitle("WindowAdapter Example");
setSize(400, 300);
setLayout(new FlowLayout());

Label label = new Label("Close the window to see


WindowAdapter in action.");
add(label);

// Add a WindowListener using WindowAdapter


addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.out.println("Window is closing. Exiting
program...");
System.exit(0); // Close the application
}
});

setVisible(true);
}

public static void main(String[] args) {


new WindowAdapterExample();
}
}

8-Develop a program using InetAddress class to retrieve IP address of computer when hostname is
entered by the user.

import java.net.*;
import java.util.Scanner;

public class IPAddressRetriever {


public static void main(String[] args) {
// Create a scanner object for user input
Scanner scanner = new Scanner(System.in);

// Prompt the user for the hostname


System.out.print("Enter the hostname: ");
String hostname = scanner.nextLine();

try {
// Get the InetAddress object for the hostname
InetAddress inetAddress =
InetAddress.getByName(hostname);

// Display the IP address of the hostname


System.out.println("IP address of " + hostname + " is: "
+ inetAddress.getHostAddress());
} catch (UnknownHostException e) {
// Handle the case where the hostname is unknown
System.out.println("Could not resolve the IP address for
the hostname: " + hostname);
} finally {
// Close the scanner
scanner.close();
}
}
}

9-Write a program using URL class to retrieve the host, protocol, port and file of URL
http://www.msbte.org.in

import java.net.*;

public class URLInfoRetriever {


public static void main(String[] args) {
try {
// Create a URL object with the given URL
URL url = new URL("http://www.msbte.org.in");

// Retrieve and display the protocol, host, port, and file from the
URL
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
System.out.println("Port: " + url.getPort());
System.out.println("File: " + url.getFile());

} catch (MalformedURLException e) {
// Handle the case where the URL is invalid
System.out.println("Invalid URL format");
}
}
}

10-Write a program using Socket and ServerSocket to create Chat Application.

import java.io.*;
import java.net.*;

public class ChatClient {


public static void main(String[] args) {
// Connect to the server at localhost, port 12345
try (Socket socket = new Socket("localhost", 12345)) {
// Create input and output streams
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new
PrintWriter(socket.getOutputStream(), true);

// Create a thread to listen for server messages


Thread readThread = new Thread(new Runnable() {
@Override
public void run() {
try {
String serverMessage;
while ((serverMessage = input.readLine()) !=
null) {
System.out.println("Server: " +
serverMessage);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
readThread.start();

// Sending messages to the server


BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in));
String message;
while (true) {
message = userInput.readLine();
output.println(message); // Send message to server
if (message.equalsIgnoreCase("exit")) {
break;
}
}

socket.close();
System.out.println("Client closed.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

import java.io.*;
import java.net.*;

public class ChatServer {


public static void main(String[] args) {
// Create a ServerSocket to listen on port 12345
try (ServerSocket serverSocket = new ServerSocket(12345)) {
System.out.println("Server is waiting for clients...");

// Accept client connection


Socket clientSocket = serverSocket.accept();
System.out.println("Client connected.");

// Create input and output streams


BufferedReader input = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter output = new PrintWriter(clientSocket.getOutputStream(),
true);

// Create a thread to listen for messages from the client


Thread readThread = new Thread(new Runnable() {
@Override
public void run() {
try {
String clientMessage;
while ((clientMessage = input.readLine()) != null) {
System.out.println("Client: " + clientMessage);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
readThread.start();

// Sending messages to the client


BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in));
String message;
while (true) {
message = userInput.readLine();
output.println(message); // Send message to client
if (message.equalsIgnoreCase("exit")) {
break;
}
}

clientSocket.close();
System.out.println("Server closed.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
11-Write a program using DatagramPacket and DatagramSocket to create chat application.

12-Write a Program to create a Student Table in database and insert a record in a Student table.

You might also like