SlideShare a Scribd company logo
SWING USING  JAVA WITH VARIOUS COMPONENTS
 Swing in java is part of Java foundation class which
is lightweight and platform independent.
 It is used for creating window based applications. It
includes components like button, scroll bar, text
field etc.
 The javax.swing package provides classes for java
swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser
etc. Putting together all these components makes a
graphical user interface
 It is build on top of the AWT API and entirely written
in java.
 Swing API architecture follows loosely based MVC
architecture in the following manner.
 Model represents component's data.
 View represents visual representation of the
component's data.
 Controller takes the input from the user on the view
and reflects the changes in Component's data.
 Swing component has Model as a seperate
element, while the View and Controller part are
clubbed in the User Interface elements. Because of
which, Swing has a pluggable look-and-feel
architecture.
SWING USING  JAVA WITH VARIOUS COMPONENTS
 Events are generated as a result of user
interaction with the graphical user interface
components.
 For example, clicking on a button, moving
the mouse, entering a character through
keyboard, selecting an item from the list, and
scrolling the page are the activities that
causes an event to occur.
 Action Events: These events are triggered by user
actions like button clicks and menu selections. They are
typically used to perform specific tasks or actions.
 Mouse Events: These events are triggered by mouse
actions such as clicks, movements, and drags. They are
useful for creating interactive graphics and handling
mouse-based interactions.
 Key Events: Key events are generated when the user
interacts with the keyboard. You can capture and respond
to keystrokes like key presses and releases.
 Window Events: Window events are associated with the
JFrame and include actions like opening, closing, resizing,
and moving the window. These events are important for
managing the application's user interface.
 Event Listeners: In Swing, event listeners are
responsible for monitoring specific components
and reacting to events. Common event listener
interfaces include ActionListener,
MouseListener, and KeyListener.
 Registering Event Listeners: To handle
events, you need to register listeners with the
components that generate events. For example,
to handle a button click, you would register an
ActionListener with the button.
 Swing Adapters are classes provided by
Swing to simplify event listener
implementation.
 They act as intermediary classes that
provide default implementations for various
listener interfaces, allowing developers to
override only the specific methods they
need.
 Adapter Classes: Swing provides adapter classes for
various listener interfaces. Some common adapter classes
include:
› MouseAdapter: Provides default implementations for mouse-
related events (e.g., mouseClicked, mousePressed).
› KeyAdapter: Offers default implementations for keyboard-
related events (e.g., keyPressed, keyReleased).
› WindowAdapter: Simplifies window-related events (e.g.,
windowOpened, windowClosing).
› FocusAdapter: Deals with focus-related events (e.g.,
focusGained, focusLost).
 Custom Adapter Classes: Developers can also create
their custom adapter classes by extending the adapter
classes provided by Swing and overriding specific
methods as needed.
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class SwingAdapterExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Swing Adapter Example");
JButton button = new JButton("Click Me");
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JOptionPane.showMessageDialog(frame, "Button Clicked!");
}
});
frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
SWING USING  JAVA WITH VARIOUS COMPONENTS
 Swing provides a variety of text components
that allow you to work with text, both for
displaying and editing purposes.
 JTextField - Single-Line Text Input
 JTextField: This component is used for single-line text input fields.
› It's ideal for short text input, such as usernames and search queries.
› You can add event listeners to respond to user input.
 JTextArea - Multi-Line Text Input
 JTextArea: Use this component when you need multi-line text input
and display.
› It's suitable for text fields that may contain paragraphs or longer descriptions.
› You can control scrolling and set word wrap preferences.
 JTextPane and JEditorPane - Rich Text Editing
 JTextPane and JEditorPane: These components support rich text
formatting, including bold, italics, underline, and the display of inline
images.
› JTextPane is designed for plain text with formatting.
› JEditorPane can handle HTML content in addition to plain text.
import javax.swing.*;
import java.awt.*;
public class SwingTextComponentExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Swing Text Components");
JTextArea textArea = new JTextArea(10, 30);
JScrollPane scrollPane = new JScrollPane(textArea);
frame.add(scrollPane);
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
 Swing components are the building blocks of
graphical user interfaces (GUIs) in Java.
They provide a variety of widgets, such as
buttons, text fields, labels, menus, and
tables, that can be used to create rich and
interactive interfaces.
 Swing components are all subclasses of the
JComponent class, which provides a
common set of methods and properties for
all Swing components. For example, all
Swing components can be resized, moved,
and added to other Swing components.
SWING USING  JAVA WITH VARIOUS COMPONENTS
JFrame: JFrame is the top-level container for a Swing application, serving as the
main window for your application.
JPanel: JPanel is a lightweight container used to group and organize other
components, providing layout flexibility.
JButton: JButton is a basic button component that responds to user clicks.
JLabel: JLabel is used for displaying non-editable text or images.
JTextField: JTextField is a single-line text input field for user data entry.
JTextArea: JTextArea is a multi-line text input and display area.
JCheckBox and JRadioButton: These components are used for making
selections in the form of checkboxes and radio buttons.
JComboBox: JComboBox is a drop-down list or combo box for selecting items
from a list.
JSlider: JSlider allows users to select a value from a range by moving a slider.
JTable: JTable is used to display and edit tabular data.
JFileChooser: JFileChooser provides a dialog for selecting files and directories.
import javax.swing.*;
import java.awt.*;
public class SwingComponentsExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Swing Components Example");
JPanel panel = new JPanel();
JButton button = new JButton("Click Me");
JLabel label = new JLabel("Hello, Swing!");
panel.add(label);
panel.add(button);
frame.add(panel);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
 Understanding Containers: In graphical user
interface (GUI) programming, containers are
essential components that hold and organize
other graphical elements, such as buttons,
labels, and text fields. Containers provide
structure and layout for GUI components.
 The Role of Frames: A frame is a top-level
container in Swing. It represents the main
window of a GUI application. Frames serve as
the outermost structure for organizing and
displaying various components.
 JFrame: The JFrame class is used to create the main
application window. It is a top-level container that typically
contains all other GUI components. You can set attributes
such as the window's title, size, and close operation.
 JPanel: The JPanel class is a lightweight container that
can be used within a JFrame or other containers. It is often
used to group related components and provides layout
flexibility.
 Content Pane: The content pane is a container that
resides within the JFrame. It is where most GUI
components are add ed. The content pane allows you
to arrange components using layout managers.
 Creating a Frame: To create a frame, you instantiate a
JFrame object, set its attributes, and add components to it.
 Adding Components: Use the add() method to add
components like buttons, labels, and text fields to
containers, such as the content pane of a JFrame.
 Layout Managers: Layout managers are used to control
the arrangement and positioning of components within
containers. Common layout managers include FlowLayout,
BorderLayout, and GridLayout.
 Event Handling: Implement event listeners to make the
GUI components interactive. For instance, use an
ActionListener to handle button clicks.
import javax.swing.*;
import java.awt.*;
public class SwingContainerExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Swing Container Example");
JPanel panel = new JPanel();
JButton button = new JButton("Click Me");
JLabel label = new JLabel("Hello, Swing!");
panel.add(label);
panel.add(button);
frame.add(panel);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
 Swing tables and trees are essential
components in Java for creating structured,
data-rich graphical user interfaces (GUIs).
Tables are used for displaying data in rows
and columns, while trees are employed for
hierarchical data representation.
SWING USING  JAVA WITH VARIOUS COMPONENTS
 JTable: JTable is a Swing component for
displaying tabular data in a grid format. It's
ideal for structured and spreadsheet-like
data presentation.
 JTree: JTree, on the other hand, is used to
display hierarchical data, such as file
systems, organization charts, or nested
categories.
 Creating a Basic JTable: You can create a simple
JTable by instantiating the JTable class and
providing it with a TableModel to define the data
structure.
 TableModel: The TableModel interface is
responsible for managing and retrieving the data to
be displayed in the JTable. You can use default
implementations like DefaultTableModel or create
custom models.
 Customizing JTable: You can customize JTables
by defining custom cell renderers and editors to
format and handle cell contents.
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class SwingTester {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public SwingTester(){
prepareGUI();
}
public static void main(String[] args){
SwingTester swingControlDemo = new SwingTester();
swingControlDemo.showTableDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(500,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showTableDemo(){
headerLabel.setText("Control in action: JTable");
String[] columnNames = {"Name", "Salary"};
Object[][] data = {
{"Ramesh Raman", 5000},
{"Shabbir Hussein", 7000}
};
JTable table = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setSize(300, 300);
table.setFillsViewportHeight(true);
controlPanel.add(scrollPane);
mainFrame.setVisible(true);
}
SWING USING  JAVA WITH VARIOUS COMPONENTS
 Creating a Basic JTree: JTrees require a
TreeModel to define the structure. You can
create a simple JTree by setting up a
DefaultTreeModel.
 TreeNode: JTree nodes are represented by
the TreeNode interface, allowing for a
flexible hierarchical structure.
 Customizing JTree: You can customize
JTrees by creating custom cell renderers,
editors, and custom icons for nodes.
 We are using the following APIs.
 JTree(root) − To create a tree.
 DefaultMutableTreeNode() − To create a
tree node.
 DefaultMutableTreeNode().add(node) − To
add a tree node to a tree node.

More Related Content

What's hot (20)

PPTX
Constructor in java
Pavith Gunasekara
 
PPTX
String in java
Ideal Eyes Business College
 
PDF
07 java collection
Abhishek Khune
 
PPS
Introduction to class in java
kamal kotecha
 
PDF
Asp.net state management
priya Nithya
 
PPSX
JDBC: java DataBase connectivity
Tanmoy Barman
 
PPTX
Static keyword ppt
Vinod Kumar
 
PPT
Collection Framework in java
CPD INDIA
 
PPT
Java awt
Arati Gadgil
 
PPTX
oops concept in java | object oriented programming in java
CPD INDIA
 
PPTX
this keyword in Java.pptx
ParvizMirzayev2
 
PPTX
Access specifiers(modifiers) in java
HrithikShinde
 
PDF
Learn C# Programming - Variables & Constants
Eng Teong Cheah
 
PPT
Scanner class
M Vishnuvardhan Reddy
 
PPTX
Threads in JAVA
Haldia Institute of Technology
 
PPTX
Event handling
swapnac12
 
PPTX
Inheritance in java
RahulAnanda1
 
PPTX
Interface in java
PhD Research Scholar
 
PDF
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
PPTX
Event In JavaScript
ShahDhruv21
 
Constructor in java
Pavith Gunasekara
 
07 java collection
Abhishek Khune
 
Introduction to class in java
kamal kotecha
 
Asp.net state management
priya Nithya
 
JDBC: java DataBase connectivity
Tanmoy Barman
 
Static keyword ppt
Vinod Kumar
 
Collection Framework in java
CPD INDIA
 
Java awt
Arati Gadgil
 
oops concept in java | object oriented programming in java
CPD INDIA
 
this keyword in Java.pptx
ParvizMirzayev2
 
Access specifiers(modifiers) in java
HrithikShinde
 
Learn C# Programming - Variables & Constants
Eng Teong Cheah
 
Scanner class
M Vishnuvardhan Reddy
 
Event handling
swapnac12
 
Inheritance in java
RahulAnanda1
 
Interface in java
PhD Research Scholar
 
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
Event In JavaScript
ShahDhruv21
 

Similar to SWING USING JAVA WITH VARIOUS COMPONENTS (20)

PPT
14a-gui.ppt
DrDGayathriDevi
 
PPT
Swing and AWT in java
Adil Mehmoood
 
PDF
Swingpre 150616004959-lva1-app6892
renuka gavli
 
PDF
28-GUI application.pptx.pdf
NguynThiThanhTho
 
PDF
Z blue introduction to gui (39023299)
Narayana Swamy
 
PPTX
Unit 4_1.pptx JDBC AND GUI FOR CLIENT SERVER
Salini P
 
PPTX
Chapter 1 swings
Jafar Nesargi
 
PPT
Chap1 1 1
Hemo Chella
 
PPT
Chap1 1.1
Hemo Chella
 
PPT
Graphical User Interface (GUI) - 1
PRN USM
 
PPT
L11cs2110sp13
karan saini
 
PPT
Chapter11 graphical components
Arifa Fatima
 
PPT
Slot04 creating gui
Viên Mai
 
PDF
Java OOP Programming language (Part 7) - Swing
OUM SAOKOSAL
 
PDF
Gui
Sardar Alam
 
PPTX
Computer Programming NC III - Java Swing.pptx
jonathancapitulo2
 
PPT
Java lecture
Nataraj Dg
 
PPT
Swing and Graphical User Interface in Java
babak danyal
 
PPTX
Chapter 11.1
sotlsoc
 
14a-gui.ppt
DrDGayathriDevi
 
Swing and AWT in java
Adil Mehmoood
 
Swingpre 150616004959-lva1-app6892
renuka gavli
 
28-GUI application.pptx.pdf
NguynThiThanhTho
 
Z blue introduction to gui (39023299)
Narayana Swamy
 
Unit 4_1.pptx JDBC AND GUI FOR CLIENT SERVER
Salini P
 
Chapter 1 swings
Jafar Nesargi
 
Chap1 1 1
Hemo Chella
 
Chap1 1.1
Hemo Chella
 
Graphical User Interface (GUI) - 1
PRN USM
 
L11cs2110sp13
karan saini
 
Chapter11 graphical components
Arifa Fatima
 
Slot04 creating gui
Viên Mai
 
Java OOP Programming language (Part 7) - Swing
OUM SAOKOSAL
 
Computer Programming NC III - Java Swing.pptx
jonathancapitulo2
 
Java lecture
Nataraj Dg
 
Swing and Graphical User Interface in Java
babak danyal
 
Chapter 11.1
sotlsoc
 
Ad

Recently uploaded (20)

PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PDF
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PPTX
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
Dimensions of Societal Planning in Commonism
StefanMz
 
Ad

SWING USING JAVA WITH VARIOUS COMPONENTS

  • 2.  Swing in java is part of Java foundation class which is lightweight and platform independent.  It is used for creating window based applications. It includes components like button, scroll bar, text field etc.  The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc. Putting together all these components makes a graphical user interface  It is build on top of the AWT API and entirely written in java.
  • 3.  Swing API architecture follows loosely based MVC architecture in the following manner.  Model represents component's data.  View represents visual representation of the component's data.  Controller takes the input from the user on the view and reflects the changes in Component's data.  Swing component has Model as a seperate element, while the View and Controller part are clubbed in the User Interface elements. Because of which, Swing has a pluggable look-and-feel architecture.
  • 5.  Events are generated as a result of user interaction with the graphical user interface components.  For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from the list, and scrolling the page are the activities that causes an event to occur.
  • 6.  Action Events: These events are triggered by user actions like button clicks and menu selections. They are typically used to perform specific tasks or actions.  Mouse Events: These events are triggered by mouse actions such as clicks, movements, and drags. They are useful for creating interactive graphics and handling mouse-based interactions.  Key Events: Key events are generated when the user interacts with the keyboard. You can capture and respond to keystrokes like key presses and releases.  Window Events: Window events are associated with the JFrame and include actions like opening, closing, resizing, and moving the window. These events are important for managing the application's user interface.
  • 7.  Event Listeners: In Swing, event listeners are responsible for monitoring specific components and reacting to events. Common event listener interfaces include ActionListener, MouseListener, and KeyListener.  Registering Event Listeners: To handle events, you need to register listeners with the components that generate events. For example, to handle a button click, you would register an ActionListener with the button.
  • 8.  Swing Adapters are classes provided by Swing to simplify event listener implementation.  They act as intermediary classes that provide default implementations for various listener interfaces, allowing developers to override only the specific methods they need.
  • 9.  Adapter Classes: Swing provides adapter classes for various listener interfaces. Some common adapter classes include: › MouseAdapter: Provides default implementations for mouse- related events (e.g., mouseClicked, mousePressed). › KeyAdapter: Offers default implementations for keyboard- related events (e.g., keyPressed, keyReleased). › WindowAdapter: Simplifies window-related events (e.g., windowOpened, windowClosing). › FocusAdapter: Deals with focus-related events (e.g., focusGained, focusLost).  Custom Adapter Classes: Developers can also create their custom adapter classes by extending the adapter classes provided by Swing and overriding specific methods as needed.
  • 10. import javax.swing.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class SwingAdapterExample { public static void main(String[] args) { JFrame frame = new JFrame("Swing Adapter Example"); JButton button = new JButton("Click Me"); button.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { JOptionPane.showMessageDialog(frame, "Button Clicked!"); } }); frame.add(button); frame.setSize(300, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
  • 12.  Swing provides a variety of text components that allow you to work with text, both for displaying and editing purposes.
  • 13.  JTextField - Single-Line Text Input  JTextField: This component is used for single-line text input fields. › It's ideal for short text input, such as usernames and search queries. › You can add event listeners to respond to user input.  JTextArea - Multi-Line Text Input  JTextArea: Use this component when you need multi-line text input and display. › It's suitable for text fields that may contain paragraphs or longer descriptions. › You can control scrolling and set word wrap preferences.  JTextPane and JEditorPane - Rich Text Editing  JTextPane and JEditorPane: These components support rich text formatting, including bold, italics, underline, and the display of inline images. › JTextPane is designed for plain text with formatting. › JEditorPane can handle HTML content in addition to plain text.
  • 14. import javax.swing.*; import java.awt.*; public class SwingTextComponentExample { public static void main(String[] args) { JFrame frame = new JFrame("Swing Text Components"); JTextArea textArea = new JTextArea(10, 30); JScrollPane scrollPane = new JScrollPane(textArea); frame.add(scrollPane); frame.setSize(400, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
  • 15.  Swing components are the building blocks of graphical user interfaces (GUIs) in Java. They provide a variety of widgets, such as buttons, text fields, labels, menus, and tables, that can be used to create rich and interactive interfaces.
  • 16.  Swing components are all subclasses of the JComponent class, which provides a common set of methods and properties for all Swing components. For example, all Swing components can be resized, moved, and added to other Swing components.
  • 18. JFrame: JFrame is the top-level container for a Swing application, serving as the main window for your application. JPanel: JPanel is a lightweight container used to group and organize other components, providing layout flexibility. JButton: JButton is a basic button component that responds to user clicks. JLabel: JLabel is used for displaying non-editable text or images. JTextField: JTextField is a single-line text input field for user data entry. JTextArea: JTextArea is a multi-line text input and display area. JCheckBox and JRadioButton: These components are used for making selections in the form of checkboxes and radio buttons. JComboBox: JComboBox is a drop-down list or combo box for selecting items from a list. JSlider: JSlider allows users to select a value from a range by moving a slider. JTable: JTable is used to display and edit tabular data. JFileChooser: JFileChooser provides a dialog for selecting files and directories.
  • 19. import javax.swing.*; import java.awt.*; public class SwingComponentsExample { public static void main(String[] args) { JFrame frame = new JFrame("Swing Components Example"); JPanel panel = new JPanel(); JButton button = new JButton("Click Me"); JLabel label = new JLabel("Hello, Swing!"); panel.add(label); panel.add(button); frame.add(panel); frame.setSize(300, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
  • 20.  Understanding Containers: In graphical user interface (GUI) programming, containers are essential components that hold and organize other graphical elements, such as buttons, labels, and text fields. Containers provide structure and layout for GUI components.  The Role of Frames: A frame is a top-level container in Swing. It represents the main window of a GUI application. Frames serve as the outermost structure for organizing and displaying various components.
  • 21.  JFrame: The JFrame class is used to create the main application window. It is a top-level container that typically contains all other GUI components. You can set attributes such as the window's title, size, and close operation.  JPanel: The JPanel class is a lightweight container that can be used within a JFrame or other containers. It is often used to group related components and provides layout flexibility.  Content Pane: The content pane is a container that resides within the JFrame. It is where most GUI components are add ed. The content pane allows you to arrange components using layout managers.
  • 22.  Creating a Frame: To create a frame, you instantiate a JFrame object, set its attributes, and add components to it.  Adding Components: Use the add() method to add components like buttons, labels, and text fields to containers, such as the content pane of a JFrame.  Layout Managers: Layout managers are used to control the arrangement and positioning of components within containers. Common layout managers include FlowLayout, BorderLayout, and GridLayout.  Event Handling: Implement event listeners to make the GUI components interactive. For instance, use an ActionListener to handle button clicks.
  • 23. import javax.swing.*; import java.awt.*; public class SwingContainerExample { public static void main(String[] args) { JFrame frame = new JFrame("Swing Container Example"); JPanel panel = new JPanel(); JButton button = new JButton("Click Me"); JLabel label = new JLabel("Hello, Swing!"); panel.add(label); panel.add(button); frame.add(panel); frame.setSize(300, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
  • 24.  Swing tables and trees are essential components in Java for creating structured, data-rich graphical user interfaces (GUIs). Tables are used for displaying data in rows and columns, while trees are employed for hierarchical data representation.
  • 26.  JTable: JTable is a Swing component for displaying tabular data in a grid format. It's ideal for structured and spreadsheet-like data presentation.  JTree: JTree, on the other hand, is used to display hierarchical data, such as file systems, organization charts, or nested categories.
  • 27.  Creating a Basic JTable: You can create a simple JTable by instantiating the JTable class and providing it with a TableModel to define the data structure.  TableModel: The TableModel interface is responsible for managing and retrieving the data to be displayed in the JTable. You can use default implementations like DefaultTableModel or create custom models.  Customizing JTable: You can customize JTables by defining custom cell renderers and editors to format and handle cell contents.
  • 28. import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; public class SwingTester { private JFrame mainFrame; private JLabel headerLabel; private JLabel statusLabel; private JPanel controlPanel;
  • 29. public SwingTester(){ prepareGUI(); } public static void main(String[] args){ SwingTester swingControlDemo = new SwingTester(); swingControlDemo.showTableDemo(); } private void prepareGUI(){ mainFrame = new JFrame("Java Swing Examples"); mainFrame.setSize(500,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new JLabel("", JLabel.CENTER); statusLabel = new JLabel("",JLabel.CENTER); statusLabel.setSize(350,100);
  • 30. controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showTableDemo(){ headerLabel.setText("Control in action: JTable"); String[] columnNames = {"Name", "Salary"}; Object[][] data = { {"Ramesh Raman", 5000}, {"Shabbir Hussein", 7000} }; JTable table = new JTable(data, columnNames); JScrollPane scrollPane = new JScrollPane(table); scrollPane.setSize(300, 300); table.setFillsViewportHeight(true); controlPanel.add(scrollPane); mainFrame.setVisible(true); }
  • 32.  Creating a Basic JTree: JTrees require a TreeModel to define the structure. You can create a simple JTree by setting up a DefaultTreeModel.  TreeNode: JTree nodes are represented by the TreeNode interface, allowing for a flexible hierarchical structure.  Customizing JTree: You can customize JTrees by creating custom cell renderers, editors, and custom icons for nodes.
  • 33.  We are using the following APIs.  JTree(root) − To create a tree.  DefaultMutableTreeNode() − To create a tree node.  DefaultMutableTreeNode().add(node) − To add a tree node to a tree node.