0% found this document useful (0 votes)
7 views

chp 4 and 5 java assignment

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

chp 4 and 5 java assignment

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

-----------------------------chp 4------------------------

1.Give difference between throw and throws.


throw:
• It is used to explicitly throw an exception in the method
body.
• Syntax: throw new ExceptionType("Message");
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or
older.");
}

• It is used in the method signature to declare that a

• It doesn't throw an exception directly but indicates


that the method might generate a specific type of


2.What are user-defined exceptions? Illustrate them with an example.
User-defined exceptions are custom exceptions that the programmer
creates to handle specific errors in their application. These exceptions
are typically subclasses of Exception or RuntimeException.
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}

public class Main {


public static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be at least 18.");
}
}

public static void main(String[] args) {


try {
validateAge(15);
} catch (InvalidAgeException e) {
System.out.println(e.getMessage());
}
}
}
3.What is stream? Explain the types of streams supported by java.
A stream in Java represents an input or output source, such as a file or
memory buffer, through which data is read or written. Streams provide
an abstraction for reading and writing data in a linear fashion.
Types of Streams:
1. Byte Stream: These handle input and output of 8-bit data, like raw
binary data.
o InputStream and OutputStream are the parent classes for
byte streams.
o Example classes: FileInputStream, FileOutputStream.
2. Character Stream: These handle input and output of 16-bit
Unicode characters.
o Reader and Writer are the parent classes for character
streams.
o Example classes: FileReader, FileWriter

4.Explain different types of streams.


Byte Streams:
• For handling binary data.
• Classes: FileInputStream, FileOutputStream, BufferedInputStream,
BufferedOutputStream, DataInputStream, DataOutputStream.
Character Streams:
• For handling text data.
• Classes: FileReader, FileWriter, BufferedReader, BufferedWriter,
PrintWriter

5.What is checked and unchecked exceptions?


Checked Exceptions:
• These are exceptions that are checked at compile-time.
• Example: IOException, SQLException.
• These exceptions must either be caught using try-catch blocks or
declared using throws in the method signature.
Unchecked Exceptions:
• These are exceptions that are checked at runtime.
• Example: NullPointerException,
ArrayIndexOutOfBoundsException.
• These exceptions do not need to be declared or caught explicitly.

6.List any two methods of File class.


exists(): Checks if the file or directory exists.
File file = new File("example.txt");
System.out.println(file.exists()); // returns true or false
length(): Returns the size of the file in bytes.
File file = new File("example.txt");
System.out.println(file.length()); // returns size in bytes
7.Write a Java program to accept a file name from command prompt.If
the file exists, then display number of words and lines in that file using
FileReader class.
import java.io.*;

public class WordCount {


public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide a file name.");
return;
}

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


if (!file.exists()) {
System.out.println("File not found.");
return;
}

try (BufferedReader br = new BufferedReader(new FileReader(file)))


{
String line;
int lineCount = 0;
int wordCount = 0;
while ((line = br.readLine()) != null) {
lineCount++;
String[] words = line.split("\\s+");
wordCount += words.length;
}

System.out.println("Lines: " + lineCount);


System.out.println("Words: " + wordCount);
} catch (IOException e) {
System.out.println("Error reading file.");
}
}
}
8.Write a Java program to get file name from command prompt.Check
whether a file by given name exists.If file is a regular file, then display
various details about that file.But if it is a directory, then display
number of files in that directory.
import java.io.*;

public class FileDetails {


public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide a file name.");
return;
}

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


if (file.exists()) {
if (file.isFile()) {
System.out.println("File Name: " + file.getName());
System.out.println("Absolute Path: " + file.getAbsolutePath());
System.out.println("File Size: " + file.length() + " bytes");
System.out.println("Last Modified: " + new
java.util.Date(file.lastModified()));
} else if (file.isDirectory()) {
String[] files = file.list();
System.out.println("Directory contains " + files.length + "
files.");
}
} else {
System.out.println("File not found.");
}
}
}
9.Write a Java program to copy a file to another file.Use proper error
handler to handle runtiae exception.File names are accepted as
argument from command prompt.
import java.io.*;

public class FileCopy {


public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Please provide source and destination file
names.");
return;
}

try (FileInputStream fis = new FileInputStream(args[0]);


FileOutputStream fos = new FileOutputStream(args[1])) {

int byteData;
while ((byteData = fis.read()) != -1) {
fos.write(byteData);
}
System.out.println("File copied successfully.");
} catch (IOException e) {
System.out.println("Error during file copy: " + e.getMessage());
}
}
}
10.Write a java program to delete all the files from the current directory
having extension as .doc also display the count number of doc files
deleted separately.
import java.io.*;

public class DeleteDocFiles {


public static void main(String[] args) {
File dir = new File(".");
File[] files = dir.listFiles((d, name) -> name.endsWith(".doc"));
int count = 0;

if (files != null) {
for (File file : files) {
if (file.delete()) {
count++;
System.out.println("Deleted: " + file.getName());
}
}
}
System.out.println("Deleted " + count + " .doc files.");
}
}
11.Write a java program which stores the username and password in
two variables.If username and password are not same, then raise
"Invalid password" with appropriate message.
import java.util.Scanner;

public class Login {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

String username = "admin";


String password = "password123";

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


String inputUsername = sc.nextLine();
System.out.print("Enter password: ");
String inputPassword = sc.nextLine();

if (!username.equals(inputUsername) ||
!password.equals(inputPassword)) {
System.out.println("Invalid password.");
} else {
System.out.println("Login successful.");
}
}
}
12.Write a Java program which displays the contents of file in reverse
order.
import java.io.*;

public class ReverseFileContent {


public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide a file name.");
return;
}

try (BufferedReader br = new BufferedReader(new


FileReader(args[0]))) {
String line;
StringBuilder content = new StringBuilder();

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


content.insert(0, line + "\n");
}

System.out.println(content);
} catch (IOException e) {
System.out.println("Error reading file.");
}
}
}
13.Write a Java program to appends the content of one file to another.
import java.io.*;

public class FileAppend {


public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Please provide source and destination file
names.");
return;
}

try (BufferedReader br = new BufferedReader(new


FileReader(args[0]));
BufferedWriter bw = new BufferedWriter(new FileWriter(args[1],
true))) {
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}

System.out.println("Content appended successfully.");


} catch (IOException e) {
System.out.println("Error during file append: " + e.getMessage());
}
}
}
14.Write a java program to accept the details of product as
productcode, productname and weight.If weight 103 then throw an
exception as Invalid Product Exception and give the proper
message.Otherwise display the product details Define required
exception class.
import java.util.Scanner;

// Define custom exception


class InvalidProductException extends Exception {
public InvalidProductException(String message) {
super(message);
}
}

public class Product {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Accept product details


System.out.print("Enter Product Code: ");
String productCode = scanner.nextLine();

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


String productName = scanner.nextLine();

System.out.print("Enter Product Weight: ");


double weight = scanner.nextDouble();

// Check weight and throw exception if it is 103


try {
if (weight == 103) {
throw new InvalidProductException("Invalid Product: Weight
cannot be 103.");
}

// Display product details


System.out.println("\nProduct Details:");
System.out.println("Product Code: " + productCode);
System.out.println("Product Name: " + productName);
System.out.println("Product Weight: " + weight);

} catch (InvalidProductException e) {
System.out.println(e.getMessage());
} finally {
scanner.close();
}
}
}
15.What is the use of finally keyword?
What is the use of the finally keyword?
The finally block is used to execute important code, such as closing
resources or cleaning up, regardless of whether an exception is thrown
or not. It is always executed after the try block, and even if an exception
is caught or thrown, the finally block will execute.
Key points about finally:
• It ensures that the code inside it is executed no matter what.
• It's typically used to release resources, close files, or handle
cleanup operations.
• If there is a return statement in the try or catch block, the finally
block will still be executed before the method returns.
public class FinallyExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // Throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("This will always execute, even if there is an
exception.");
}
}
}
16.List and describe any five methods of InputStream class along with
their syntax.
The InputStream class is the superclass for all byte input streams in
Java. It provides basic methods for reading byte data.
Here are five important methods of InputStream:
1. int read():
o Reads the next byte of data from the input stream.
o Returns the byte read as an integer (0 to 255), or -1 if the
end of the stream is reached.
int byteData = inputStream.read();
int read(byte[] b):
• Reads up to b.length bytes of data into an array b.
• Returns the number of bytes read, or -1 if the end of the stream is
reached.
int bytesRead = inputStream.read(byteArray);
int read(byte[] b, int off, int len):
• Reads up to len bytes of data into a portion of an array b starting
at the off position.
• Returns the number of bytes read, or -1 if the end of the stream is
reached.
int bytesRead = inputStream.read(byteArray, 0, 1024);
long skip(long n):
• Skips over n bytes of data from the input stream.
• Returns the number of bytes actually skipped (this could be less
than n if the end of the stream is reached).
long skippedBytes = inputStream.skip(100);
void close():
• Closes the input stream and releases any system resources
associated with it.
• It is a good practice to close the stream after using it to avoid
memory leaks.
inputStream.close();
import java.io.*;

public class InputStreamExample {


public static void main(String[] args) {
try (InputStream inputStream = new
FileInputStream("example.txt")) {
byte[] buffer = new byte[1024];
int bytesRead;

// Reading data using read() method


while ((bytesRead = inputStream.read(buffer)) != -1) {
System.out.write(buffer, 0, bytesRead); // Write data to
console
}

// Skipping some bytes


inputStream.skip(5); // Skips 5 bytes

} catch (IOException e) {
e.printStackTrace();
}
}
}
--------------Chp5-----------------------------------------------------
1.Define AWT and swing.
AWT (Abstract Window Toolkit):
• AWT is a set of application programming interfaces (APIs) used for
creating graphical user interfaces (GUIs) in Java.
• It provides a collection of classes for creating windows, buttons,
text fields, etc.
• AWT components are platform-dependent, meaning they rely on
the underlying operating system's GUI.
Swing:
• Swing is a part of Java's javax.swing package and is an extension
of AWT.
• Swing provides a rich set of GUI components like buttons,
checkboxes, labels, tables, trees, etc., but unlike AWT, Swing
components are lightweight and are platform-independent.
• Swing components do not rely on native OS components for
rendering, making them more consistent across different
platforms.

2.Define anonymous class.


An anonymous class is a class without a name and is used to instantiate
an object with a class definition. It is typically used when you need to
implement a class or interface for a short period and do not need to
refer to it elsewhere.
Button button = new Button("Click me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked");
}
});
3.List constructors of JTextArea class (any two).
JTextArea is a Swing component that allows the user to enter and edit
multi-line text.
1. JTextArea():
o Creates an empty JTextArea with default settings (no text, 0
rows, 0 columns).
JTextArea textArea = new JTextArea();
JTextArea(String text):
• Creates a JTextArea initialized with the specified text.
JTextArea textArea = new JTextArea("Initial text");
4.Explain JOptionPane class with their static methods.
JOptionPane is a Swing class that provides methods for pop-up dialog
boxes such as message boxes, input dialogs, confirmation dialogs, etc.
Common Static Methods:
1. showMessageDialog(Component parentComponent, Object
message):
o Displays a message in a dialog box.
JOptionPane.showMessageDialog(null, "Hello, World!");
showConfirmDialog(Component parentComponent, Object message):
• Displays a confirmation dialog with options like "Yes", "No", and
"Cancel".
int option = JOptionPane.showConfirmDialog(null, "Do you want to
continue?");
showInputDialog(Component parentComponent, Object message):
• Displays an input dialog to ask for user input.
String name = JOptionPane.showInputDialog("Enter your name:");
5.Design a screen in Java using AWT to handle the mouse events and
display the positions of mouse click in textbox.
import java.awt.*;
import java.awt.event.*;

public class MousePositionFrame extends Frame {


TextField textField;

public MousePositionFrame() {
// Set up frame
setSize(400, 300);
setLayout(null);

// Create a text field


textField = new TextField();
textField.setBounds(50, 50, 300, 30);
add(textField);

// Mouse click event handler


addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// Get mouse click coordinates and display in text field
String position = "X: " + e.getX() + " Y: " + e.getY();
textField.setText(position);
}
});

// Set frame visible


setVisible(true);
}

public static void main(String[] args) {


new MousePositionFrame();
}
}
6.List any four methods of JButton class.
addActionListener(ActionListener l):
• Adds an action listener to the button.
setText(String text):

• Sets the text displayed on the button.


• button.setText("Click Me");
setEnabled(boolean b):

• Enables or disables the button.


• button.setEnabled(false); // Disable the button
setIcon(Icon icon):

• Sets an icon (image) on the button


• button.setIcon(new ImageIcon("icon.png"));

7.Explain JComboBox class with their constructor and methods.


JComboBox is a Swing component that allows the user to select an item
from a drop-down list.
JComboBox():
• Creates a combo box with no items.
JComboBox comboBox = new JComboBox();
addItem(Object item):
• Adds an item to the combo box.
comboBox.addItem("New Option");
getSelectedItem():
• Returns the currently selected item.
Object selectedItem = comboBox.getSelectedItem();
setSelectedIndex(int index):
• Sets the selected item by index.
comboBox.setSelectedIndex(1); // Selects the second item
removeItem(Object item):
• Removes a specific item from the combo box.
comboBox.removeItem("Option 2");
8.What is an adapter class? What is the use of adapter class?
An adapter class in Java is a class that provides default implementations
for all methods of an interface. It allows you to override only the
methods you need, rather than implementing every method of the
interface.
Use of Adapter Class:
• It is primarily used to simplify the handling of events, especially
when you are only interested in handling some of the methods of
an interface.
• It reduces the need for writing empty method implementations.
MouseAdapter mouseAdapter = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked!");
}
};
9.Give two types of Dialogs.
Message Dialog: Displays a message to the user. It can have buttons
like "OK" or "Cancel".
• Example: JOptionPane.showMessageDialog(null, "Message");
Input Dialog: Prompts the user for input, such as text input.
• Example: JOptionPane.showInputDialog("Enter your name:");

10.Explain in brier the event handling mechanism in Java with the help
of suitable example.
Event handling in Java is the process of responding to user actions like
clicks, key presses, mouse movements, etc. It involves the following
steps:
1. Event Source: The object that generates an event (e.g., a button).
2. Event Listener: An object that listens to the event and responds to
it (e.g., ActionListener).
3. Event: The actual event object that holds information about the
action.
import java.awt.*;
import java.awt.event.*;

public class ButtonClickExample {


public static void main(String[] args) {
Frame frame = new Frame("Event Handling Example");
Button button = new Button("Click Me");

button.setBounds(100, 100, 100, 50);


frame.add(button);
frame.setSize(300, 300);
frame.setLayout(null);
frame.setVisible(true);

// Event listener for button click


button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});
}
}
11.What are the features of Swing?
Swing is a part of Java's standard library for building graphical user
interfaces (GUIs). It is part of the javax.swing package and provides
several advanced features compared to AWT. Some key features of
Swing are:
1. Lightweight Components: Swing components are not tied to
native OS widgets, meaning they are rendered purely in Java. They
are therefore lighter in weight compared to AWT components.
2. Pluggable Look and Feel: Swing allows you to change the look and
feel of components. This means you can have the same
application appear with different visual themes, such as Windows,
Metal, or a custom theme.
3. Rich Set of Components: Swing provides a wide range of
components, including buttons, checkboxes, labels, text fields,
tables, trees, menus, and toolbars.
4. Double Buffering: Swing supports double buffering to prevent
flickering during UI updates, making the interface smoother.
5. Event Handling: Swing provides better event handling support and
allows for more complex event-driven behaviors.
6. Customizable: Swing components are highly customizable. You
can change their appearance, behavior, and functionality easily.
7. Java 2D API: Swing is integrated with the Java 2D API, which
allows for advanced graphics rendering, including the drawing of
shapes, images, and text.

12.Write a syntax of JFileChooser class.


he JFileChooser class is used to provide an easy way for users to select
files or directories. It can be used to open or save files in the system.
import javax.swing.*;
import java.io.*;
public class FileChooserExample {
public static void main(String[] args) {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(null); // Opens file dialog

if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: " +
selectedFile.getAbsolutePath());
}
}
}
13.Why Swing objects are called as light weight components?
Swing objects are called lightweight components because they are
drawn entirely in Java using a single-threaded painting mechanism.
Unlike AWT components, which rely on native operating system
components (and thus have more overhead), Swing components do not
rely on the OS for rendering, making them lighter. This allows them to
be more flexible and consistent across different platforms
14.State any four methods of WindowListener.
WindowListener is an interface that receives events from a window
(such as opening, closing, minimizing, etc.).
1. windowOpened(WindowEvent we): Invoked when the window is
first opened.
2. windowClosing(WindowEvent we): Invoked when the user
attempts to close the window.
3. windowClosed(WindowEvent we): Invoked when the window has
been closed.
4. windowIconified(WindowEvent we): Invoked when the window is
minimized.

15.How is menu created in Java? Explain with suitable example.


A menu in Java is created using JMenuBar, JMenu, and JMenuItem. The
menu is added to the frame using setJMenuBar().
import javax.swing.*;

public class MenuExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Menu Example");
JMenuBar menuBar = new JMenuBar();

JMenu fileMenu = new JMenu("File");


JMenuItem openItem = new JMenuItem("Open");
JMenuItem saveItem = new JMenuItem("Save");
fileMenu.add(openItem);
fileMenu.add(saveItem);
JMenu editMenu = new JMenu("Edit");
JMenuItem cutItem = new JMenuItem("Cut");
JMenuItem copyItem = new JMenuItem("Copy");
editMenu.add(cutItem);
editMenu.add(copyItem);

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

frame.setJMenuBar(menuBar);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
16.What is the use of Checkboxes and RadioButtons? Explain with
suitable example.
Checkboxes allow the user to select multiple options from a set.
Radio buttons allow the user to select only one option from a group
of choices.
import javax.swing.*;
import java.awt.*;

public class CheckBoxRadioButtonExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Checkbox and RadioButton
Example");

// Checkbox
JCheckBox checkbox = new JCheckBox("I agree to the terms and
conditions");

// RadioButton
JRadioButton radioButton1 = new JRadioButton("Option 1");
JRadioButton radioButton2 = new JRadioButton("Option 2");

ButtonGroup group = new ButtonGroup();


group.add(radioButton1);
group.add(radioButton2);

frame.setLayout(new FlowLayout());
frame.add(checkbox);
frame.add(radioButton1);
frame.add(radioButton2);

frame.setSize(300, 200);
frame.setVisible(true);
}
}
17.Explain layout managers used in AWT.
Layout Managers in AWT help to arrange the components in a container
in a structured manner. Some of the common layout managers are:
1. FlowLayout: Components are placed one after another in a single
line, and they move to the next line if the current line is full.
2. BorderLayout: Divides the container into five regions: North,
South, East, West, and Center.
3. GridLayout: Arranges components in a grid with specified rows
and columns.
4. CardLayout: Allows components to be stacked on top of each
other, showing one at a time.
5. GridBagLayout: Provides a flexible grid system for positioning
components based on their grid position and weights.

18.What are the different types of dialogs in Java? Write any one in
detail.
Dialog boxes in Java can be used to interact with the user and collect
input or display information. Common types of dialogs include:
1. Message Dialog: A simple dialog that displays information.
2. Input Dialog: A dialog where the user can input data.
3. Confirm Dialog: A dialog that asks the user to confirm an action.
4. Custom Dialog: A dialog with customized components.
import javax.swing.*;

public class MessageDialogExample {


public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "This is a message dialog");
}
}
19.Which Swing classes are used to create menu?
JMenuBar: A container for the menu.
JMenu: Represents an individual menu.
JMenuItem: Represents an item in a menu.
JCheckBoxMenuItem: Represents a menu item with a checkbox.
JRadioButtonMenuItem: Represents a menu item with a radio
button.
20.Write a Java program to set background colour of dialog box using
JColorChooser.
import javax.swing.*;
import java.awt.*;

public class ColorChooserExample {


public static void main(String[] args) {
// Create a frame and a button
JFrame frame = new JFrame("Color Chooser Example");
JButton button = new JButton("Choose Background Color");

button.addActionListener(e -> {
// Use JColorChooser to get a color
Color color = JColorChooser.showDialog(frame, "Choose a Color",
Color.WHITE);
if (color != null) {
frame.getContentPane().setBackground(color); // Set
background color
}
});

frame.setLayout(new FlowLayout());
frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
21.Write a program in Java to create a screen which contains three
checkboxes (net, php, java) and displays the selected items in a textbox.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class CheckboxSelection {


public static void main(String[] args) {
JFrame frame = new JFrame("Checkbox Selection");
JCheckBox netCheckBox = new JCheckBox("Net");
JCheckBox phpCheckBox = new JCheckBox("PHP");
JCheckBox javaCheckBox = new JCheckBox("Java");
JTextField textField = new JTextField(20);

// Add action listeners to checkboxes


netCheckBox.addItemListener(e -> updateSelection(textField,
netCheckBox, phpCheckBox, javaCheckBox));
phpCheckBox.addItemListener(e -> updateSelection(textField,
netCheckBox, phpCheckBox, javaCheckBox));
javaCheckBox.addItemListener(e -> updateSelection(textField,
netCheckBox, phpCheckBox, javaCheckBox));

frame.setLayout(new FlowLayout());
frame.add(netCheckBox);
frame.add(phpCheckBox);
frame.add(javaCheckBox);
frame.add(textField);
frame.setSize(300, 200);
frame.setVisible(true);
}

// Update text field with selected items


private static void updateSelection(JTextField textField, JCheckBox
netCheckBox, JCheckBox phpCheckBox, JCheckBox javaCheckBox) {
StringBuilder selectedItems = new StringBuilder();
if (netCheckBox.isSelected()) selectedItems.append("Net ");
if (phpCheckBox.isSelected()) selectedItems.append("PHP ");
if (javaCheckBox.isSelected()) selectedItems.append("Java ");
textField.setText(selectedItems.toString());
}
}
22.Write a Java program using AWT to print "Welcome to T.Y B.Sc
Computer Science" with Times New Roman font face and size is 16 in
Red Color When we click on a button text color should change to Blue.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class CheckboxSelection {


public static void main(String[] args) {
JFrame frame = new JFrame("Checkbox Selection");
JCheckBox netCheckBox = new JCheckBox("Net");
JCheckBox phpCheckBox = new JCheckBox("PHP");
JCheckBox javaCheckBox = new JCheckBox("Java");
JTextField textField = new JTextField(20);

// Add action listeners to checkboxes


netCheckBox.addItemListener(e -> updateSelection(textField,
netCheckBox, phpCheckBox, javaCheckBox));
phpCheckBox.addItemListener(e -> updateSelection(textField,
netCheckBox, phpCheckBox, javaCheckBox));
javaCheckBox.addItemListener(e -> updateSelection(textField,
netCheckBox, phpCheckBox, javaCheckBox));

frame.setLayout(new FlowLayout());
frame.add(netCheckBox);
frame.add(phpCheckBox);
frame.add(javaCheckBox);
frame.add(textField);

frame.setSize(300, 200);
frame.setVisible(true);
}

// Update text field with selected items


private static void updateSelection(JTextField textField, JCheckBox
netCheckBox, JCheckBox phpCheckBox, JCheckBox javaCheckBox) {
StringBuilder selectedItems = new StringBuilder();
if (netCheckBox.isSelected()) selectedItems.append("Net ");
if (phpCheckBox.isSelected()) selectedItems.append("PHP ");
if (javaCheckBox.isSelected()) selectedItems.append("Java ");
textField.setText(selectedItems.toString());
}
}

23.Write a java program which will create a frame if we try to close it.It
should change it's color Red and it display closing message on the
screen (Use swing)
import java.awt.*;
import java.awt.event.*;

public class FontColorChange {


public static void main(String[] args) {
Frame frame = new Frame("Font and Color Change");
Button button = new Button("Change Color");
Label label = new Label("Welcome to T.Y B.Sc Computer Science");

// Set font and color for label


label.setFont(new Font("Times New Roman", Font.PLAIN, 16));
label.setForeground(Color.RED);

// ActionListener to change text color when button is clicked


button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setForeground(Color.BLUE); // Change color to Blue
}
});

frame.setLayout(new FlowLayout());
frame.add(label);
frame.add(button);
frame.setSize(400, 200);
frame.setVisible(true);
}
}

You might also like