KEMBAR78
Module 3 Own | PDF | Computer Programming | Computing
0% found this document useful (0 votes)
18 views23 pages

Module 3 Own

Uploaded by

Pravallika Reddy
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)
18 views23 pages

Module 3 Own

Uploaded by

Pravallika Reddy
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/ 23

Module 3

What is Java Swing? Discuss the evolution of Java Swing and explain its key
features.(MQP)

Java Swing is a part of the Java Foundation Classes (JFC) used for building graphical user
interfaces (GUIs) in Java applications. It provides a richer set of GUI components than the
earlier Abstract Window Toolkit (AWT), enabling the creation of more flexible and
powerful user interfaces.

Swing is often used for developing desktop applications and supports components like
buttons, text boxes, tables, trees, and more—all of which are more advanced and
customizable compared to AWT components.

Evolution of Java Swing

• Early Days – AWT:


Java's original GUI toolkit was the AWT. It provided basic components that relied on
platform-specific “peers.” These were heavyweight and lacked flexibility.

• Limitations of AWT:

o Platform-dependent appearance and behavior.

o Inconsistent look and feel across systems.


o Difficult to customize components.

o Use of native peers limited flexibility and portability.

• Introduction of Swing (1997):


To overcome AWT’s drawbacks, Swing was introduced as part of the JFC. Initially
released for Java 1.1 as a separate library, it became fully integrated from Java 1.2
onwards, marking the beginning of Java 2 (J2SE 1.2).

Key Features of Swing

1. Lightweight Components:

o Unlike AWT, Swing components are mostly written in pure Java.

o They do not rely on native OS peers.

o Result: more consistent behavior and appearance across platforms.

2. Pluggable Look and Feel (PLAF):


o Swing separates component logic from appearance.
o Developers can switch between different UI styles without modifying
component code.

3. Built on AWT:

o Swing does not replace AWT; it builds on top of it.

o It uses AWT’s event handling model and extends the component framework.

4. MVC Architecture:

o Many Swing components follow the Model-View-Controller pattern.


o This promotes better separation of data, presentation, and user interaction.

5. Extensive Set of Components:

o Includes not just basic controls but also advanced components like:

▪ JTree, JTable, JTabbedPane, JList, JFormattedTextField, JSpinner, etc.

6. Custom Rendering & Painting:


o Swing allows custom drawing via methods like paintComponent(), enabling
rich graphics and animations.
7. Thread-Safe GUI Updates:
o Swing uses the Event Dispatch Thread (EDT) to manage all UI updates,
ensuring thread safety in GUI applications.

Describe the MVC Connection. How is this design pattern


implemented in Java Swing applications(MQP)
Components
 Swing components are derived from the JComponent class..

 JComponent inherits AWT classes Container and Component.

 All the Swing components are represented by classes in the javax.swing package.

 All the component classes start with J: JLabel, JButton, JScrollbar, ..

Containers
Swing supports two types of containers:

1. Top-Level Containers

o Examples: JFrame, JApplet, JWindow, JDialog

o These do not inherit JComponent, but do inherit AWT’s Component and


Container.

o They are heavyweight components.

Every GUI must begin with a top-level container.

2. Lightweight Containers
o Example: JPanel
o These do inherit JComponent and can be nested.

o Often used to organize components and form subgroups within a GUI.

Swing uses a containment hierarchy, and JFrame is most commonly used for application

A simple Swing Application


import javax.swing.*;

class SwingDemo {

SwingDemo() {

JFrame jfrm = new JFrame("A simple Swing Application");

jfrm.setSize(275, 100);

jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel jlab = new JLabel("Swing means powerful GUI");
jfrm.add(jlab);

jfrm.setVisible(true);

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {

new SwingDemo();
}

});
}}
Event Handling
“The event handling mechanism used by Swing is the same as that used by the AWT.”

• It uses the Delegation Event Model, where:

o A source generates an event.

o A listener waits for it and handles it.

• AWT-related events are in **java.awt.event**, while Swing-specific events are in


**javax.swing.event**.

Steps for Button Click Event Handling

1. Create a JButton

2. Add an ActionListener to the button


3. Override the actionPerformed method to define the behavior when the button is clicked

Program Example
import javax.swing.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class ButtonClickExample {

public static void main(String[] args) {

// Create the JFrame (window)

JFrame frame = new JFrame("Button Click Example");


frame.setSize(300, 150);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(null); // Using absolute positioning

// Create a JButton

JButton button = new JButton("Click Me");

button.setBounds(100, 40, 100, 30);


// Create a JLabel to show result

JLabel label = new JLabel("");

label.setBounds(100, 80, 150, 20);

// Add ActionListener to the button

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

label.setText("Button was clicked!");

});

// Add components to the frame


frame.add(button);

frame.add(label);

// Set frame visible

frame.setVisible(true);

}
Java Swing Applet
➢ The class extends JApplet to create a Swing-based applet.
➢ GUI is initialized inside the init() method.
➢ Uses SwingUtilities.invokeAndWait() for thread-safe GUI creation.
➢ Handles button click events using ActionListener.

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

import java.awt.event.*;

public class ButtonClickApplet extends JApplet {

JButton button;

JLabel label;

public void init() {

// Ensure GUI creation runs on Event Dispatch Thread

try {

SwingUtilities.invokeAndWait(new Runnable() {

public void run() {

makeGUI();

}
});

} catch (Exception e) {

System.out.println("GUI creation failed: " + e);

private void makeGUI() {

setLayout(null);

// Create and position button


button = new JButton("Click Me");
button.setBounds(80, 30, 120, 30);
// Create and position label

label = new JLabel("");

label.setBounds(80, 70, 200, 20);

// Add ActionListener to button


button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

label.setText("Button was clicked!");

});

// Add components to applet

add(button);
add(label);
}

Elaborate the concept of painting in Java Swing. Illustrate your


explanation with a suitable example program.(MQP)
Painting in Java Swing

Painting in Swing refers to the process of drawing custom graphics directly onto a
component such as a panel or label. Swing provides the ability to render lines, shapes, text,
and images by overriding specific methods and using the Graphics class from AWT.

Key Concepts:

1. Swing's Painting Model:

o Unlike AWT, Swing divides painting into three distinct methods:

▪ paintComponent(Graphics g) – paints the component’s content.


▪ paintBorder(Graphics g) – paints the border.

▪ paintChildren(Graphics g) – paints any child components.

o You typically override only paintComponent() for custom drawing.


2. Always Call super.paintComponent(g)
o The overridden method should begin with super.paintComponent(g) to ensure
proper rendering and background clearing.
3. Use repaint() to Refresh the Display

o When you want to trigger redrawing, you call repaint(). This results in
paintComponent() being invoked.

4. Compute the Paintable Area

o Use getInsets() along with getWidth() and getHeight() to ensure your drawing
doesn't overwrite borders

Program

import javax.swing.*;

import java.awt.*;

// Custom panel where painting happens

class MyPanel extends JPanel {

// Override paintComponent to draw something

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g); // call superclass method

// Set color and draw a rectangle

g.setColor(Color.BLUE);

g.fillRect(50, 50, 100, 100);

// Draw a string

g.setColor(Color.RED);

g.drawString("Hello, Swing!", 60, 180);

// Draw a line

g.setColor(Color.GREEN);

g.drawLine(20, 20, 200, 20);

}
}
public class SimplePaintingExample {

public static void main(String[] args) {

JFrame frame = new JFrame("Painting Example");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(300, 300);

// Add custom panel to frame

frame.add(new MyPanel());

frame.setVisible(true);

}
}

Discuss the functionality of the four commonly used buttons in


Java Swing. Illustrate each with a suitable example.(MQP)
Four Commonly Used Buttons in Java Swing

Swing provides four main types of buttons, all of which are subclasses of AbstractButton.
These buttons support common features such as text, icons, tooltips, and event handling.

1.JButton
The JButton class provides the functionality of a push button. JButton allows an icon, a
string, or both to be associated with the push button. Three of its constructors are shown here

Example Program:- Same as Event Handling


2. JToggleButton – Two-State Button

• A toggle button retains its state: pressed (on) or released (off).

• Pressing it toggles the state.

• It is a superclass of JCheckBox and JRadioButton.


Constructor:

JToggleButton(String text);

This creates a toggle button that contains the text passed in str. By default, the button is in the
off position. Other constructors enable you to create toggle buttons that contain images, or
images and text.
Example

import javax.swing.*;

import java.awt.event.*;

public class ToggleButtonExample {

public static void main(String[] args) {

// Create the frame


JFrame frame = new JFrame("JToggleButton Example");

frame.setSize(300, 150);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(null); // Absolute positioning

// Create a JToggleButton

JToggleButton toggleButton = new JToggleButton("OFF");

toggleButton.setBounds(100, 40, 100, 30);

// Create a label to show the state

JLabel label = new JLabel("Button is OFF");

label.setBounds(100, 80, 150, 20);


// Add ActionListener to toggle button

toggleButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

if (toggleButton.isSelected()) {
toggleButton.setText("ON");

label.setText("Button is ON");

} else {

toggleButton.setText("OFF");

label.setText("Button is OFF");

}
});

// Add components to frame

frame.add(toggleButton);

frame.add(label);

// Show the frame

frame.setVisible(true);
}

3. JCheckBox – Checkable Option

• Used for on/off or yes/no choices.

• Multiple checkboxes can be selected at once.

• Subclass of JToggleButton.

Constructor:
JCheckBox(String str)

It creates a check box that has the text specified by str as a label. Other constructors let you
specify the initial selection state of the button and specify an icon
import javax.swing.*;

import java.awt.event.*;

public class CheckBoxExample {


public static void main(String[] args) {

// Create the frame

JFrame frame = new JFrame("JCheckBox Example");

frame.setSize(300, 200);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(null); // Using absolute positioning

// Create a JCheckBox
JCheckBox checkBox = new JCheckBox("I agree to the terms");

checkBox.setBounds(50, 50, 200, 30);

// Create a JLabel to display the result

JLabel label = new JLabel("");

label.setBounds(50, 100, 200, 30);

// Add an ItemListener to the checkbox

checkBox.addItemListener(new ItemListener() {

public void itemStateChanged(ItemEvent e) {

if (checkBox.isSelected()) {

label.setText("Checked");

} else {

label.setText("Unchecked");
}

}
});
// Add components to the frame

frame.add(checkBox);

frame.add(label);

// Show the frame

frame.setVisible(true);

4. JRadioButton – Exclusive Selection

• Used in groups where only one option is selected at a time.


• Must be added to a ButtonGroup for mutual exclusivity.
• Also a subclass of JToggleButton.

Constructor:

JRadioButton(String str)

Here, str is the label for the button. Other constructors let you specify the initial selection
state of the button and specify an icon.

import javax.swing.*;

import java.awt.event.*;

public class RadioButtonExample {

public static void main(String[] args) {


// Create the frame

JFrame frame = new JFrame("JRadioButton Example");

frame.setSize(300, 200);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(null); // Using absolute positioning


// Create radio buttons

JRadioButton option1 = new JRadioButton("Male");

option1.setBounds(50, 40, 100, 30);

JRadioButton option2 = new JRadioButton("Female");

option2.setBounds(150, 40, 100, 30);

// Group the radio buttons so only one can be selected

ButtonGroup group = new ButtonGroup();

group.add(option1);

group.add(option2);

// Label to show result

JLabel label = new JLabel("Select Gender");

label.setBounds(50, 100, 200, 30);

// Add action listeners

option1.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {


label.setText("Selected: Male");

});

option2.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

label.setText("Selected: Female");
}

});
// Add components to frame

frame.add(option1);

frame.add(option2);

frame.add(label);

// Show the frame

frame.setVisible(true);

Explain the following swing components with an example


program: i)JLabel ii)JTextField iii) JScrollPane iv) JTable(MQP)
i) JLabel
• The JLabel class is a component in Java Swing used to display a short string of
text, an icon, or both. It is part of the javax.swing package.

• It does not accept user input and is mainly used for display purposes.

Icon getIcon()

String getText()

Void setIcon(Icon icon)

Void setText(String str)

Example
import javax.swing.*;
public class LabelExample {

public static void main(String[] args) {

// Create the frame


JFrame frame = new JFrame("JLabel Example");
frame.setSize(300, 150);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(null); // Using absolute positioning

// Create a JLabel
JLabel label = new JLabel("Welcome to Swing!");

label.setBounds(90, 50, 150, 30); // x, y, width, height

// Add label to frame

frame.add(label);

// Show the frame


frame.setVisible(true);
}

Welcome to Swing!

2.JTextFeild

import javax.swing.*;

import java.awt.event.*;

public class TextFieldActionExample {

public static void main(String[] args) {

JFrame frame = new JFrame("TextField Action");


frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null); // Absolute positioning

// Create a text field

JTextField textField = new JTextField();


textField.setBounds(50, 50, 200, 30);

// Create a label

JLabel label = new JLabel("");

label.setBounds(50, 100, 200, 30);

// Add ActionListener to the text field (triggers when Enter is pressed)


textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

String text = textField.getText();

label.setText("You typed: " + text);

});

// Add components to frame


frame.add(textField);

frame.add(label);

// Show the frame

frame.setVisible(true);

}
3.JScrollPane
• JScrollPane adds scrolling capabilities to components like JPanel, JTable, etc.

• It automatically shows scrollbars if the content is larger than the viewport.


import javax.swing.*;

public class ScrollPaneExample {

public static void main(String[] args) {


// Create a frame

JFrame frame = new JFrame("JScrollPane Example");

frame.setSize(300, 200);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(null); // Absolute positioning

// Create a multi-line text area

JTextArea textArea = new JTextArea();


textArea.setText("This is a scrollable text area.\nYou can write multiple lines
here.\nLine 3\nLine 4\nLine 5");

// Wrap the text area in a scroll pane

JScrollPane scrollPane = new JScrollPane(textArea);

scrollPane.setBounds(30, 30, 220, 100); // Set scroll pane size


// Add scroll pane to frame (not the text area directly)

frame.add(scrollPane);

// Show the frame


frame.setVisible(true);

iv) JTable

• JTable displays data in tabular format (rows and columns).

• To enable scrolling, it's typically placed inside a JScrollPane.

import javax.swing.*;
public class SimpleJTable {
public static void main(String[] args) {

// Data for the table

String[][] data = {

{"1", "Apple"},

{"2", "Banana"},

{"3", "Cherry"}

};

// Column headers

String[] columns = {"ID", "Fruit"};

// Create table and put it in scroll pane

JTable table = new JTable(data, columns);

JScrollPane scrollPane = new JScrollPane(table);

// Create frame and add the scroll pane


JFrame frame = new JFrame("Simple JTable");
frame.add(scrollPane); // no layout set — default BorderLayout used

frame.setSize(300, 150);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);
}

What is JPanel in Java Swing?

JPanel is a generic container class in Java Swing used to group components together. It
doesn’t have a window of its own — instead, it's added to a JFrame or another container. You
can use it for:

• Organizing layout

• Painting custom graphics

• Nesting components

Simple Example of JPanel

import javax.swing.*;

import java.awt.*;

public class JPanelExample {

public static void main(String[] args) {

// Create the frame

JFrame frame = new JFrame("JPanel Example");


frame.setSize(300, 200);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a panel

JPanel panel = new JPanel();

// Add a button to the panel


JButton button = new JButton("Click Me");

panel.add(button); // add button to panel

// Add the panel to the frame


frame.add(panel);

// Make the frame visible

frame.setVisible(true);

JFrame is a class in the javax.swing package used to create a window in a Java Swing application.It represents the main
window of a graphical user interface (GUI) where you can add other components like buttons, labels, text fields, etc.
JFrame()
JFrame(String title)

You might also like