Unit 2: GUI and Event Handling - Subjective Questions
CSE406 — Advanced Java Programming • Practice Questions with Detailed Answers
20 questions
Define Swing in Java. Explain its main features and advantages over AWT.
Swing is a GUI toolkit in Java provided by the javax.swing package. It is used to create platform-independent graphical user interfaces.
Main features of Swing:
- Swing provides lightweight components that are written almost entirely in Java.
- It supports a pluggable look and feel.
- It contains a rich set of components such as
JButton,JLabel,JTextField,JTable, andJTree. - Swing follows a modified Model-View-Controller architecture.
- It supports event-driven programming through listener interfaces.
- Swing components are more flexible and customizable than AWT components.
AWT components are heavyweight because they depend on native operating-system components, whereas Swing components are lightweight and generally provide a consistent appearance across platforms.
Explain the purpose and structure of JFrame and JPanel in a Swing application.
JFrame and JPanel are fundamental containers used for constructing Swing GUIs.
JFrame:
- It represents the main window of a desktop application.
- It provides a title bar, border, minimize button, maximize button, and close button.
- Components are generally added to the frame's content pane.
- Common methods include
setTitle(),setSize(),setVisible(), andsetDefaultCloseOperation().
JPanel:
- It is a lightweight container used to group related components.
- It can have its own layout manager, background color, and border.
- Multiple panels can be placed inside a frame to organize the interface.
- It is commonly subclassed when custom painting is required.
A typical hierarchy is: JFrame contains one or more JPanel objects, and each panel contains GUI components.
Describe any five commonly used Swing components and explain their purposes.
Common Swing components include:
JLabel: Displays non-editable text or an image.JButton: Provides a clickable button that generates an action event.JTextField: Allows the user to enter a single line of text.JTextArea: Allows entry and display of multiple lines of text.JCheckBox: Represents an independent on-or-off choice.JRadioButton: Represents one choice from a group of mutually exclusive options when used withButtonGroup.JComboBox: Displays a drop-down list of selectable items.JList: Displays a list of items from which the user can select one or more values.
Each component provides methods for setting properties, retrieving user input, and registering event listeners.
Explain the concept of layout managers in Swing. Compare FlowLayout, BorderLayout, and GridLayout.
A layout manager automatically controls the size and position of components within a container. It helps create interfaces that adjust when the window is resized.
FlowLayout: Places components from left to right in a row. When the row is full, components move to the next row. It is the default layout forJPanel.BorderLayout: Divides a container into five regions:NORTH,SOUTH,EAST,WEST, andCENTER. It is the default layout for a frame's content pane.GridLayout: Arranges components in a rectangular grid with equal-sized cells.
Comparison:
FlowLayoutis suitable for simple rows of controls.BorderLayoutis suitable for dividing a window into major sections.GridLayoutis suitable for calculators, keypads, and forms requiring equal-sized components.
Layout managers are preferred over fixed coordinates because they support portability and resizing.
Explain the Color class in Java Swing. Describe how colors can be created and applied to components.
The java.awt.Color class represents colors using red, green, and blue components.
Ways to create colors:
- Use predefined constants such as
Color.RED,Color.BLUE, andColor.BLACK. - Create a color using RGB values:
new Color(red, green, blue). - Use the constructor with an alpha value to represent transparency:
new Color(red, green, blue, alpha).
Each RGB value normally lies between and . The alpha value also ranges from to , where is fully transparent and is fully opaque.
Colors can be applied using methods such as:
setBackground(Color c)to set the background color.setForeground(Color c)to set the text or foreground color.setColor(Color c)in aGraphicsobject before drawing.
For example, button.setBackground(Color.GREEN) changes the background color of a button.
Explain the Font class and describe the significance of font name, style, and size in GUI programming.
The java.awt.Font class defines the appearance of text displayed by Swing components or drawn using a Graphics object.
A font is generally created using:
new Font(name, style, size)
Font properties:
- Name: Specifies the typeface, such as
Serif,SansSerif, orMonospaced. - Style: Specifies
Font.PLAIN,Font.BOLD,Font.ITALIC, or a combination using the bitwise OR operator. - Size: Specifies the height of the characters in points.
A font can be applied using setFont(), for example, label.setFont(new Font("Serif", Font.BOLD, 18)).
Fonts improve readability and help establish visual hierarchy in an interface. Applications should select clear fonts and suitable sizes for labels, headings, and input controls.
Describe the role of the Graphics class in Swing. Explain the use of paintComponent() in a custom panel.
The java.awt.Graphics class provides methods for drawing text, lines, rectangles, ovals, polygons, and images.
A custom Swing panel should override paintComponent(Graphics g) to perform drawing operations:
- First call
super.paintComponent(g)to clear the panel and preserve normal painting behavior. - Set the drawing color using
g.setColor(). - Set the font using
g.setFont(). - Draw shapes using methods such as
drawLine(),drawRect(), anddrawOval(). - Draw text using
drawString().
The method is called by Swing whenever the component needs to be painted. A program should request repainting by calling repaint() rather than calling paintComponent() directly. This allows Swing to manage painting correctly.
Write and explain a Java Swing program that creates a window containing a label, a text field, and a button.
The following program creates a basic graphical user interface:
import javax.swing.*;
import java.awt.*;
public class SimpleGUI {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Simple GUI");
JPanel panel = new JPanel(new FlowLayout());
JLabel label = new JLabel("Name:");
JTextField field = new JTextField(15);
JButton button = new JButton("Submit");
panel.add(label);
panel.add(field);
panel.add(button);
frame.add(panel);
frame.setSize(350, 120);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}Explanation:
JFramecreates the main window.JPanelgroups the controls.FlowLayoutarranges the components in a row.SwingUtilities.invokeLater()starts the GUI on the Event Dispatch Thread.setDefaultCloseOperation()specifies what happens when the window is closed.
Explain the event delegation model in Java. Identify the roles of an event source, event object, and event listener.
The event delegation model is the mechanism used by Java to handle user actions in a GUI. Instead of a component handling every event internally, it delegates event processing to registered listener objects.
Main elements:
- Event source: The component that generates an event, such as a button, text field, mouse-controlled panel, or frame.
- Event object: An object containing information about the event, such as its source, type, coordinates, or key code. Examples include
ActionEvent,MouseEvent, andKeyEvent. - Event listener: An object that receives and processes the event. It implements a suitable listener interface, such as
ActionListener,MouseListener, orKeyListener.
The general sequence is:
- A user performs an action.
- The source creates an event object.
- Registered listeners are notified.
- The listener method executes the required response.
This model separates GUI components from application-specific event-processing logic.
Distinguish between an event source and an event object with suitable examples.
An event source is the GUI component or object that produces an event. An event object is the object that describes the event and carries information about it.
Event source examples:
- A
JButtongenerates an action event when clicked. - A
JTextFieldcan generate an action event when the user presses Enter. - A
JPanelcan generate mouse events. - A window can generate window events.
Event object examples:
ActionEventcontains information about an action performed on a component.MouseEventcontains the mouse position, button, and click count.KeyEventcontains the key code, key character, and modifier information.
For example, when a user clicks a button, the button is the event source and the generated ActionEvent is the event object passed to the registered ActionListener.
Describe the important event listener interfaces used in Swing and state the purpose of each.
Event listener interfaces define callback methods that are invoked when specific events occur.
ActionListener: Handles actions such as button clicks and pressing Enter in a text field. It definesactionPerformed(ActionEvent e).MouseListener: Handles mouse entering, exiting, pressing, releasing, and clicking. It defines five methods.MouseMotionListener: Handles mouse movement and dragging throughmouseMoved()andmouseDragged().KeyListener: Handles keyboard actions throughkeyPressed(),keyReleased(), andkeyTyped().WindowListener: Handles window operations such as opening, closing, activating, and deactivating a window.ItemListener: Handles changes in the selected state of components such as check boxes and combo boxes.FocusListener: Handles focus gained and focus lost events.
A component must register an appropriate listener before the listener can receive events.
Explain the process of registering and handling an event in Swing. Illustrate it using ActionListener.
Event handling in Swing generally involves three steps:
- Create the event source, such as a
JButton. - Create or implement a listener that contains the event-handling code.
- Register the listener with the source using an
add...Listener()method.
Example:
JButton button = new JButton("Click");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked");
}
});Here, the button is the source, ActionEvent is the event object, and the anonymous object implementing ActionListener is the listener. When the button is clicked, Swing invokes actionPerformed() automatically.
The listener can also be registered using a named class or a lambda expression when the interface has one abstract method.
Explain mouse events in Swing. Describe the methods of MouseListener and MouseMotionListener.
Mouse events are generated when the user interacts with a component using a mouse.
MouseListener methods:
mouseClicked(MouseEvent e): Called after a mouse click.mousePressed(MouseEvent e): Called when a mouse button is pressed.mouseReleased(MouseEvent e): Called when a pressed mouse button is released.mouseEntered(MouseEvent e): Called when the pointer enters a component.mouseExited(MouseEvent e): Called when the pointer leaves a component.
MouseMotionListener methods:
mouseMoved(MouseEvent e): Called when the pointer moves.mouseDragged(MouseEvent e): Called when the pointer moves while a mouse button is pressed.
The MouseEvent object provides methods such as getX(), getY(), getButton(), and getClickCount() to obtain event details.
Write a Java Swing program that displays the coordinates of the mouse pointer when it is clicked on a panel.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MouseCoordinates {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Mouse Coordinates");
JPanel panel = new JPanel();
JLabel label = new JLabel("Click inside the panel");
panel.setPreferredSize(new Dimension(350, 200));
panel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
label.setText("Coordinates: (" + e.getX() + ", " + e.getY() + ")");
}
});
frame.add(panel, BorderLayout.CENTER);
frame.add(label, BorderLayout.SOUTH);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}The panel is the event source. A MouseAdapter receives the mouse event, and getX() and getY() return the click position relative to the panel.
Explain key events in Java Swing. Differentiate among keyPressed, keyReleased, and keyTyped.
Key events are generated when the user interacts with the keyboard. A component must generally be focusable and have keyboard focus to receive these events.
keyPressed(KeyEvent e): Invoked when a physical key is pressed. It is suitable for detecting special keys, function keys, and key codes.keyReleased(KeyEvent e): Invoked when a pressed key is released.keyTyped(KeyEvent e): Invoked when a character is generated. It is generally used for character input rather than physical key identification.
Useful KeyEvent methods include:
getKeyCode()to obtain the symbolic key code.getKeyChar()to obtain the typed character.isShiftDown(),isControlDown(), and similar methods to check modifier keys.
For reliable text input validation, document listeners or formatted text components may be preferable to a KeyListener, because text can also be entered through paste or input methods.
Write and explain a Swing program that responds to keyboard events by displaying the pressed key.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class KeyEventDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Key Event Demo");
JLabel label = new JLabel("Press a key", SwingConstants.CENTER);
label.setFocusable(true);
label.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
label.setText("Pressed: " + e.getKeyText(e.getKeyCode()));
}
});
frame.add(label);
frame.setSize(350, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
label.requestFocusInWindow();
});
}
}The label is made focusable and requests focus after the window becomes visible. The KeyAdapter handles keyPressed(), and getKeyText() converts the key code into readable text.
What is an anonymous class listener? Explain its use in event handling with an example.
An anonymous class listener is an unnamed class object created at the location where it is needed. It implements a listener interface or extends a listener adapter class without requiring a separate class declaration.
Example:
JButton button = new JButton("Save");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Save operation performed");
}
});Advantages:
- Keeps event-handling code close to the component that generates the event.
- Avoids creating a separate named listener class.
- Is useful when a listener is used only once.
Limitation: Large or reusable event-handling logic may become difficult to maintain when many anonymous classes are placed in one method.
Explain listener adapter classes. Why are they useful when handling mouse or window events?
A listener adapter is an abstract convenience class that provides empty implementations of all methods in a listener interface containing multiple methods.
For example, MouseAdapter implements MouseListener, MouseMotionListener, and related interfaces with empty method bodies. A programmer can extend it and override only the required method:
panel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
System.out.println("Mouse pressed");
}
});Without an adapter, implementing MouseListener requires definitions for mouseClicked(), mousePressed(), mouseReleased(), mouseEntered(), and mouseExited(), even when most are unnecessary.
Common adapters include MouseAdapter, KeyAdapter, WindowAdapter, and FocusAdapter. They reduce boilerplate and improve readability.
Compare implementing a listener interface, extending an adapter class, and using a lambda expression for Swing event handling.
Swing events can be handled in several ways:
Implementing a listener interface:
- A class explicitly implements an interface such as
ActionListener. - It must provide all abstract methods.
- This is suitable for reusable or complex handlers.
Extending an adapter class:
- A class extends an adapter such as
MouseAdapter. - Only the required methods need to be overridden.
- This is useful for listener interfaces containing several methods.
Using a lambda expression:
- A lambda can be used with a functional interface containing one abstract method.
- Example:
button.addActionListener(e -> label.setText("Clicked")); - It is concise and useful for short action handlers.
The choice depends on readability, reuse, and the number of methods that must be handled. Lambda expressions cannot directly replace multi-method interfaces such as MouseListener.
Design a Swing GUI for a simple calculator and explain the roles of its components, layout manager, and event handlers.
A simple calculator GUI can be designed using the following structure:
- A
JFrameacts as the main application window. - A
JTextFielddisplays the current input and result. JButtonobjects represent digits, arithmetic operators, clear, and equals operations.- A
JPanelwithGridLayoutarranges the calculator buttons in rows and columns. - A second panel with
BorderLayoutcan place the display at the top and the button panel in the center. - An
ActionListeneris registered with each button.
When a digit button is clicked, its value is appended to the display. When an operator is clicked, the first operand and operator are stored. When the equals button is clicked, the second operand is read and the calculation is performed.
A robust design should also validate input, handle division by zero, clear the display when requested, and keep calculation logic separate from GUI construction.
Define Swing in Java. Explain its main features and advantages over AWT.
Swing is a GUI toolkit in Java provided by the javax.swing package. It is used to create platform-independent graphical user interfaces.
Main features of Swing:
- Swing provides lightweight components that are written almost entirely in Java.
- It supports a pluggable look and feel.
- It contains a rich set of components such as
JButton,JLabel,JTextField,JTable, andJTree. - Swing follows a modified Model-View-Controller architecture.
- It supports event-driven programming through listener interfaces.
- Swing components are more flexible and customizable than AWT components.
AWT components are heavyweight because they depend on native operating-system components, whereas Swing components are lightweight and generally provide a consistent appearance across platforms.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →