0% found this document useful (0 votes)
26 views38 pages

Assignment 3-5 - 110100

The document contains multiple Java programming assignments that cover various concepts such as interfaces, classes, inheritance, exception handling, and file operations. It includes examples of creating classes like Country, State, Staff, and Patient, along with methods for displaying details and handling user input. Additionally, it demonstrates the use of functional interfaces and exception handling in Java.

Uploaded by

psb18039
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)
26 views38 pages

Assignment 3-5 - 110100

The document contains multiple Java programming assignments that cover various concepts such as interfaces, classes, inheritance, exception handling, and file operations. It includes examples of creating classes like Country, State, Staff, and Patient, along with methods for displaying details and handling user input. Additionally, it demonstrates the use of functional interfaces and exception handling in Java.

Uploaded by

psb18039
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/ 38

ASSIGNMENT 3

SET A

A1

interface Continent {

String getContinentName();

class Country implements Continent {

String continentName;

String countryName;

Country(String continentName, String countryName) {

this.continentName = continentName;

this.countryName = countryName;

@Override

public String getContinentName() {

return continentName;

public String getCountryName() {

return countryName;

class State extends Country {

String stateName;

String placeName;
State(String continentName, String countryName, String stateName, String placeName) {

super(continentName, countryName);

this.stateName = stateName;

this.placeName = placeName;

public String getStateName() {

return stateName;

public String getPlaceName() {

return placeName;

public void displayDetails() {

System.out.println("Place: " + getPlaceName());

System.out.println("State: " + getStateName());

System.out.println("Country: " + getCountryName());

System.out.println("Continent: " + getContinentName());

public class Test {

public static void main(String[] args) {

// Create an object of the State class

State place = new State("Asia", "India", "Maharashtra", "Mumbai");

// Display the place, state, country, and continent

place.displayDetails();

}
A2

import java.util.Scanner;

// Abstract class Staff

abstract class Staff {

protected int id;

protected String name;

// Parameterized constructor

public Staff(int id, String name) {

this.id = id;

this.name = name;

// Abstract method to be implemented by subclasses

abstract void displayDetails();

// Subclass OfficeStaff

class OfficeStaff extends Staff {

private String department;

// Parameterized constructor

public OfficeStaff(int id, String name, String department) {

super(id, name); // Call to the superclass constructor

this.department = department;

// Implement the abstract method


@Override

void displayDetails() {

System.out.println("ID: " + id);

System.out.println("Name: " + name);

System.out.println("Department: " + department);

System.out.println("--------------------------");

// Main class to test the implementation

public class TestStaff {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input: Number of OfficeStaff objects

System.out.print("Enter the number of OfficeStaff members: ");

int n = scanner.nextInt();

scanner.nextLine(); // Consume the newline

// Create an array of OfficeStaff objects

OfficeStaff[] staffArray = new OfficeStaff[n];

// Input: OfficeStaff details

for (int i = 0; i < n; i++) {

System.out.println("Enter details for OfficeStaff " + (i + 1));

System.out.print("Enter ID: ");

int id = scanner.nextInt();

scanner.nextLine(); // Consume the newline

System.out.print("Enter Name: ");


String name = scanner.nextLine();

System.out.print("Enter Department: ");

String department = scanner.nextLine();

// Create a new OfficeStaff object and add it to the array

staffArray[i] = new OfficeStaff(id, name, department);

// Display all OfficeStaff details

System.out.println("\nDetails of OfficeStaff members:");

for (OfficeStaff staff : staffArray) {

staff.displayDetails();

scanner.close();

A3

import java.util.Scanner;

interface Operation {

// Constants in interfaces are implicitly public, static, and final

double PI = 3.142;

// Abstract methods

double area();

double volume();

}
class Cylinder implements Operation {

private double radius;

private double height;

// Constructor to initialize radius and height

public Cylinder(double radius, double height) {

this.radius = radius;

this.height = height;

// Implement the area method

@Override

public double area() {

// Area of a cylinder = 2 * PI * r * (r + h)

return 2 * PI * radius * (radius + height);

// Implement the volume method

@Override

public double volume() {

// Volume of a cylinder = PI * r^2 * h

return PI * radius * radius * height;

public class TestCylinder {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Taking radius input from the user


System.out.print("Enter the radius of the cylinder: ");

double radius = scanner.nextDouble();

// Taking height input from the user

System.out.print("Enter the height of the cylinder: ");

double height = scanner.nextDouble();

// Create an object of the Cylinder class with user inputs

Cylinder cylinder = new Cylinder(radius, height);

// Calculate and display the area and volume

System.out.println("Area of the cylinder: " + cylinder.area());

System.out.println("Volume of the cylinder: " + cylinder.volume());

scanner.close(); // Close the scanner to avoid resource leaks

A4

import java.util.Scanner;

@FunctionalInterface

interface Cube {

int calculate(int num);

public class CubeCalculator {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Using a lambda expression to define the calculate method

Cube cube = n -> n * n * n;


// Calculate the cube of a given number

System.out.println("Enter a number:");

int number = sc.nextInt();

int result = cube.calculate(number);

// Display the result

System.out.println("The cube of " + number + " is: " + result);

SET B

B1]

import java.util.Scanner;

abstract class Order

int id;

String description;

public Order()

this.id=0;

this.description=" ";

public Order(int id,String description)

this.id=id;

this.description=description;

abstract void accept();


abstract void display();

class PurchaseOrder extends Order

String customerName;

public PurchaseOrder()

super();

this.customerName="";

public PurchaseOrder(int id,String description,String customerName)

super(id,description);

this.customerName=customerName;

void accept()

Scanner sc=new Scanner(System.in);

System.out.print("Enter purchase order Id: ");

id=sc.nextInt();

sc.nextLine();

System.out.print("Enter description: ");

description=sc.nextLine();

System.out.print("Enter Customer Name: ");

customerName=sc.nextLine();

void display()

{
System.out.printf("%-5d|%-25s|%-20s|\n",id,description,customerName);

class SalesOrder extends Order

String vendorName;

public SalesOrder()

super();

this.vendorName=" ";

public SalesOrder(int id,String description,String vendorName)

super(id,description);

this.vendorName=vendorName;

void accept()

Scanner sc=new Scanner(System.in);

System.out.print("Enter Sales order Id:");

id=sc.nextInt();

sc.nextLine();

System.out.print("Enter description:");

description=sc.nextLine();

System.out.print("Enter Vendor Name");

vendorName=sc.nextLine();

}
void display()

System.out.printf("|%-5d|%-25s|%-20s|\n",id,description,vendorName);

public class B1

public static void main(String[] args)

PurchaseOrder po1=new PurchaseOrder();

PurchaseOrder po2=new PurchaseOrder();

PurchaseOrder po3=new PurchaseOrder();

System.out.println("Enter details for purchase order 1:");

po1.accept();

System.out.println("Enter details for purchase order 2:");

po2.accept();

System.out.println("Enter details for purchase order 3:");

po3.accept();

SalesOrder so1=new SalesOrder();

SalesOrder so2=new SalesOrder();

SalesOrder so3=new SalesOrder();

System.out.println("Enter details for Sales order 1:");

so1.accept();

System.out.println("Enter details for Sales order 2:");

so2.accept();

System.out.println("Enter details for Sales order 3:");

so3.accept();

System.out.println("\n Puchase Order:");


System.out.println("ID |Description |Customer Name |");

System.out.println("-----------------------------------------------------");

po1.display();

po2.display();

po3.display();

System.out.println("\n Sales Order:");

System.out.println("ID |Description |Vendor Name |");

System.out.println("------------------------------------------------------");

so1.display();

so2.display();

so3.display();

B2]

import java.util.*;

interface MarkerInt{

class product implements MarkerInt

int pid,pcost,quantity;

String pname;

static int cnt;

product()

//DefaultConstructor

pid=1;

pcost=10;

quantity=1;

pname="Pencil";
cnt++;

//Parametrized constructor

product(int pid,String pname,int pcost,int quantity)

this.pid=pid;

this.pname=pname;

this.pcost=pcost;

this.quantity=quantity;

cnt++;

System.out.println("Count of object is : "+cnt+"\n");

void display()

System.out.println("|\t"+pid+"\t"+pname+"\t"+pcost+"\t\t"+quantity+"\t|");

public class B2

public static void main(String[] args)

Scanner sc=new Scanner(System.in);

System.out.println("Enter no of Product : ");

int n=sc.nextInt();

product p[]=new product[n];

for(int i=0;i<n;i++)

System.out.println("Enter Product "+(i+1)+" Details:\n");

System.out.println("Enter Product ID : ");

int pid=sc.nextInt();

sc.nextLine();
System.out.println("Enter Product Name : ");

String pn=sc.nextLine();

System.out.println("Enter Product Cost : ");

int pc=sc.nextInt();

System.out.println("Enter Product Quantity : ");

int pq=sc.nextInt();

p[i]=new product(pid,pn,pc,pq);

System.out.println("\n******************Product Details****************** \n");

System.out.println("|\tPID\tPname\tCost\tQuantity\t|");

for(int i=0;i<n;i++)

p[i].display();

sc.close();

SET C

import java.util.Scanner;

interface Department

String deptName = "CS";

String depthead = "HOD";

void displayDept();

class Hostel

String hostelName;

String hostelLocation;

int noOfRooms;
public Hostel( String hostelName ,String hostelLocation, int noOfRooms)

this.hostelName = hostelName;

this.hostelLocation = hostelLocation;

this.noOfRooms = noOfRooms;

public void displayHostel()

System.out.println("Hostel Name : " + hostelName);

System.out.println("Hostel Location : " + hostelLocation);

System.out.println("No. of rooms : " + noOfRooms);

class Student extends Hostel implements Department

String studentName;

String regNo;

String electiveSubject;

double avgMarks;

public Student(String hostelName , String hostelLocation , int noOfRooms , String


studentName,String regNo ,String electiveSubject , double avgMarks)

super(hostelName , hostelLocation , noOfRooms);

this.studentName = studentName;

this.regNo = regNo;

this.electiveSubject = electiveSubject;

this.avgMarks = avgMarks;
}

public void displayDetails()

System.out.println("\nStudent Name : "+studentName);

System.out.println("Reg No. : "+regNo);

System.out.println("Elective Subject : "+electiveSubject);

System.out.println("Average Marks :" + avgMarks);

displayHostel();

displayDept();

public void displayDept()

System.out.println("Department Name : "+deptName);

System.out.println("Depatment Head : "+depthead);

public class C1

static Scanner inp = new Scanner(System.in);

static Student student = null;

public static void admit()

System.out.print("Enter hostel name : ");

String hostelName = inp.nextLine();

System.out.print("Enter hostel location : ");

String hostelLocation = inp.nextLine();


System.out.print("Enter no. of rooms : ");

int noOfRooms = inp.nextInt();

System.out.print("Enter Student name : ");

String studentName = inp.nextLine();

inp.nextLine();

System.out.print("Enter reg no. : ");

String regNo = inp.nextLine();

System.out.print("Enter elective subject : ");

String electiveSubject = inp.nextLine();

System.out.print("Enter average marks : ");

double avgMarks = inp.nextDouble();

inp.nextLine();

student = new Student(hostelName , hostelLocation , noOfRooms, studentName , regNo ,


electiveSubject , avgMarks);

System.out.println("Student Admitted Successfully.");

public static void migrate()

if(student == null)

System.out.println("No student admitted.");

}
else

System.out.print("Enter new hostel name : ");

student.hostelName = inp.nextLine();

System.out.print("Enter new hostel location : ");

student.hostelLocation = inp.nextLine();

System.out.print("Enter new no. of rooms : ");

student.noOfRooms = inp.nextInt();

inp.nextLine();

System.out.println("Student Migrated to new hostel successfully.");

public static void display()

if(student == null)

System.out.println("No student admitted.");

else

student.displayDetails();

public static void main(String[] args)


{

int choice;

do

System.out.println("\nMenu\n1. Admit new student \n2. Migrate student \n3. Display student
details \n4. Exit");

System.out.print("Enter your choice : ");

choice = inp.nextInt();

inp.nextLine();

switch(choice)

case 1 : admit(); break;

case 2 : migrate(); break;

case 3 : display(); break;

case 4 : System.out.println("Exit"); break;

default : System.out.println("Invalid choice"); break;

}while(choice !=4);

ASSIGNMENT 4

SET A

1]

import java.util.Scanner;

class CovidPositiveException extends Exception {

CovidPositiveException(String message) {

super(message);

}
}

class Patient {

String patient_name;

int patient_age;

double patient_oxy_level;

int patient_HRCT_report;

// Constructor

Patient(String name, int age, double oxyLevel, int hrctReport) {

this.patient_name = name;

this.patient_age = age;

this.patient_oxy_level = oxyLevel;

this.patient_HRCT_report = hrctReport;

// Method to check the patient condition

void checkCondition() throws CovidPositiveException {

if (patient_oxy_level < 95.0 && patient_HRCT_report > 10) {

throw new CovidPositiveException("Patient is Covid Positive(+) and Needs to be


Hospitalized");

} else {

displayInfo();

// Method to display patient information

void displayInfo() {

System.out.println("Patient Name: " + patient_name);

System.out.println("Patient Age: " + patient_age);

System.out.println("Oxygen Level: " + patient_oxy_level);


System.out.println("HRCT Report: " + patient_HRCT_report);

public class a1{

public static void main(String[] args) {

// Create a patient object

// Patient patient = new


Patient(patient_name,patient_age,patient_oxy_level,patient_HRCT_report);

Scanner sc = new Scanner(System.in);

System.out.println("enter name");

String name = sc.nextLine();

System.out.println("enter age");

int age = sc.nextInt();

System.out.println("enter oxy level");

double oxylevel = sc.nextInt();

System.out.println("enter hrtc report");

int HRCTreport = sc.nextInt();

try {

Patient patient = new Patient(name,age,oxylevel,HRCTreport);

// Check the patient condition

patient.checkCondition();

} catch (CovidPositiveException e) {

System.out.println(e.getMessage());

} finally {

System.out.println("Patient evaluation complete.");

}
}}

2]

import java.io.*;

public class a2{

public static void main(String[] args) {

File f = new File("sample.txt");

if (!f.exists()) {

System.out.println("File not found!");

System.exit(0);

try {

// Reading the file into a StringBuilder for reverse output

FileReader file_reader = new FileReader(f);

BufferedReader buf_reader = new BufferedReader(file_reader);

StringBuilder content = new StringBuilder();

String line;

System.out.println("Original content in UPPER CASE:");

// Reading and converting each line to uppercase

while ((line = buf_reader.readLine()) != null) {

System.out.println(line.toUpperCase());

content.append(line).append("\n");

buf_reader.close();
// Display contents in reverse order

System.out.println("\nContent in Reverse Order:");

System.out.println(content.reverse().toString());

} catch (IOException e) {

System.out.println("IO exception = " + e);

3]

import java.io.*;

public class a3{

public static void main(String[] args) {

if (args.length < 2) {

System.out.println("Usage: java FileCopyApp <source file> <destination file>");

System.exit(0);

File sourceFile = new File(args[0]);

File destinationFile = new File(args[1]);

// Check if source file exists

if (!sourceFile.exists()) {

System.out.println("Source file does not exist!");

System.exit(0);

try {

// File readers and writers

FileReader file_reader = new FileReader(sourceFile);


BufferedReader buf_reader = new BufferedReader(file_reader);

FileWriter file_writer = new FileWriter(destinationFile);

BufferedWriter buf_writer = new BufferedWriter(file_writer);

String line;

// Read from the source file and write to the destination file

while ((line = buf_reader.readLine()) != null) {

buf_writer.write(line);

buf_writer.newLine();

// Add the comment 'end of file'

buf_writer.write("end of file");

// Close the readers and writers

buf_reader.close();

buf_writer.close();

System.out.println("File copied successfully with 'end of file' comment.");

} catch (IOException e) {

System.out.println("IO Exception: " + e);

SET B

2]

import java.util.Scanner;

class InvalidUsernameException extends Exception


{

public InvalidUsernameException(String message)

super(message);

class InvalidPasswordException extends Exception

public InvalidPasswordException(String message)

super(message);

public class B2

String username;

String password;

public B2()

this.username = "";

this.password = "";

public B2(String username , String password) throws InvalidUsernameException ,


InvalidPasswordException

if(!isValidUsername(username))

{
throw new InvalidUsernameException("Invalid Username : Username should be atleast 5
characters long.");

if(!isValidPassword(password))

throw new InvalidPasswordException("Invalid Password : Password should be atleast 8


characters long.");

this.username = username;

this.password = password;

private boolean isValidUsername(String username)

return username.length()>=5;

private boolean isValidPassword(String password)

return password.length() >= 8 && password.matches(".*\\d.*") && password.matches(".*[A-Z,a-


z].*") && password.matches(".*[!@#$%^&*].*");

public void display()

System.out.println("Username : "+ this.username);

System.out.println("Password : "+ this.password);

}
public static void main(String[] args)

Scanner inp = new Scanner(System.in);

try

System.out.print("Enter username : ");

String username = inp.nextLine();

System.out.print("Enter password : ");

String password = inp.nextLine();

B2 email = new B2(username , password);

email.display();

catch(InvalidUsernameException exp)

System.out.println(exp.getMessage());

catch(InvalidPasswordException exp)

System.out.println(exp.getMessage());

3]

import java.util.Scanner;
class InvalidDateException extends Exception{

String msg="Invalid date...\nTry Again\n";

public String toString(){

return msg;

class MyDate{

int day,mon,yr;

MyDate(int d,int m,int y){

day=d;

mon=m;

yr=y;

void display(){

System.out.println("\n\t\tDate\n");

System.out.println("\t-------------");

System.out.println("\tDay\tMonth\tYear");

System.out.println("\t-------------");

System.out.println("\t"+day+"\t"+mon+"\t"+yr);

System.out.println("\t-------------");

public class b3

public static void main(String arg[])

Scanner sc=new Scanner(System.in);


System.out.println("Enter Date:dd mm yyyy");

int day=sc.nextInt();

int mon=sc.nextInt();

int yr=sc.nextInt();

int flag=0;

try{

if(mon<=0||mon>12)

throw new InvalidDateException();

else{

if(mon==1||mon==3||mon==5||mon==7||mon==8||mon==10||mon==12)

if(day>=1&&day<=31)

flag=1;

else

throw new InvalidDateException();

}else if(mon==2){

if(yr%4==00){

if(day>=1&&day<=29)

flag=1;

else

throw new InvalidDateException();

}else{

if(mon==4||mon==6||mon==9||mon==11){

if(day>=1&&day<=30)

flag=1;

else

throw new InvalidDateException();

}
}

if(flag==1){

MyDate dt=new MyDate(day,mon,yr);

dt.display();

}catch(InvalidDateException e){

System.out.println(e);

ASSIGNMENT 5

SET A

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class Calculator extends JFrame implements ActionListener

JTextField display;

JPanel panel;

String cinput="";

double cresult=0.0;

char lastop = ' ';

boolean resultdisp = false;

public Calculator()

setTitle("Simple Calculator");

setLayout(new BorderLayout());

display=new JTextField(10);

display.setEditable(false);

add(display,BorderLayout.NORTH);
panel=new JPanel();

panel.setLayout(new GridLayout(4,4));

add(panel,BorderLayout.CENTER);

String[] buttonLabels={"1","2","3","+","4","5","6","-","7","8","9","*","0",".","=","/"};

for(String label:buttonLabels)

JButton button=new JButton(label);

button.addActionListener(this);

panel.add(button);

public void actionPerformed(ActionEvent e)

String command = e.getActionCommand();

if(command.equals("="))

if(!resultdisp)

calculateResult();

resultdisp=true;

else if(isOperator(command))

if(!resultdisp)

calculateResult();

}
lastop=command.charAt(0);

cinput="";

resultdisp=false;

else

cinput += command;

display.setText(cinput);

public boolean isOperator(String input)

return "+-*/".contains(input);

public void calculateResult()

try

double cvalue=Double.parseDouble(cinput);

switch(lastop)

case '+' : cresult += cvalue;

break;

case '-' : cresult -= cvalue;

break;

case '*': cresult *= cvalue;

break;

case '/': cresult /= cvalue;

break;

default : cresult = cvalue;

break;
}

display.setText(Double.toString(cresult));

}catch(NumberFormatException e)

display.setText("Error");

public static void main(String[] args)

Calculator calc = new Calculator();

calc.setSize(400,400);

calc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

calc.setVisible(true);

SET B

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.text.AttributeSet;

import javax.swing.text.SimpleAttributeSet;

import javax.swing.text.StyleConstants;

import javax.swing.text.StyledDocument;

public class GUI {

private JFrame frame;

private JTextField nameField;

private JComboBox<String> classComboBox;

private JTextPane hobbiesTextPane;

private JTextPane resultTextPane;


private JCheckBox musicCheckBox;

private JCheckBox sportCheckBox;

private JCheckBox travellingCheckBox;

private JCheckBox boldCheckBox;

private JCheckBox italicCheckBox;

private JCheckBox underlineCheckBox;

public GUI() {

frame = new JFrame("User Information");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(new BorderLayout());

JPanel inputPanel = new JPanel();

inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.PAGE_AXIS));

// Your Name

inputPanel.add(new JLabel("Your Name:"));

nameField = new JTextField(20);

inputPanel.add(nameField);

// Your Class

JPanel classPanel = new JPanel();

classPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

classPanel.add(new JLabel("Your Class:"));

String[] classOptions = {"Select", "FY", "SY", "TY"};

classComboBox = new JComboBox<>(classOptions);

classPanel.add(classComboBox);

inputPanel.add(classPanel);

// Your Hobbies

JPanel hobbiesPanel = new JPanel();


hobbiesPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

hobbiesPanel.add(new JLabel("Your Hobbies:"));

musicCheckBox = new JCheckBox("Music");

sportCheckBox = new JCheckBox("Sport");

travellingCheckBox = new JCheckBox("Travelling");

hobbiesPanel.add(musicCheckBox);

hobbiesPanel.add(sportCheckBox);

hobbiesPanel.add(travellingCheckBox);

inputPanel.add(hobbiesPanel);

// Font Settings

JPanel fontPanel = new JPanel();

fontPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

fontPanel.add(new JLabel("Font:"));

String[] fontOptions = {"Select", "Arial", "Times New Roman", "Verdana"};

JComboBox<String> fontComboBox = new JComboBox<>(fontOptions);

fontPanel.add(fontComboBox);

inputPanel.add(fontPanel);

// Font Size

JPanel sizePanel = new JPanel();

sizePanel.setLayout(new FlowLayout(FlowLayout.LEFT));

sizePanel.add(new JLabel("Size:"));

String[] sizeOptions = {"Select", "8", "10", "12", "14"};

JComboBox<String> sizeComboBox = new JComboBox<>(sizeOptions);

sizePanel.add(sizeComboBox);

inputPanel.add(sizePanel);

// Font Style

JPanel stylePanel = new JPanel();

stylePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
stylePanel.add(new JLabel("Style:"));

boldCheckBox = new JCheckBox("Bold");

italicCheckBox = new JCheckBox("Italic");

underlineCheckBox = new JCheckBox("Underlne");

stylePanel.add(boldCheckBox);

stylePanel.add(italicCheckBox);

stylePanel.add(underlineCheckBox);

inputPanel.add(stylePanel);

// Result Button

JButton submitButton = new JButton("Submit");

submitButton.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

displayUserInformation();

});

inputPanel.add(submitButton);

frame.add(inputPanel, BorderLayout.NORTH);

resultTextPane = new JTextPane();

resultTextPane.setEditable(false);

frame.add(new JScrollPane(resultTextPane), BorderLayout.CENTER);

frame.pack();

frame.setVisible(true);

private void displayUserInformation() {

String name = nameField.getText();


String selectedClass = classComboBox.getSelectedItem().toString();

StyledDocument doc = resultTextPane.getStyledDocument();

SimpleAttributeSet attributes = new SimpleAttributeSet();

// Font and Style Settings

String selectedFont = "Arial";

int fontSize = 12;

int fontStyle = Font.PLAIN;

if (selectedFont != null) {

StyleConstants.setFontFamily(attributes, selectedFont);

String selectedSize = "12";

try {

fontSize = Integer.parseInt(selectedSize);

} catch (NumberFormatException e) {

// Handle the exception if parsing fails

StyleConstants.setFontSize(attributes, fontSize);

if (boldCheckBox.isSelected()) {

fontStyle |= Font.BOLD;

if (italicCheckBox.isSelected()) {

fontStyle |= Font.ITALIC;

StyleConstants.setBold(attributes, (fontStyle & Font.BOLD) != 0);

StyleConstants.setItalic(attributes, (fontStyle & Font.ITALIC) != 0);


if (underlineCheckBox.isSelected()) {

StyleConstants.setUnderline(attributes, true);

doc.setParagraphAttributes(0, doc.getLength(), attributes, false);

String hobbies = "Hobbies: ";

if (musicCheckBox.isSelected()) {

hobbies += "Music, ";

if (sportCheckBox.isSelected()) {

hobbies += "Sport, ";

if (travellingCheckBox.isSelected()) {

hobbies += "Travelling";

doc.setParagraphAttributes(0, doc.getLength(), attributes, false);

resultTextPane.setText("Name: " + name + "\nClass: " + selectedClass + "\n" + hobbies);

public static void main(String[] args) {

GUI g= new GUI();

You might also like