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

Unit-1(Advance Java)

The document provides an overview of GUI programming in Java, focusing on AWT and Swing toolkits. It highlights the limitations of AWT, such as platform dependency and performance issues, while emphasizing the advantages of Swing, including lightweight components and a rich set of features. Additionally, it covers key classes like JFrame and JComponent, methods for customizing GUI elements, and techniques for drawing shapes and handling events in Swing applications.

Uploaded by

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

Unit-1(Advance Java)

The document provides an overview of GUI programming in Java, focusing on AWT and Swing toolkits. It highlights the limitations of AWT, such as platform dependency and performance issues, while emphasizing the advantages of Swing, including lightweight components and a rich set of features. Additionally, it covers key classes like JFrame and JComponent, methods for customizing GUI elements, and techniques for drawing shapes and handling events in Swing applications.

Uploaded by

bikram.sah.2023
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

GUI Programming

AWT: AWT is the original GUI toolkit for Java, introduced in JDK 1.0. It provides a set of heavyweight components that
rely on the underlying native operating system (OS) to render and manage GUI elements.

Limitations
 Platform Dependency: The appearance and behavior of AWT components can vary across different platforms,
leading to inconsistencies.
 Limited Flexibility: AWT lacks the extensive set of components and customization options available in Swing.
 Performance: Because AWT relies on native resources, it can be less performant and more resource-intensive
than Swing.

Swing: Swing is a part of the Java Foundation Classes (JFC) and was introduced in JDK 1.2 as an extension of AWT. It
provides a richer and more flexible set of components for building GUIs.

Features
 Lightweight Components: Swing components are lightweight and written entirely in Java. They do not depend
on native OS resources, leading to consistent behavior across platforms.
 Pluggable Look and Feel: Swing supports changing the look and feel of applications dynamically, allowing for a
customizable user interface.
 Rich Set of Components: Swing offers a wide range of advanced components, such as trees, tables, lists, and
text components.
 MVC Architecture: Swing components follow the Model-View-Controller (MVC) architecture, separating data
handling from the display and interaction logic.
 Double Buffering: Swing supports double buffering, reducing flicker and providing smoother graphics.

JFrame: JFrame is a class in Java's Swing library that represents a window with a title, border, and buttons for closing,
minimizing, and maximizing the window. It is a fundamental class for creating graphical user interfaces in Java
applications.
Example:
import javax.swing.JFrame;

public class MyJFrame extends JFrame {

public MyJFrame() {
setTitle("My JFrame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setVisible(true);
}
public static void main(String[] args){
new MyJFrame();
}
}
Output:

JFrame Constructors: JFrame has several constructors that allow you to create a frame in different ways, depending on
your requirements. Here are the main constructors provided by JFrame:
1. JFrame(): Creates a frame that has no title.
2. JFrame(GraphicsConfiguration gc): Creates a frame with the specified GraphicsConfiguration of a screen device.
This is used when you need to work with multiple screen devices.
3. JFrame(String title): Creates a frame with the specified title.
4. JFrame(String title, GraphicsConfiguration gc): Creates a frame with the specified title and
GraphicsConfiguration.

JFrame Methods: JFrame class in Java Swing provides a variety of methods to customize and control the behavior of the
window. Here are some important methods commonly used with JFrame.
1. setTitle(String title): Sets the title for the frame.
setTitle("My JFrame Title");
2. setSize(int width, int height): Sets the size of the frame.
setSize(400, 300);
3. setVisible(boolean b): Makes the frame visible or invisible.
setVisible(true);
4. setDefaultCloseOperation(int operation): Defines the operation that will happen by default when the user
initiates a "close" on this frame. Common options are:
JFrame.EXIT_ON_CLOSE : This terminates the application when the frame is closed.
JFrame.DISPOSE_ON_CLOSE : This disposes of the frame when it is closed but does not terminate the
application.
JFrame.HIDE_ON_CLOSE : This hides the frame when it is closed.
JFrame.DO_NOTHING_ON_CLOSE : This does nothing when the close button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
5. setLocation(int x, int y): Sets the location of the frame relative to the screen coordinates.
setLocation(100, 100);
6. setBounds(int x, int y, int width, int height): It combines setting the location and size of the frame in one call. The
method takes four parameters: x, y, width, and height.
setBounds(100, 100,400,300);
7. add(Component comp): Adds a component to the frame.
frame.add(new JButton("Click Me"));
8. pack(): Causes the frame to be sized to fit the preferred size and layouts of its subcomponents.
pack();
9. setResizable(boolean resizable): Determines whether the frame is resizable by the user.
setResizable(false);
10. setIconImage(Image image): Sets the image to be displayed as the icon for this window.
ImageIcon icon = new ImageIcon("path/icon.png").getImage();
setIconImage(icon.getImage());
11. setLayout(LayoutManager manager): Sets the layout manager for the frame's content pane.
setLayout(new FlowLayout());

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

public class MyJFrame extends JFrame {

public MyJFrame() {
setSize(400, 300);
setLocation(100, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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


add(button);

Image img = new ImageIcon("..//MyJavaSwing//src//main//java//spider.png").getImage();


setIconImage(img);

setLayout(new FlowLayout());
setResizable(false);
setVisible(true);
}
public static void main(String[] args){
new MyJFrame();
}

Output:

EventQueue.invokeLater: It is a method used in Java to ensure that a piece of code is executed on the Event
Dispatch Thread (EDT). This is crucial in Swing applications for ensuring that updates to the GUI are thread-safe and
performed on the correct thread. The invokeLater method takes a Runnable object, which contains the code to be
executed, and schedules it to run on the EDT.

Why Use EventQueue.invokeLater?


Swing is not thread-safe, which means that GUI components should only be updated on the EDT. If GUI updates are
performed on a different thread, it can lead to unpredictable behavior and bugs. EventQueue.invokeLater ensures that
your GUI-related code is executed on the EDT, maintaining thread safety.

Syntax:
EventQueue.invokeLater(Runnable runnable);

Using a Lambda Expression:


EventQueue.invokeLater(() -> {
// Code to be executed on the Event Dispatch Thread
});

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

public class MyJFrame extends JFrame {


public MyJFrame() {
EventQueue.invokeLater(()->{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,400);
setLocationRelativeTo(null);
setVisible(true);
});
}
public static void main(String[] args){
new MyJFrame();
}
}

JComponent: It is the base class for all Swing components except top-level containers like JFrame, JDialog, and
JApplet. It provides a foundation of common functionality for all Swing components, including features such as painting,
event handling, layout management, and properties management.
Key Features of JComponent
1. Painting and Rendering: JComponent provides the mechanism for custom painting. You can override the
paintComponent(Graphics g) method to perform custom rendering.
2. Event Handling: JComponent inherits from Container, which means it can listen to and handle various types of
events like mouse clicks, key presses, and more.
3. Layout Management: Since JComponent is a subclass of Container, it can contain other components and be
managed by layout managers.
4. Properties: JComponent provides support for properties, including methods to set and get properties, as well as
property change events.
5. Borders: You can set borders on any JComponent using the setBorder(Border border) method.

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

class MyJComponent extends JComponent {


@Override
protected void paintComponent(Graphics g) {
// Cast Graphics to Graphics2D
Graphics2D g2d = (Graphics2D) g;

// Draw a custom shape


g2d.setColor(Color.RED);
g2d.fillOval(10, 10, 100, 100);

@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
// Set preferred size of the component
}

public class MyJFrame extends JFrame {


public MyJFrame() {
EventQueue.invokeLater(()->{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

MyJComponent mComponent = new MyJComponent();


add(mComponent);
pack();
setVisible(true);
});
}
public static void main(String[] args){
new MyJFrame();
}
}

Output:

Explanation:
1. void paintComponent(Graphics g) : method in Swing is used for performing custom painting on a JComponent. When
you want to draw something custom in a component, you override this method to specify what and how it
should be drawn.
2. Casting to Graphics2D: Graphics2D is a subclass of Graphics that provides more advanced features.
Graphics2D g2d = (Graphics2D) g;
3. void getPreferredSize() : This method in Swing is used to specify the preferred size of a component. It is part of the
JComponent class and is often overridden in custom components to return the desired size of the component.
This size can then be used by layout managers to determine the component's layout within a container.

2D Shapes: Working with 2D shapes in Swing involves using the Graphics and Graphics2D classes to draw various
shapes on a component. The Graphics2D class, which extends Graphics, provides more sophisticated control over
geometry, coordinate transformations, color management, and text layout.

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

class MyJComponent extends JComponent {


@Override
protected void paintComponent(Graphics g) {
// Cast Graphics to Graphics2D
Graphics2D g2d = (Graphics2D) g;

// Set the drawing color


g2d.setColor(Color.BLUE);

// Draw a rectangle
g2d.fillRect(10, 10, 100, 50);

// Draw an oval
g2d.setColor(Color.RED);
g2d.fillOval(130, 10, 100, 50);

// Draw a line
g2d.setColor(Color.GREEN);
g2d.drawLine(10, 80, 240, 80);

// Draw a rounded rectangle


g2d.setColor(Color.MAGENTA);
g2d.fillRoundRect(10, 100, 100, 50, 20, 20);

// Draw an arc
g2d.setColor(Color.ORANGE);
g2d.fillArc(130, 100, 100, 50, 0, 180);

// Draw a polygon
int[] xPoints = { 10, 30, 50};
int[] yPoints = { 180, 160, 180};
g2d.setColor(Color.CYAN);
g2d.fillPolygon(xPoints, yPoints, xPoints.length);

@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
// Set preferred size of the component
}

public class MyJFrame extends JFrame {


public MyJFrame() {
EventQueue.invokeLater(()->{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

MyJComponent mComponent = new MyJComponent();


add(mComponent);

pack();
setLocationRelativeTo(null);
setVisible(true);
});
}
public static void main(String[] args){
new MyJFrame();
}
}
Output:

Shape Methods:
fillRect(int x, int y, int width, int height): Draws a filled rectangle with the specified coordinates and dimensions.
 x: The x-coordinate of the rectangle's top-left corner.
 y: The y-coordinate of the rectangle's top-left corner.
 width: The width of the rectangle.
 height: The height of the rectangle.

fillOval(int x, int y, int width, int height): Draws a filled oval bounded by the specified rectangle.
 x: The x-coordinate of the rectangle's top-left corner.
 y: The y-coordinate of the rectangle's top-left corner.
 width: The width of the bounding rectangle.
 height: The height of the bounding rectangle.

drawLine(int x1, int y1, int x2, int y2): Draws a line between the specified coordinates.
 x1: The x-coordinate of the start point.
 y1: The y-coordinate of the start point.
 x2: The x-coordinate of the end point.
 y2: The y-coordinate of the end point.

fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight): Draws a filled rounded rectangle with the
specified dimensions and corner arc widths.
 x: The x-coordinate of the rounded rectangle's top-left corner.
 y: The y-coordinate of the rounded rectangle's top-left corner.
 width: The width of the rounded rectangle.
 height: The height of the rounded rectangle.
 arcWidth: The horizontal diameter of the arc at the four corners.
 arcHeight: The vertical diameter of the arc at the four corners.

fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): Draws a filled arc covering the specified rectangle
from startAngle to startAngle + arcAngle.
 x: The x-coordinate of the arc's bounding rectangle.
 y: The y-coordinate of the arc's bounding rectangle.
 width: The width of the bounding rectangle.
 height: The height of the bounding rectangle.
 startAngle: The starting angle of the arc in degrees.
 arcAngle: The angular extent of the arc in degrees.

fillPolygon(int[] xPoints, int[] yPoints, int nPoints): Draws a filled polygon defined by arrays of x and y coordinates.
 xPoints: An array of x-coordinates of the polygon's vertices.
 yPoints: An array of y-coordinates of the polygon's vertices.
 nPoints: The total number of vertices.

Colors: To use colors in your 2D graphics, you need to set the color on the Graphics2D object before drawing shapes or
text. These are some ways to set colors on shapes.
1. setColor(Color c): This method is used to set the current color for all subsequent drawing operations.
 c: An instance of the java.awt.Color class that represents the desired color.

2. Using the Color class by specifying RGB or RGBA values:


a) RGB Color: new Color(int r, int g, int b) where r, g, and b are values between 0 and 255.
b) RGBA Color: new Color(int r, int g, int b, int a) where a is the alpha (transparency) value between 0
(completely transparent) and 255 (completely opaque).

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

class MyJComponent extends JComponent {


@Override
protected void paintComponent(Graphics g) {
// Cast Graphics to Graphics2D
Graphics2D g2d = (Graphics2D) g;

// Set the drawing color


g2d.setColor(Color.BLUE);

// Draw a rectangle
g2d.fillRect(10, 10, 100, 50);

// Draw with a custom RGB color


Color cc1 = new Color(128, 0, 128); // Purple color
g2d.setColor(cc1);
g2d.fillRect(10, 70, 100, 50);

// Draw with a custom RGBA color (semi-transparent)


Color cc2 = new Color(0, 128, 0, 50); // Semi-transparent green
g2d.setColor(cc2);
g2d.fillOval(130, 10, 100, 50);

@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
// Set preferred size of the component
}

public class MyJFrame extends JFrame {


public MyJFrame() {
EventQueue.invokeLater(()->{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

MyJComponent mComponent = new MyJComponent();


add(mComponent);
pack();
setLocationRelativeTo(null);
setVisible(true);
});
}
public static void main(String[] args){
new MyJFrame();
}
}

Output:

Fonts: Using special fonts for text in Java Swing applications involves customizing the font properties such as font
family, style, and size. The Font class in the java.awt package is used to define the font properties, and you can set these
properties on a Graphics2D object to render text with the desired font.
1. Font(String name, int style, int size): Creates a font object with the specified name, style, and size.
2. Font.createFont(Font.TRUETYPE_FONT, new File("path/to/custom_font.ttf")).deriveFont(24f); is used to load a
custom TrueType font from a file and then create a derived font object with a specific size. This approach allows
you to use fonts that are not installed on the system
 Font.createFont() to load the font from a .ttf file.
 deriveFont(float size) method to set the desired size for the font.
Methods:
1. setFont(Font font): Set the current font for a Graphics2D context. This method defines the font that will be used
for all subsequent text rendering operations within the graphics context.
2. drawString(String str, int x, int y): Draw a string of text at a specified location within the graphics context. The
position of the text is defined by the x and y coordinates, which represent the baseline of the text.
Example:
import java.awt.*;
import java.io.*;
import javax.swing.*;

class MyJComponent extends JComponent {


@Override
protected void paintComponent(Graphics g) {
// Cast Graphics to Graphics2D
Graphics2D g2d = (Graphics2D) g;

Font serifFont = new Font("Serif", Font.PLAIN, 24);

g2d.setColor(Color.BLACK);

g2d.setFont(serifFont);
g2d.drawString("Serif Plain 24", 10, 40);

try {
// Load the custom font from a file
Font customFont = Font.createFont(Font.TRUETYPE_FONT, new File("F:\\Fonts\\BLKCHCRY.ttf")).deriveFont(24f);
g2d.setFont(customFont);
g2d.setColor(Color.BLACK);
g2d.drawString("Custom Font", 10, 80);
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}

@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
// Set preferred size of the component
}

public class MyJFrame extends JFrame {


public MyJFrame() {
EventQueue.invokeLater(()->{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

MyJComponent mComponent = new MyJComponent();


add(mComponent);

pack();
setLocationRelativeTo(null);
setVisible(true);
});
}
public static void main(String[] args){
new MyJFrame();
}
}

Output:

Displaying Images: Displaying images in a Swing application involves using components like JLabel, ImageIcon, and
custom drawing via paintComponent in a subclass of JComponent.

Image img = new ImageIcon(path).getImage(): It is a common approach to load an image from a file path and obtain an Image
object. This can be useful when you want to perform custom drawing with the image in a JComponent.

Example:
class MyJComponent extends JComponent {
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Image img = new ImageIcon("..//MyJavaSwing//src//main//java//submit.gif").getImage();

g2.drawImage(img, 0, 0, this);
}

@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
// Set preferred size of the component
}

public class MyJFrame extends JFrame {


public MyJFrame() {
EventQueue.invokeLater(()->{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

MyJComponent mComponent = new MyJComponent();


add(mComponent);

pack();
setLocationRelativeTo(null);
setVisible(true);
});
}
public static void main(String[] args){
new MyJFrame();
}
}

Output:

Explanation:
new ImageIcon(imagePath).getImage(): It loads the image and retrieves the Image object.
drawImage(img, 0, 0, this): draws the image at the top-left corner (0, 0).

ImageIcon(path): It to load and display images in a Swing application is straightforward and commonly used.
Example:
import java.awt.*;
import javax.swing.*;

class MyJComponent extends JComponent {


@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
ImageIcon icon = new ImageIcon("..//MyJavaSwing//src//main//java//spider.png");
JLabel label = new JLabel(icon);

// Set the layout and add the label to this component


setLayout(new BorderLayout());
add(label, BorderLayout.CENTER);
}

@Override
public Dimension getPreferredSize() {
return new Dimension(600, 600);
// Set preferred size of the component
}

public class MyJFrame extends JFrame {


public MyJFrame() {
EventQueue.invokeLater(()->{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

MyJComponent mComponent = new MyJComponent();


add(mComponent);

pack();
setLocationRelativeTo(null);
setVisible(true);
});
}
public static void main(String[] args){
new MyJFrame();
}
}

Output:

Explanation:
 ImageIcon is created from the provided image path.
 A JLabel is created with the image icon
 The component’s layout is set to BorderLayout, and the label is added to the center.

Event handling: Event handling in Java Swing is a fundamental aspect of building interactive GUI applications. Swing
provides a robust framework for capturing and responding to user interactions, such as button clicks, mouse
movements, key presses, and other events. Here's an overview of how to handle events in Swing.
Basics of Event Handling in Swing
1. Event Source: The component that generates an event (e.g., a button, text field, window).
2. Event Listener: An interface that defines the methods to handle specific types of events.
3. Event Object: Encapsulates the information about the event (e.g., ActionEvent, MouseEvent).

Example: Handling Button Clicks


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

class EventHandling{
public EventHandling(){
JFrame f = new JFrame("EventHandling");
f.setSize(300,300);
f.setResizable(false);
f.setLocationRelativeTo(null);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton b = new JButton("Click Here!");


b.setBounds(100, 100, 100,20);
f.add(b);

b.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Buttom clicked");
}
});

f.setVisible(true);
}
}

public class Example {


public static void main(String[] args){
new EventHandling();
}
}

In this example event source is button, ActionListener interface is used as Event Listener and object of ActionEvent class
is used.

Event classes: Event classes are used to represent events generated by GUI components. These classes encapsulate
the details about the events and provide methods to retrieve information about the event, such as its source and the
specific type of event.

Event Listener: An event listener in Java is an interface that defines the methods required to handle specific types of
events. Listeners are used in GUI applications to respond to user actions, such as button clicks, mouse movements, and
key presses. When an event occurs, the corresponding method in the listener interface is called, allowing the application
to respond appropriately.

Below are some common event classes and listener used in Swing.
1. ActionEvent: Represents action events, such as button clicks or menu item selections.
ActionListener: Handles action events, such as button clicks.
Method to implement: void actionPerformed(ActionEvent e).
Example:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class Example{


public static void main(String[] args) {
JFrame f = new JFrame("ActionEvent Example");
f.setLayout(null);
f.setSize(300, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton b = new JButton("Click Here");


b.setBounds(100, 100, 100, 20);

b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});

f.add(b);
f.setVisible(true);
}
}

2. MouseEvent: Represents mouse events, such as mouse clicks, movements, and drags.
MouseListener: Handles mouse events, such as clicks, presses, and releases.
Methods to implement: void mouseClicked(MouseEvent e), void mousePressed(MouseEvent e), void
mouseReleased(MouseEvent e), void mouseEntered(MouseEvent e), void mouseExited(MouseEvent e).
Example:
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;

public class Example{


public static void main(String[] args) {
JFrame f = new JFrame("MouseEvent Example");
f.setLayout(null);
f.setSize(300, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at (" + e.getX() + ", " + e.getY() + ")");
}
@Override
public void mousePressed(MouseEvent e) {
System.out.println("Mouse Pressed");
}
@Override
public void mouseReleased(MouseEvent e) {
System.out.println("Mouse Released");
}
@Override
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse Entered");
}
@Override
public void mouseExited(MouseEvent e) {
System.out.println("Mouse Exited");
}
});

f.setVisible(true);
}
}

3. KeyEvent: Represents keyboard events, such as key presses, releases, and typing.
KeyListener: Handles keyboard events, such as key presses and releases.
Methods to implement: void keyTyped(KeyEvent e), void keyPressed(KeyEvent e), void keyReleased(KeyEvent
e).
Example:
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;

public class Example{


public static void main(String[] args) {
JFrame f = new JFrame("KeyEvent Example");
f.setLayout(null);
f.setSize(300, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
System.out.println("Key typed: " + e.getKeyChar());
}
@Override
public void keyPressed(KeyEvent e) {
System.out.println("Key pressed: " + e.getKeyCode());
}
@Override
public void keyReleased(KeyEvent e) {
System.out.println("Key pressed: ");
}
});

f.setVisible(true);
}
}

4. WindowEvent: Represents window events, such as opening, closing, and resizing.


WindowListener: Handles window events, such as opening, closing, and minimizing.
Methods to implement: void windowOpened(WindowEvent e), void windowClosing(WindowEvent e), void
windowClosed(WindowEvent e), void windowIconified(WindowEvent e), void windowDeiconified(WindowEvent
e), void windowActivated(WindowEvent e), void windowDeactivated(WindowEvent e).
Example:
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.*;

public class Example{


public static void main(String[] args) {
JFrame f = new JFrame("WindowEvent Example");
f.setLayout(null);
f.setSize(300, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent e) {
System.out.println("Window opened");
}
@Override
public void windowClosing(WindowEvent e) {
System.out.println("Window closing");
}
@Override
public void windowClosed(WindowEvent e) {
System.out.println("Window closed");
}
@Override
public void windowIconified(WindowEvent e) {
System.out.println("Window minimized");
}
@Override
public void windowDeiconified(WindowEvent e) {
System.out.println("Window restored");
}
@Override
public void windowActivated(WindowEvent e) {
System.out.println("Window activated");
}
@Override
public void windowDeactivated(WindowEvent e) {
System.out.println("Window deactivated");
}
});

f.setVisible(true);
}
}

Adapter classes: These are abstract classes that provide default (empty) implementations for all methods in an event
listener interface. These classes allow you to override only the methods you are interested in without needing to provide
implementations for all methods in the interface. This simplifies event handling when you only need to handle a subset
of events defined by an interface. Some common adapter classes are:

1. MouseAdapter: Provides default implementations for MouseListener and MouseMotionListener interfaces.


Example:
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;

public class Example{


public static void main(String[] args) {
JFrame f = new JFrame("MouseAdapter Example");
f.setLayout(null);
f.setSize(300, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel l = new JLabel("Click Anywhere");


l.setBounds(100, 100, 100,20);
f.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
System.out.println("Mouse clicked at (" + e.getX() + ", " + e.getY() + ")");
}
});

f.add(l);
f.setVisible(true);
}
}

2. KeyAdapter: Provides default implementations for KeyListener interface.


Example:
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.*;

public class Example{


public static void main(String[] args) {
JFrame f = new JFrame("KeyAdapter Example");
f.setLayout(null);
f.setSize(300, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JTextField t = new JTextField();


t.setBounds(100, 100, 100,20);
t.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
System.out.println("Key typed: " + e.getKeyChar());
}
});

f.add(t);
f.setVisible(true);
}
}

3. WindowAdapter: Provides default implementations for WindowListener interface.


Example:
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;

public class Example{


public static void main(String[] args) {
JFrame f = new JFrame("WindowAdapter Example");
f.setLayout(null);
f.setSize(300, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.out.println("Window closing");
}
});

f.setVisible(true);
}
}
MVC design pattern: The Model-View-Controller (MVC) design pattern is a widely used architectural pattern that
separates an application into three interconnected components:
1. Model: Represents the application's data and business logic.
2. View: Displays the data (the user interface).
3. Controller: Manages user input and updates the Model and View accordingly.
In Java Swing, the MVC design pattern helps to create applications that are more modular, easier to maintain, and
scalable.

Example: login page using MVC design pattern


Model: The Model component represents the data and the logic of the application. For a simple login page, the model
might include user data validation logic.
// Model: User.java
public class User {
private String un;
private String ps;

public User(String username, String password) {


this.un= username;
this.ps= password;
}

public String getUsername() {


return un;
}

public String getPassword() {


return ps;
}

public boolean validate() {


// Simple validation logic for demonstration purposes
return un.equals("admin") && ps.equals("password");
}
}

View: The View component is responsible for displaying the login form and capturing user input.
import javax.swing.*;
import java.awt.*;

public class LoginView extends JFrame {


private JTextField tUser= new JTextField(20);
private JPasswordField tPass= new JPasswordField(20);
private JButton bLogin = new JButton("Login");
private JLabel lMessage = new JLabel();

public LoginView() {
setTitle("Login Page");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);

JPanel panel = new JPanel(new GridLayout(4, 1));


panel.add(new JLabel("Username:"));
panel.add(tUser);
panel.add(new JLabel("Password:"));
panel.add(tPass);
panel.add(bLogin);
panel.add(lMessage);
add(panel);
}

public String getUsername() {


return tUser.getText();
}

public String getPassword() {


return new String(tPass.getPassword());
}

public JButton getLoginButton() {


return bLogin;
}

public void setMessage(String message) {


lMessage.setText(message);
}
}

Controller: The Controller component handles the user interaction, updating the Model and the View accordingly.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LoginController {


private User model;
private LoginView view;

public LoginController(User model, LoginView view) {


this.model = model;
this.view = view;
this.view.getLoginButton().addActionListener(new LoginButtonListener());
}

class LoginButtonListener implements ActionListener {


public void actionPerformed(ActionEvent e) {
model = new User(view.getUsername(), view.getPassword());
if (model.validate()) {
view.setMessage("Login successful!");
} else {
view.setMessage("Invalid username or password.");
}
}
}
}

Main Class: The main class ties everything together.


public class MVCDemo {
public static void main(String[] args) {
User model = new User("", "");
LoginView view = new LoginView();
LoginController controller = new LoginController(model, view);

view.setVisible(true);
}
}
Layout Management: Swing layout management involves arranging components within a container. Swing provides
several layout managers to handle this task, each with different ways of positioning and resizing components. Here’s an
overview of some commonly used layout managers and how to use them.

1. FlowLayout: The FlowLayout is used to arrange the components in a line, one after another (in a flow) much like
lines of text in a paragraph. It is the default layout of panel.
Exmaple:
import java.awt.FlowLayout;
import javax.swing.*;

public class Example{


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

for (int i = 1; i <= 5; i++) {


f.add(new JButton("Button " + i));
}

f.setVisible(true);
}
}

2. BorderLayout: The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of frame or window.
Example:
import java.awt.BorderLayout;
import javax.swing.*;

public class Example{


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

f.add(new JButton("North"), BorderLayout.NORTH);


f.add(new JButton("South"), BorderLayout.SOUTH);
f.add(new JButton("East"), BorderLayout.EAST);
f.add(new JButton("West"), BorderLayout.WEST);
f.add(new JButton("Center"), BorderLayout.CENTER);

f.setVisible(true);
}
}

3. GridLayout: The GridLayout is used to arrange the components in rectangular grid with equal size.
Example:
import java.awt.GridLayout;
import javax.swing.*;

public class Example{


public static void main(String[] args) {
JFrame f = new JFrame("Example");
f.setSize(300, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new GridLayout(3, 2)); // 3 rows, 2 columns

for (int i = 0; i <= 5; i++) {


f.add(new JButton("Button " + i));
}

f.setVisible(true);
}
}

4. BoxLayout: Arranges components either horizontally or vertically.


Example:
import javax.swing.*;

public class Example{


public static void main(String[] args) {
JFrame f = new JFrame("Example");
f.setSize(300, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS)); // Vertical alignment

for (int i = 1; i <= 5; i++) {


f.add(new JButton("Button " + i));
}

f.setVisible(true);
}
}

5. GridBagLayout: A more complex but powerful layout manager that allows for more control over component
placement and resizing.
Example:
import java.awt.*;
import javax.swing.*;

public class Example{


public static void main(String[] args) {
JFrame f = new JFrame("Example");
f.setSize(300, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();

// Button 1
gbc.gridx = 0;
gbc.gridy = 0;
f.add(new JButton("Button 1"), gbc);

// Button 2
gbc.gridx = 1;
gbc.gridy = 0;
f.add(new JButton("Button 2"), gbc);

// Button 3
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 2; // Span two columns
f.add(new JButton("Button 3"), gbc);

f.setVisible(true);
}
}

Basic swing components: Swing provides a variety of basic components that you can use to build a graphical user
interface (GUI) for your application. Here are some of the most commonly used Swing components:

JFrame: The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class. JFrame works like
the main window where components like labels, buttons, textfields are added to create a GUI. Unlike Frame, JFrame has
the option to hide or close the window with the help of setDefaultCloseOperation(int) method.

Example:
import javax.swing.*;
public class Example{
public static void main(String[] args) {
JFrame f = new JFrame("Example");
f.setSize(300, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}

JPanel:
The JPanel is a simplest container class. It provides space in which an application can attach any other component. It
inherits the JComponents class. It doesn't have title bar.
Example:
import java.awt.Color;
import javax.swing.*;

public class Example{


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

JPanel p=new JPanel();


p.setBounds(80,80,300,200); //(x,y,w,h)
p.setBackground(Color.black);
JButton b1=new JButton("Button 1");
b1.setBackground(Color.yellow);
JButton b2=new JButton("Button 2");
b2.setBackground(Color.green);
p.add(b1);
p.add(b2);
f.add(p);

f.setVisible(true);
}
}

JLabel: The object of JLabel class is a component for placing text in a container. It is used to display a single line of read
only text. The text can be changed by an application but a user cannot edit it directly. It inherits JComponent class.
Example:
import java.awt.Color;
import javax.swing.*;

public class Example{


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

JPanel p =new JPanel();


p.setBounds(20,20,300,200);//(x,y,w,h)
p.setBackground(Color.yellow);
f.add(p);
JLabel l;
l=new JLabel("Welcome to My Label");
p.add(l);

f.setVisible(true);
}
}

JTextField: The object of a JTextField class is a text component that allows the editing of a single line text.
It inherits JTextComponent class.
Example:
import javax.swing.*;

public class Example{


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

JTextField t1,t2;
t1=new JTextField("Your name");
t1.setBounds(50,100, 200,30);
t2=new JTextField("Address");
t2.setBounds(50,150, 200,30);
f.add(t1);
f.add(t2);

f.setVisible(true);
}
}

JTextArea: JTextArea is a Swing component used for displaying and editing multiple lines of text. It provides functionality
beyond what is available with JTextField, such as support for multiple lines of text, line wrapping, and more.
Example:
import javax.swing.*;

public class Example{


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

JTextField textField = new JTextField("Enter text here");


textField.setBounds(50, 50, 200, 120);
f.add(textField);

f.setVisible(true);
}
}
JRadioButton: The JRadioButton class is used to create a radio button. It is used to choose one option from multiple
options.
Example:
import javax.swing.*;

public class Example{


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

JRadioButton r1=new JRadioButton("1. Male");


JRadioButton r2=new JRadioButton("2. Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);
bg.add(r2);
f.add(r1);
f.add(r2);

f.setVisible(true);
}
}

JTable: The JTable class is used to display data in tabular form. It is composed of rows and columns.
Example:
import javax.swing.*;

public class Example{


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

String data[][]={ {"1","Aakash","Damak"},


{"2","Raj","Itahari"},
{"3","Priya","Dharan"}};
String title[]={"s.n","NAME","ADDRESS"};
JTable t=new JTable(data,title);
t.setBounds(30,40,200,300);
JScrollPane s = new JScrollPane(t);
f.add(s);

f.setVisible(true);
}
}

JList: The object of JList class represents a list of text items. The list of text items can be set up so that the user can
choose either one item or multiple items. It inherits JComponent class.
Example:
import java.awt.*;
import javax.swing.*;

public class Example{


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

JLabel l = new JLabel();


l.setSize(500,100);
JButton b=new JButton("Show");
b.setBounds(200,150,80,30);

final DefaultListModel<String> l1 = new DefaultListModel<>();


l1.addElement("Nepal");
l1.addElement("India");
l1.addElement("China");
l1.addElement("U.S.A");
final JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list); f.add(b); f.add(l);
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String data = "";
if (list.getSelectedIndex() != -1) {
data = "Coutry Selected is: " + list.getSelectedValue();
l.setText(data);
}
}
});

f.setVisible(true);
}
}

JCheckBox: The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false).
Example:
import javax.swing.*;

public class Example{


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

JCheckBox checkBox1 = new JCheckBox("veg");


checkBox1.setBounds(100,100,50,50);
JCheckBox checkBox2 = new JCheckBox("non-veg");
checkBox2.setBounds(100,150,100,50);
f.add(checkBox1);
f.add(checkBox2);

f.setVisible(true);
}
}

JComboBox:
The object of Choice class is used to show popup menu of choices. Choice selected by user is shown on the top of a
menu. It inherits JComponent class.
Example:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class Example{


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

JTextField l = new JTextField("...");


l.setSize(100,20);
JButton b=new JButton("Show");
b.setBounds(200,100,75,20);
String city[]={"Itahari","Dharan","Kathmandu","Biratnagar","Damak"};
JComboBox cb=new JComboBox(city);
cb.setBounds(50,100,90,20);
f.add(l);
f.add(b);
f.add(cb);
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String data = "My city is " + cb.getItemAt(cb.getSelectedIndex());
l.setText(data);
}
});

f.setVisible(true);
}
}

JDesktopPane: The JDesktopPane class, can be used to create "multi-document" applications. A multi-document
application can have many windows included in it. We do it by making the contentPane in the main window as an
instance of the JDesktopPane class or a subclass.

Internal windows add instances of JInternalFrame to the JdesktopPane instance.


JInternalFrame(String t, boolean resizable, boolean closable, boolean maximizable, boolean iconifiable)
creates a new JInternalFrame with a title, closability, maximizability, iconifiability and resizability specified.
Example:
import java.awt.*;
import javax.swing.*;

class JDesktopPaneDemo extends JFrame {

private JDesktopPane jd = new JDesktopPane();

JDesktopPaneDemo()
{
setTitle("JInternalFrame");
setSize(600,400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setJInternalFrame(jd,"InternalFrame1",30,30);
setJInternalFrame(jd,"InternalFrame2",60,60);
add(jd);
}
void setJInternalFrame(JDesktopPane jd,String name,int loc1,int loc2){
JInternalFrame jn = new JInternalFrame(name,true,true,true,true);
jn.setLayout(new FlowLayout());
jn.setSize(300, 300);
jn.add(new JButton("JButton"));
jn.setLocation(loc2, loc2);
jn.setVisible(true);
jd.add(jn);
}
}

public class Example {

public static void main(String[] args) {


new JDesktopPaneDemo();
}
}

JDialogBox: The JDialog control represents a top level window with a border and a title used to take some form of input
from the user. It inherits the Dialog class. Unlike JFrame, it doesn't have maximize and minimize buttons.
Example:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class Example{


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

JPanel p = new JPanel();


p.setSize(300,300);
JButton b = new JButton("click");
b.setBounds(50,50,80,30);
p.add(b);
f.add(p);
b.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
JDialog d = new JDialog(f, "dialog Box");
JLabel l = new JLabel("This is a dialog box");
d.add(l);
d.setBounds(50,80,200,200);
d.setVisible(true);
}
});

f.setVisible(true);
}
}

JMenu: The JMenuBar class is used to display menubar on the window or frame. It may have several menus. The object
of JMenu class is a pull down menu component which is displayed from the menu bar. It inherits the JMenuItem class.
Example:
import javax.swing.*;

public class Example{


public static void main(String[] args) {
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;

JFrame f = new JFrame("Example");


f.setSize(300, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(null);

JMenuBar mb=new JMenuBar();


menu=new JMenu("Home");
submenu=new JMenu("Other");
i1=new JMenuItem("New");
i2=new JMenuItem("Save");
i3=new JMenuItem("Delete");
i4=new JMenuItem("Copy");
i5=new JMenuItem("Paste");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);

f.setVisible(true);
}
}

You might also like