UNIT – V
Part A Assignment Questions:
Define Generic program with example
Give the Restrictions and Limitations in generic program.
What is a bounded type parameter in Java Generics?
Compare between adapter class and listener interface
Sketch the steps needed to show a Frame.
Show what method can be used for changing font of
Characters?
What is event handling? Give its three components.
Compare the JavaAWT and JavaSwing
Write a java code for Button creation
How to create a menu in frame?
Part B Assignment Questions and Answer
1. code to simulates a traffic light
import java.util.Timer;
import java.util.TimerTask;
public class TrafficLightSimulator {
private enum LightColor {
RED, GREEN, YELLOW
}
private LightColor currentColor;
private Timer timer;
public TrafficLightSimulator() {
currentColor = LightColor.RED; // Start with Red light
timer = new Timer();
startTrafficLight();
}
private void startTrafficLight() {
timer.schedule(new TimerTask() {
public void run() {
switch (currentColor) {
case RED:
currentColor = LightColor.GREEN;
System.out.println("Green light is ON");
break;
case GREEN:
currentColor = LightColor.YELLOW;
System.out.println("Yellow light is ON");
break;
case YELLOW:
currentColor = LightColor.RED;
System.out.println("Red light is ON");
break;
}
adjustTiming();
}
}, 0, 3000); // Change light every 3 seconds
}
private void adjustTiming() {
// Adjust the timing based on the current color
switch (currentColor) {
case RED:
timer.schedule(new TimerTask() {
public void run() {
currentColor = LightColor.GREEN;
}
}, 3000); // Red for 3 seconds
break;
case GREEN:
timer.schedule(new TimerTask() {
public void run() {
currentColor = LightColor.YELLOW;
}
}, 5000); // Green for 5 seconds
break;a
case YELLOW:
timer.schedule(new TimerTask() {
public void run() {
currentColor = LightColor.RED;
}
}, 2000); // Yellow for 2 seconds
break;
}
}
public static void main(String[] args) {
new TrafficLightSimulator();
}
}
2. a simple calculator using mouse events that restrict
only addition, subtraction, multiplication and
division.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class SimpleCalculator extends JFrame {
private JTextField display;
private StringBuilder input;
public SimpleCalculator() {
input = new StringBuilder();
display = new JTextField();
display.setEditable(false);
display.setFont(new Font("Arial", Font.PLAIN, 24));
JButton buttonAdd = createButton("+");
JButton buttonSubtract = createButton("-");
JButton buttonMultiply = createButton("*");
JButton buttonDivide = createButton("/");
JButton buttonEquals = createButton("=");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 5));
panel.add(buttonAdd);
panel.add(buttonSubtract);
panel.add(buttonMultiply);
panel.add(buttonDivide);
panel.add(buttonEquals);
this.setLayout(new BorderLayout());
this.add(display, BorderLayout.NORTH);
this.add(panel, BorderLayout.CENTER);
this.setTitle("Simple Calculator");
this.setSize(400, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
private JButton createButton(String label) {
JButton button = new JButton(label);
button.setFont(new Font("Arial", Font.PLAIN, 24));
button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
handleButtonClick(label);
}
});
return button;
}
private void handleButtonClick(String label) {
if ("=".equals(label)) {
try {
String result = evaluateExpression(input.toString());
display.setText(result);
input.setLength(0); // Clear input after evaluation
} catch (Exception e) {
display.setText("Error");
input.setLength(0); // Clear input on error
}
} else {
input.append(label);
display.setText(input.toString());
}
}
private String evaluateExpression(String expression) {
String[] tokens = expression.split("(?=[-+*/])|(?<=[-+*/])");
double result = Double.parseDouble(tokens[0]);
for (int i = 1; i < tokens.length; i += 2) {
String operator = tokens[i];
double nextValue = Double.parseDouble(tokens[i + 1]);
switch (operator) {
case "+":
result += nextValue;
break;
case "-":
result -= nextValue;
break;
case "*":
result *= nextValue;
break;
case "/":
if (nextValue != 0) {
result /= nextValue;
} else {
throw new ArithmeticException("Division by zero");
}
break;
}
}
return String.valueOf(result);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(SimpleCalculator::new);
}
}
3. Code for menu creation: a. Circle. (4) b.
Rectangle. (4) c. Line. (4) d. Diagonal for the
rectangle.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GeometricShapes extends JFrame {
private String shapeToDraw = "";
public GeometricShapes() {
setTitle("Geometric Shapes");
setSize(600, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JMenuBar menuBar = new JMenuBar();
JMenu shapesMenu = new JMenu("Shapes");
JMenuItem circleItem = new JMenuItem("Circle");
JMenuItem rectangleItem = new JMenuItem("Rectangle");
JMenuItem lineItem = new JMenuItem("Line");
JMenuItem diagonalItem = new JMenuItem("Diagonal");
circleItem.addActionListener(e -> {
shapeToDraw = "Circle";
repaint();
});
rectangleItem.addActionListener(e -> {
shapeToDraw = "Rectangle";
repaint();
});
lineItem.addActionListener(e -> {
shapeToDraw = "Line";
repaint();
});
diagonalItem.addActionListener(e -> {
shapeToDraw = "Diagonal";
repaint();
});
shapesMenu.add(circleItem);
shapesMenu.add(rectangleItem);
shapesMenu.add(lineItem);
shapesMenu.add(diagonalItem);
menuBar.add(shapesMenu);
setJMenuBar(menuBar);
}
protected void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics g2d = (Graphics2D) g;
switch (shapeToDraw) {
case "Circle":
g2d.drawOval(100, 100, 100, 100); // Circle at (100, 100) with a diameter of 100
break;
case "Rectangle":
g2d.drawRect(250, 100, 150, 100); // Rectangle at (250, 100)
break;
case "Line":
g2d.drawLine(100, 250, 400, 250); // Line from (100, 250) to (400, 250)
break;
case "Diagonal":
g2d.drawLine(250, 100, 400, 200); // Diagonal of the rectangle
break;
}
}
public void paint(Graphics g) {
super.paint(g);
paintComponent(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
GeometricShapes frame = new GeometricShapes();
frame.setVisible(true);
});
}
}
4. Program: layout manager with its types which is
available in Java Swing
import javax.swing.*;
import java.awt.*;
public class LayoutManagerExample extends JFrame {
public LayoutManagerExample() {
setTitle("Layout Manager Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Panel using FlowLayout
JPanel flowPanel = new JPanel(new FlowLayout());
flowPanel.add(new JButton("Button 1"));
flowPanel.add(new JButton("Button 2"));
flowPanel.add(new JButton("Button 3"));
// Panel using GridLayout
JPanel gridPanel = new JPanel(new GridLayout(2, 2));
gridPanel.add(new JButton("Button 4"));
gridPanel.add(new JButton("Button 5"));
gridPanel.add(new JButton("Button 6"));
gridPanel.add(new JButton("Button 7"));
// Panel using BoxLayout
JPanel boxPanel = new JPanel();
boxPanel.setLayout(new BoxLayout(boxPanel, BoxLayout.Y_AXIS));
boxPanel.add(new JButton("Button 8"));
boxPanel.add(new JButton("Button 9"));
boxPanel.add(new JButton("Button 10"));
// Adding panels to the main frame
add(flowPanel, BorderLayout.NORTH);
add(gridPanel, BorderLayout.CENTER);
add(boxPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
LayoutManagerExample frame = new LayoutManagerExample();
frame.setVisible(true);
});
}
}
5. program to display the An ellipse should be inside
a Rectangle. Colors also can be used.
import javax.swing.*;
import java.awt.*;
public class EllipseInRectangle extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Set background color
setBackground(Color.WHITE);
// Draw rectangle
g.setColor(Color.BLUE);
g.fillRect(50, 50, 300, 200); // (x, y, width, height)
// Draw ellipse
g.setColor(Color.RED);
g.fillOval(50, 50, 300, 200); // (x, y, width, height)
}
public static void main(String[] args) {
JFrame frame = new JFrame("Ellipse Inside Rectangle");
EllipseInRectangle panel = new EllipseInRectangle();
frame.add(panel);
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
6. in detail about working with 2D shapes in Java.
Working with 2D shapes in Java primarily involves using the Java 2D API, which is part of
the Abstract Window Toolkit (AWT) and is designed for advanced graphics capabilities.
Here’s an overview of the key concepts, classes, and methods you'll need to effectively work
with 2D shapes in Java.
1. Key Classes in Java 2D API
• Graphics: This is the base class for all graphics operations in Java. It provides
methods to draw shapes, text, and images.
• Graphics2D: This is a subclass of Graphics that provides more sophisticated control
over geometry, coordinate transformations, color management, and text layout. You
typically cast Graphics to Graphics2D for 2D drawing.
• Shape: An interface that represents a 2D geometric shape. Classes like Rectangle2D,
Ellipse2D, Line2D, and Polygon implement this interface.
• Color: Represents colors in the RGB color model. You can create custom colors using
the Color class.
• BasicStroke: Defines the style of the stroke used for drawing shapes, including width,
dash patterns, and caps.
2. Commonly Used Shapes
• Rectangle: Created using Rectangle2D.Double or Rectangle.
• Ellipse: Created using Ellipse2D.Double.
• Line: Created using Line2D.Double.
• Polygon: Created using Polygon.
3. Basic Drawing Operations
Setting Up a Drawing Environment
1. Create a JFrame: This is your main window.
2. Add a JPanel: Override the paintComponent method to perform custom drawing.
Example Code
Here’s a simple example that demonstrates how to draw various 2D shapes:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class ShapeExample extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// Set anti-aliasing for smoother shapes
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Draw a rectangle
g2d.setColor(Color.BLUE);
g2d.fill(new Rectangle2D.Double(50, 50, 200, 100));
// Draw an ellipse
g2d.setColor(Color.RED);
g2d.fill(new Ellipse2D.Double(100, 70, 150, 60));
// Draw a line
g2d.setColor(Color.GREEN);
g2d.setStroke(new BasicStroke(5)); // Set line width
g2d.draw(new Line2D.Double(50, 50, 250, 150));
// Draw a polygon (triangle)
g2d.setColor(Color.MAGENTA);
int[] xPoints = {300, 350, 250};
int[] yPoints = {150, 250, 250};
g2d.fill(new Polygon(xPoints, yPoints, xPoints.length));
}
public static void main(String[] args) {
JFrame frame = new JFrame("2D Shapes Example");
ShapeExample panel = new ShapeExample();
frame.add(panel);
frame.setSize(500, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
7. Event handling in Java
Event handling in Java is a crucial part of creating interactive applications, especially in
graphical user interfaces (GUIs). It involves responding to various user actions (events) such
as clicks, key presses, mouse movements, and more. Here’s a detailed breakdown of how
event handling works in Java:
1. Understanding Events
Events are objects that represent a specific action or occurrence in the program. In Java,
common types of events include:
• Action Events: Triggered by buttons, menu items, etc.
• Mouse Events: Triggered by mouse actions like clicks, movements, and dragging.
• Key Events: Triggered by keyboard actions (key presses, key releases).
• Window Events: Triggered by window-related actions (opening, closing, minimizing).
2. Event Sources
Event sources are components that generate events. Common event sources include:
• Buttons
• Text Fields
• Menus
• Panels
• Windows
3. Event Listeners
To handle events, you need to implement event listeners. A listener is an interface that
defines methods that must be overridden to respond to specific events. Each type of event has
a corresponding listener interface.
Common Listener Interfaces:
• ActionListener: For action events (e.g., button clicks).
o Method: void actionPerformed(ActionEvent e)
• MouseListener: For mouse events (e.g., mouse clicks).
o Methods: void mouseClicked(MouseEvent e), void mousePressed(MouseEvent e), void
mouseReleased(MouseEvent e), void mouseEntered(MouseEvent e), void
mouseExited(MouseEvent e)
• MouseMotionListener: For mouse motion events.
o Methods: void mouseDragged(MouseEvent e), void mouseMoved(MouseEvent e)
• KeyListener: For keyboard events.
o Methods: void keyPressed(KeyEvent e), void keyReleased(KeyEvent e), void
keyTyped(KeyEvent e)
4. Registering Listeners
Once you have implemented a listener, you need to register it with the event source so that it
can respond to events. This is typically done using the add<ListenerType> method of the
component.
5. Example of Event Handling
import javax.swing.*;
import java.awt.event.*;
public class EventHandlingExample extends JFrame {
public EventHandlingExample() {
JButton button = new JButton("Click Me!");
// Registering ActionListener
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Button was clicked!");
}
});
this.add(button);
this.setSize(300, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
new EventHandlingExample();
}
}
8. Implement a Java Program to display User
Authentication page using AWT/Swing.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class UserAuthentication extends JFrame {
private JTextField usernameField;
private JPasswordField passwordField;
public UserAuthentication() {
setTitle("User Authentication");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // Center the window
// Create components
JLabel usernameLabel = new JLabel("Username:");
usernameField = new JTextField(15);
JLabel passwordLabel = new JLabel("Password:");
passwordField = new JPasswordField(15);
JButton loginButton = new JButton("Login");
// Add action listener for the login button
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
authenticateUser();
}
});
// Layout setup
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
panel.add(usernameLabel);
panel.add(usernameField);
panel.add(passwordLabel);
panel.add(passwordField);
panel.add(new JLabel()); // Empty cell for spacing
panel.add(loginButton);
add(panel);
}
private void authenticateUser() {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
// Simple authentication logic (replace with real logic)
if ("user".equals(username) && "pass".equals(password)) {
JOptionPane.showMessageDialog(this, "Login successful!", "Success",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "Invalid username or password.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
UserAuthentication authFrame = new UserAuthentication();
authFrame.setVisible(true);
});
}
}
9. Explain in details about swing components
Swing is a part of Java Foundation Classes (JFC) and provides a rich set of GUI components for
building graphical user interfaces in Java applications. Swing components are lightweight, meaning
they are not tied to the native system's windowing system and instead are drawn using Java's graphics
API
1. Top-Level Containers
These are the primary windows in which Swing components are placed. There are three main
types:
• JFrame: A top-level window with a title and a border. It can contain multiple Swing
components and is commonly used for standalone applications.
JFrame frame = new JFrame("My Application"); frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
2. Basic Components
These are the fundamental components for user interaction:
• JButton: A button that can trigger actions when clicked.
JButton button = new JButton("Click Me");
JLabel: Displays a short string or an image icon. It does not react to input events.
JLabel label = new JLabel("This is a label");
JTextField: A single-line text field for user input.
JTextField textField = new JTextField(20);
JPasswordField: A text field that hides input for password entry.
JPasswordField passwordField = new JPasswordField(20);
JTextArea: A multi-line area for text input.
JTextArea textArea = new JTextArea(5, 20);
Swing is a part of Java Foundation Classes (JFC) and provides a rich set of GUI components
for building graphical user interfaces in Java applications. Swing components are lightweight,
meaning they are not tied to the native system's windowing system and instead are drawn
using Java's graphics API. Here’s a detailed explanation of the main Swing components, their
characteristics, and usage.
1. Top-Level Containers
These are the primary windows in which Swing components are placed. There are three main
types:
• JFrame: A top-level window with a title and a border. It can contain multiple Swing
components and is commonly used for standalone applications.
JFrame frame = new JFrame("My Application");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
• JApplet: A container for applets, which are small applications that can be embedded
in web pages. Applets are less common now due to security restrictions in modern
browsers.
• JDialog: A pop-up window used for gathering input from the user or displaying
information. It can be modal (blocking input to other windows) or non-modal.
JDialog dialog = new JDialog(frame, "Dialog Title", true);
2. Basic Components
These are the fundamental components for user interaction:
• JButton: A button that can trigger actions when clicked.
JButton button = new JButton("Click Me");
• JLabel: Displays a short string or an image icon. It does not react to input events.
JLabel label = new JLabel("This is a label");
• JTextField: A single-line text field for user input.
JTextField textField = new JTextField(20);
• JPasswordField: A text field that hides input for password entry.
JPasswordField passwordField = new JPasswordField(20);
• JTextArea: A multi-line area for text input.
JTextArea textArea = new JTextArea(5, 20);
3. Selection Components
These components allow users to make selections:
• JCheckBox: A box that can be checked or unchecked, representing a boolean value.
JCheckBox checkBox = new JCheckBox("Accept Terms");
• JRadioButton: A button that allows a user to select one option from a set. It is used
within a ButtonGroup to ensure only one can be selected at a time.
JRadioButton radioButton1 = new JRadioButton("Option 1"); JRadioButton radioButton2 = new
JRadioButton("Option 2"); ButtonGroup group = new ButtonGroup(); group.add(radioButton1);
JComboBox: A drop-down list that allows users to select one item from a list.
String[] items = {"Item 1", "Item 2", "Item 3"}; JComboBox<String> comboBox = new
JComboBox<>(items);
4. Container Components
These components can hold other components:
• JPanel: A generic container used for organizing components. It can use various layout
managers
JPanel panel = new JPanel();
JScrollPane: Provides a scrollable view of another component, useful for long lists or large text areas.
JScrollPane scrollPane = new JScrollPane(textArea);
JTabbedPane: Allows for multiple tabs, each containing a different component or set of components.
JTabbedPane tabbedPane = new JTabbedPane();
5. Menu Components
Components for creating menus in applications:
• JMenuBar: A menu bar that holds one or more menus.
JMenuBar menuBar = new JMenuBar();
JMenu: A drop-down menu that contains menu items.
JMenu fileMenu = new JMenu("File");
JMenuItem: An item within a menu that can trigger actions.
JMenuItem openItem = new JMenuItem("Open");
Discuss the following with example programs.
10. Generic class and Generic method
1. Generic Class
A generic class is a class that can operate on objects of various types while providing
compile-time type safety. You define a generic class using angle brackets <> to specify the
type parameter.
Example of a Generic Class
Here’s an example of a simple generic class that represents a box that can hold any type of
object:
// Generic Class
class Box<T>
{ private T item; public void setItem(T item)
{ this.item = item; } public T getItem()
{ return item; } }
public class GenericClassExample {
public static void main(String[] args) {
// Create a box for Integer
Box<Integer> intBox = new Box<>();
2. Generic Method
A generic method allows you to define a method with its own type parameters, independent
of the class's type parameters. This can be useful when you want a method that can work with
different types.
Example of a Generic Method
Here’s an example of a generic method that swaps two elements in an array:
public class GenericMethodExample {
// Generic Method to swap two elements
public static <T> void swap(T[] array, int index1, int index2) {
T temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
public static void main(String[] args) {
// Example with Integer array
Integer[] intArray = {1, 2, 3, 4, 5};
System.out.println("Before Swap: " + java.util.Arrays.toString(intArray));
swap(intArray, 1, 3);
System.out.println("After Swap: " + java.util.Arrays.toString(intArray));
// Example with String array
String[] strArray = {"One", "Two", "Three"};
System.out.println("Before Swap: " + java.util.Arrays.toString(strArray));
swap(strArray, 0, 2);
System.out.println("After Swap: " + java.util.Arrays.toString(strArray));
}
}