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

Java 4 Marks SOlution

The document covers various Java programming concepts, including exception handling, thread priorities, the Runnable interface, and GUI components like TextField and JTabbedPane. It provides code examples for using the throw keyword, setting thread priorities, implementing the Runnable interface, and creating panels and layouts in Java AWT and Swing. Additionally, it discusses event handling for item events and window events in Java applications.

Uploaded by

atharvanichat7
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)
4 views

Java 4 Marks SOlution

The document covers various Java programming concepts, including exception handling, thread priorities, the Runnable interface, and GUI components like TextField and JTabbedPane. It provides code examples for using the throw keyword, setting thread priorities, implementing the Runnable interface, and creating panels and layouts in Java AWT and Swing. Additionally, it discusses event handling for item events and window events in Java applications.

Uploaded by

atharvanichat7
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/ 25

Q.

Exception: An event that disrupts the normal flow of a program.

Exception handling in Java is a powerful mechanism to handle runtime errors, maintaining the
normal flow of the application.
Q.6
Q.7

The throw keyword in Java is used to explicitly throw an exception from


within a method or block of code.

This allows a programmer to manually trigger an exception when certain


conditions are met

It is used to throw a specific exception at a particular point in your code.

Syntax: The syntax of using throw is:

throw new ExceptionType("Error message");

Example of throw in Action:

public class ThrowKeywordExample


{

public static void main(String[] args)


{
try
{
validateAge(15);
}
catch (IllegalArgumentException e)
{

System.out.println("Caught exception: " + e.getMessage());


}
}

public static void validateAge(int age)


{
if (age < 18)
{
throw new IllegalArgumentException("Age must be 18 or older.");
}
else
{
System.out.println("Age is valid.");
}
}}

Breakdown of the Example:

1. The validateAge method checks if the given age is less than 18.
2. If the condition is true (i.e., the age is less than 18), the method uses the
throw keyword to explicitly throw an IllegalArgumentException with a
custom error message.
3. The exception is caught in the catch block of the main method, where the
exception message is printed.

Q.8

Setting Thread Priorities in Java

Java provides the Thread class’s setPriority() method to set the priority
of a thread. The priority values range from Thread.MIN_PRIORITY (1)
to Thread.MAX_PRIORITY (10), with the default being
Thread.NORM_PRIORITY (5).

Thread Priority Values:

 Thread.MIN_PRIORITY: The minimum possible priority (1).


 Thread.NORM_PRIORITY: The default priority (5).
 Thread.MAX_PRIORITY: The maximum possible priority (10).

Class MyThread extends Thread

public void run()


{

System.out.println(Thread.currentThread().getPriority());

public class ThreadPriorityExample

public static void main(String[] args)

MyThread thread1 = new MyThread();

thread1.setPriority(Thread.MIN_PRIORITY);

MyThread thread2 = new MyThread();

thread2.setPriority(Thread.NORM_PRIORITY);

MyThread thread3 = new MyThread();

thread3.setPriority(Thread.MAX_PRIORITY);

thread1.start();

thread2.start();
thread3.start();

Q.9
The primary purpose of the Runnable interface is to define the task that is executed by a
thread. You implement the Runnable interface when you want to run a piece of code in a
separate thread.

The Runnable interface has a single method:

void run();

o The run() method contains the code you want the thread to execute.
o The method doesn't return anything and doesn't throw any checked exceptions.

Once you implement the Runnable interface, you can pass it to a Thread object, which
will execute the run() method in a new thread.

Example of Using Runnable Interface


public class RunnableExample
{
public static void main(String[] args)
{
// Create a Runnable task
Runnable task = new MyRunnable();

// Create a new thread and pass the Runnable task


Thread thread = new Thread(task);

// Start the thread


thread.start();
}
}

class MyRunnable implements Runnable


{

public void run()


{
// Code that will be executed in a separate thread
System.out.println("Hello from a separate thread!");
}
}

Explanation:

1. Runnable Implementation: The class MyRunnable implements the Runnable interface


and provides the implementation of the run() method, where the task is defined.
2. Thread Creation: In the main method, we create a new Thread object and pass an
instance of MyRunnable to it.
3. Starting the Thread: The start() method is called on the Thread object. This triggers
the execution of the run() method of the Runnable in a new thread.

Q.10
Q.11
Q.13

In Java AWT (Abstract Window Toolkit), the TextField class is a single-line text
input field where users can enter text.

Key Methods of TextField

Constructors

TextField()
This constructor creates an empty TextField object with no initial text.

TextField textField = new TextField();

TextField(String text)

This constructor creates a TextField with the specified initial text.

TextField textField = new TextField("Default text");

Methods

1. setText(String text)
This method sets the text content of the TextField. It replaces any existing
text with the new one.

textField.setText("Hello, World!");

2. getText()
This method retrieves the current text from the TextField.

String currentText = textField.getText();


System.out.println(currentText); // Prints the text in the TextField

3. setColumns(int columns)
This method sets the number of columns (width) of the TextField. The
number of columns defines how wide the field is.

textField.setColumns(20); // Sets the width of the text field to 20 columns


4. getColumns()
This method returns the number of columns (width) of the TextField.

int columns = textField.getColumns();


System.out.println(columns); // Prints the width of the TextField in columns

5. setEditable(boolean editable)

This method enables or disables editing in the TextField. If set to false, the
user cannot change the text.

textField.setEditable(false); // Makes the text field non-editable

6. setEchoChar(char echoChar):

This method sets the character to be displayed in place of the actual


characters entered by the user (useful for password fields).

textField.setEchoChar('*'); // For password fields, displays '*' instead of


actual characters

7. getEchoChar()
This method returns the character that is used as the echo character when
typing in the TextField.

char echoChar = textField.getEchoChar();


System.out.println(echoChar); // Prints the echo character, e.g., '*'

Q.14

 A Panel is a container used to organize and group components within a


container like a Frame or Dialog.
 It is often used to create complex layouts by placing different components
inside a Panel.
 By using panel we can add various components like buttons, labels, text
fields, etc., to a Panel and then add the Panel to a Frame.
Steps to Create and Use a Panel in Java

1. Create a Panel: You can create a Panel object either by using the default
constructor or by specifying a layout manager.
2. Add Components to the Panel: After creating the Panel, you can add
various components like buttons, text fields, labels, etc., to it.
3. Add the Panel to a Frame: Finally, the Panel is added to a Frame or other
containers.

Example of Creating and Using a Panel in Java

Here’s a simple example to demonstrate how to create and use a Panel in Java:

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

public class PanelExample


{
public static void main(String[] args)
{
Frame frame = new Frame("Panel Example");
Panel panel = new Panel();
panel.setLayout(new FlowLayout());

Button button1 = new Button("Button 1");


Button button2 = new Button("Button 2");
TextField textField = new TextField("Enter text");

panel.add(button1);
panel.add(button2);
panel.add(textField);

frame.add(panel, BorderLayout.CENTER);

frame.setSize(400, 200);
frame.setVisible(true);
}
}
Q.15

 In Java, BorderLayout is a layout manager used for arranging components in


five distinct areas: North, South, East, West, and Center. It is one of the
most commonly used layout managers in Java Swing.
 To use BorderLayout, you typically set it as the layout manager for a
container like a JPanel or JFrame.
 The BorderLayout provides five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:

o BorderLayout(): creates a border layout but with no gaps between the


components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.

 Following program shows the demonstration of BorderLayout in java

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

public class BorderLayoutExample


{
public static void main(String[] args)
{
JFrame frame = new JFrame("BorderLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);

frame.setLayout(new BorderLayout());
frame.add(new JButton("North Button"), BorderLayout.NORTH);
frame.add(new JButton("South Button"), BorderLayout.SOUTH);
frame.add(new JButton("East Button"), BorderLayout.EAST);
frame.add(new JButton("West Button"), BorderLayout.WEST);
frame.add(new JButton("Center Button"), BorderLayout.CENTER);

frame.setVisible(true);
}
}

Explanation:

 frame.setLayout(new BorderLayout()): This sets the layout manager to


BorderLayout for the JFrame.
 frame.add(new JButton("North Button"), BorderLayout.NORTH): Adds a
button to the North area.
 Similarly, components can be added to South, East, West, and Center
using their respective constants.

Q.18
Q.19

To create a JTabbedPane in Java Swing, follow these steps:

1. Import Necessary Packages: Ensure you import the Swing components and
layout managers you'll use.

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

2. Create the JFrame: Initialize a JFrame to serve as the main window for
your application.

JFrame frame = new JFrame("Tabbed Pane Example");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);

3. Initialize the JTabbedPane: Create an instance of JTabbedPane, which will


manage the tabs.

JTabbedPane tabbedPane = new JTabbedPane();


4. Create Panels for Each Tab: Define the content for each tab by creating
JPanel objects and adding components to them.

JPanel panel1 = new JPanel();


panel1.add(new JLabel("Content for Tab 1"));

JPanel panel2 = new JPanel();


panel2.add(new JLabel("Content for Tab 2"));

JPanel panel3 = new JPanel();


panel3.add(new JLabel("Content for Tab 3"));

5. Add Tabs to the JTabbedPane: Add each panel to the JTabbedPane with a
title (and optionally, an icon).

tabbedPane.addTab("Tab 1", panel1);


tabbedPane.addTab("Tab 2", panel2);
tabbedPane.addTab("Tab 3", panel3);

6. Add the JTabbedPane to the JFrame: Set the layout of the frame and add
the JTabbedPane to it.

frame.setLayout(new BorderLayout());
frame.add(tabbedPane, BorderLayout.CENTER);

7. Display the JFrame: Make the frame visible.

frame.setVisible(true);

Complete Example:

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

public class TabbedPaneExample


{
public static void main(String[] args)
{
JFrame frame = new JFrame("Tabbed Pane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
JTabbedPane tabbedPane = new JTabbedPane();

JPanel panel1 = new JPanel();


panel1.add(new JLabel("Content for Tab 1"));

JPanel panel2 = new JPanel();


panel2.add(new JLabel("Content for Tab 2"));

JPanel panel3 = new JPanel();


panel3.add(new JLabel("Content for Tab 3"));

tabbedPane.addTab("Tab 1", panel1);


tabbedPane.addTab("Tab 2", panel2);
tabbedPane.addTab("Tab 3", panel3);

frame.setLayout(new BorderLayout());
frame.add(tabbedPane, BorderLayout.CENTER);

frame.setVisible(true);
}
}

Q.23

In Java, the ItemListener interface is part of the java.awt.event package and is used to
handle item events, which occur when the state of an item—such as a checkbox, radio button, or
item in a list—changes.

Implementing this interface allows developers to respond to user interactions with these
components.

ItemListener is designed to handle events related to the selection or deselection of items in


components that implement the ItemSelectable interface, including checkboxes, radio buttons,
combo boxes, and lists.

The interface defines a single method:

void itemStateChanged(ItemEvent e);

This method is invoked whenever the state of an item changes. The ItemEvent parameter
provides information about the event, such as the source component and the state change.
Demo Program

import javax.swing.*;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.*;

public class ItemListenerExample


{
public static void main(String[] args)
{
JFrame frame = new JFrame("ItemListener Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLayout(new FlowLayout());

JCheckBox checkBox = new JCheckBox("Enable Feature");


JLabel label = new JLabel("Feature is disabled");

checkBox.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
if (e.getStateChange() == ItemEvent.SELECTED)
{
label.setText("Feature is enabled");
}
else
{
label.setText("Feature is disabled");
}
}
});

frame.add(checkBox);
frame.add(label);
frame.setVisible(true);
}
}
Q.24

The WindowEvent class represents low-level events that indicate changes in the
status of a window.

These events are generated by window objects (such as Frame, Dialog, or


Window) in response to user interactions or system actions, including opening,
closing, activating, deactivating, minimizing, or restoring a window

WindowEvent defines several constants representing different types of window


events. Some of the primary event types include:

o WINDOW_OPENED: Triggered when a window is first opened or


made visible.
o WINDOW_CLOSING: Invoked when the user attempts to close the
window
o WINDOW_CLOSED: Fired after the window has been closed.
o WINDOW_ICONIFIED: Occurs when the window is minimized
(iconified).
o WINDOW_DEICONIFIED: Triggered when the window is restored
from a minimized state.
o WINDOW_ACTIVATED: Sent when the window becomes the
active window, receiving user input.
o WINDOW_DEACTIVATED: Occurs when the window loses focus
and becomes inactive.

Event Handling: To handle window events, classes can implement the


WindowListener interface, which provides methods corresponding to each of the
event types mentioned above.

/* Demo Program */

import javax.swing.*;

import java.awt.*;

import java.awt.event.WindowEvent;

import java.awt.event.WindowListener;

public class WindowEventsDemo


{

public static void main(String[] args)

JFrame frame = new JFrame("All Window Events Example");

frame.setSize(400, 300);

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

frame.addWindowListener(new WindowListener()

public void windowOpened(WindowEvent e)

System.out.println("Window Opened");

public void windowClosing(WindowEvent e)

System.out.println("Window Closing");

frame.dispose();

public void windowClosed(WindowEvent e)

{
System.out.println("Window Closed");

public void windowIconified(WindowEvent e)

System.out.println("Window Minimized");

public void windowDeiconified(WindowEvent e)

System.out.println("Window Restored");

public void windowActivated(WindowEvent e)

System.out.println("Window Activated");

public void windowDeactivated(WindowEvent e)

{
System.out.println("Window Deactivated");

});

frame.setVisible(true);

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy