SlideShare a Scribd company logo
1 of 30
Download to read offline
Java Programming – Swing
Oum Saokosal
Master’s Degree in information systems,Jeonju
University,South Korea
012 252 752 / 070 252 752
oumsaokosal@gmail.com
Contact Me
• Tel: 012 252 752 / 070 252 752
• Email: oumsaokosal@gmail.com
• FB Page: https://facebook.com/kosalgeek
• PPT: http://www.slideshare.net/oumsaokosal
• YouTube: https://www.youtube.com/user/oumsaokosal
• Twitter: https://twitter.com/okosal
• Web: http://kosalgeek.com
Swing Components
• Swing is a collection of libraries that contains
primitive widgets or controls used for designing
GraphicalUser Interfaces(GUIs).
• Commonly used classes in javax.swing package:
• JButton, JTextBox, JTextArea, JPanel,
JFrame, JMenu, JSlider, JLabel, JIcon, …
• There are many, many such classesto do anything
imaginablewithGUIs
• Here we onlystudy the basic architecture and do
simpleexamples
Swing components, cont.
• Each componentis a Java classwith a fairlyextensive
inheritencyhierarchy:
Object
Component
Container
JComponent
JPanel
Window
Frame
JFrame
Using Swing Components
•Very simple, just create object from
appropriate class – examples:
• JButton but = new JButton();
• JTextField text = new JTextField();
• JTextArea text = new JTextArea();
• JLabel lab = new JLabel();
•Many more classes. Don’t need to know every
one to get started.
Adding components
• Once a component is created, it can be added
to a container by calling the container’s add
method:
Container cp = getContentPane();
cp.add(new JButton(“cancel”));
cp.add(new JButton(“go”));
How these are laid out is determined by the layout
manager.
This is required
Laying out components
•Not so difficult but takes a little practice
•Do not use absolute positioning – not
very portable, does not resize well, etc.
Laying out components
• Use layout managers – basically tells form how
to align components when they’re added.
• Each Container has a layout manager
associated with it.
• A JPanel is a Container– to have different
layout managers associated with different
parts of a form, tile with JPanels and set the
desired layout manager for each JPanel, then
add components directly to panels.
Layout Managers
•Java comes with 7 or 8. Most common
and easiest to use are
• FlowLayout
• BorderLayout
• GridLayout
•Using just these three it is possible to
attain fairly precise layout for most
simple applications.
Setting layout managers
• Very easy to associate a layout manager with a
component. Simply call the setLayout method
on theContainer:
JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout(FlowLayout.LEFT));
JPanel p2 = new JPanel();
p2.setLayout(new BorderLayout());
As Componentsare added to the container,the layout
manager determinestheir size and positioning.
Event handling
What are events?
• All componentscan listen for one or more events.
• Typical examples are:
• Mouse movements
• Mouse clicks
• Hitting any key
• Hitting return key
• etc.
• Telling the GUI what to do when a particular event
occurs is the role of the event handler.
ActionEvent
• In Java, most components have a special
event called an ActionEvent.
• This is loosely speaking the most common
or canonical event for that component.
• A good example is a click for a button.
• To have any component listen for
ActionEvents, you must register the
component with anActionListener. e.g.
button.addActionListener(new MyAL());
Delegation, cont.
• This is referred to as the Delegation Model.
• When you register an ActionListener with a
component, you must pass it the class
which will handle the event – that is, do the
work when the event is triggered.
• For anActionEvent, this class must
implement the ActionListener interface.
• This is simple a way of guaranteeing that
the actionPerformed method is defined.
actionPerformed
• The actionPerformed method has the following
signature:
void actionPerformed(ActionEvent)
• The object of type ActionEvent passed to the
event handler is used to query information about
the event.
• Some common methods are:
• getSource()
• object reference to component generating event
• getActionCommand()
• some text associated with event (text on button, etc).
actionPerformed, cont.
•These methods are particularly useful
when using one eventhandler for
multiple components.
Simplest GUI
import javax.swing.JFrame;
class SimpleGUI extends JFrame{
SimpleGUI(){
setSize(400,400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
System.out.println("main thread continues");
}
}
Another Simple GUI
import javax.swing.*;
class SimpleGUI extends JFrame{
SimpleGUI(){
setSize(400,400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton but1 = new JButton(“Click me”);
Container cp = getContentPane();//must do this
cp.add(but1);
}
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
System.out.println("main thread continues");
}
}
Add Layout Manager
import javax.swing.*; import java.awt.*;
class SimpleGUI extends JFrame{
SimpleGUI(){
setSize(400, 400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton but1 = new JButton("Click me");
Container cp = getContentPane();//must do this
cp.setLayout(new FlowLayout(FlowLayout.CENTER));
cp.add(but1);
}
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
System.out.println("main thread continues");
}
}
Add call to event handler
import javax.swing.*; import java.awt.*;
class SimpleGUI extends JFrame{
SimpleGUI(){
setSize(400,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton but1 = new JButton("Click me");
Container cp = getContentPane();
cp.setLayout(new FlowLayout(FlowLayout.CENTER);
but1.addActionListener(new MyActionListener());
cp.add(but1);
}
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
}
}
Event Handler Code
class MyActionListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
JOptionPane.showMessageDialog(
"I got clicked",
null
);
}
}
Add second button/event
class SimpleGUI extends JFrame{
SimpleGUI(){
JButton but1 = new Jbutton("Click me");
JButton but2 = new JButton(“exit”);
MyActionListener al = new MyActionListener();
but1.addActionListener(al);
but2.addActionListener(al);
cp.add(but1);
cp.add(but2);
}
}
How to distinguish events –Less
good way
class MyActionListener implents ActionListener{
public void actionPerformed(ActionEvent ae){
if (ae.getActionCommand().equals("Exit"){
System.exit(1);
}
else if (ae.getActionCommand().equals("Click me"){
JOptionPane.showMessageDialog(null, "I’m clicked");
}
}
}
Good way
class MyActionListener implents ActionListener{
public void actionPerformed(ActionEvent ae){
if (ae.getSource() == but2){
System.exit(1);
}
else if (ae.getSource() == but1){
JOptionPane.showMessageDialog(
null, "I’m clicked");
}
}
Question: How are but1, but2 brought into scope to do this?
Question:Why is this better?

More Related Content

Viewers also liked

Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+javaYe Win
 
Measuring And Defining The Experience Of Immersion In Games
Measuring And  Defining The  Experience Of  Immersion In GamesMeasuring And  Defining The  Experience Of  Immersion In Games
Measuring And Defining The Experience Of Immersion In GamesOUM SAOKOSAL
 
ITS (Intelligent Teleportation System)
ITS (Intelligent Teleportation System)ITS (Intelligent Teleportation System)
ITS (Intelligent Teleportation System)OUM SAOKOSAL
 
Terminology In Telecommunication
Terminology In TelecommunicationTerminology In Telecommunication
Terminology In TelecommunicationOUM SAOKOSAL
 
Chapter 9 Interface
Chapter 9 InterfaceChapter 9 Interface
Chapter 9 InterfaceOUM SAOKOSAL
 
Kimchi Questionnaire
Kimchi QuestionnaireKimchi Questionnaire
Kimchi QuestionnaireOUM SAOKOSAL
 
Actionscript 3 - Session 7 Other Note
Actionscript 3 - Session 7 Other NoteActionscript 3 - Session 7 Other Note
Actionscript 3 - Session 7 Other NoteOUM SAOKOSAL
 
09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)Oum Saokosal
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 InheritanceOUM SAOKOSAL
 
Rayleigh Fading Channel In Mobile Digital Communication System
Rayleigh Fading Channel In Mobile Digital Communication SystemRayleigh Fading Channel In Mobile Digital Communication System
Rayleigh Fading Channel In Mobile Digital Communication SystemOUM SAOKOSAL
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Matt Harrison
 
Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)Chia-Chi Chang
 
Java OOP Programming language (Part 1) - Introduction to Java
Java OOP Programming language (Part 1) - Introduction to JavaJava OOP Programming language (Part 1) - Introduction to Java
Java OOP Programming language (Part 1) - Introduction to JavaOUM SAOKOSAL
 
Meetup Python Nantes - les tests en python
Meetup Python Nantes - les tests en pythonMeetup Python Nantes - les tests en python
Meetup Python Nantes - les tests en pythonArthur Lutz
 
Operator Overloading
Operator Overloading  Operator Overloading
Operator Overloading Sardar Alam
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MoreMatt Harrison
 

Viewers also liked (20)

Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+java
 
Measuring And Defining The Experience Of Immersion In Games
Measuring And  Defining The  Experience Of  Immersion In GamesMeasuring And  Defining The  Experience Of  Immersion In Games
Measuring And Defining The Experience Of Immersion In Games
 
Chapter 7 String
Chapter 7 StringChapter 7 String
Chapter 7 String
 
ITS (Intelligent Teleportation System)
ITS (Intelligent Teleportation System)ITS (Intelligent Teleportation System)
ITS (Intelligent Teleportation System)
 
Terminology In Telecommunication
Terminology In TelecommunicationTerminology In Telecommunication
Terminology In Telecommunication
 
Chapter 9 Interface
Chapter 9 InterfaceChapter 9 Interface
Chapter 9 Interface
 
Tutorial 1
Tutorial 1Tutorial 1
Tutorial 1
 
Kimchi Questionnaire
Kimchi QuestionnaireKimchi Questionnaire
Kimchi Questionnaire
 
Actionscript 3 - Session 7 Other Note
Actionscript 3 - Session 7 Other NoteActionscript 3 - Session 7 Other Note
Actionscript 3 - Session 7 Other Note
 
09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
 
Rayleigh Fading Channel In Mobile Digital Communication System
Rayleigh Fading Channel In Mobile Digital Communication SystemRayleigh Fading Channel In Mobile Digital Communication System
Rayleigh Fading Channel In Mobile Digital Communication System
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
 
Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)
 
Introduction to Advanced Javascript
Introduction to Advanced JavascriptIntroduction to Advanced Javascript
Introduction to Advanced Javascript
 
Java OOP Programming language (Part 1) - Introduction to Java
Java OOP Programming language (Part 1) - Introduction to JavaJava OOP Programming language (Part 1) - Introduction to Java
Java OOP Programming language (Part 1) - Introduction to Java
 
Python - Lecture 1
Python - Lecture 1Python - Lecture 1
Python - Lecture 1
 
Meetup Python Nantes - les tests en python
Meetup Python Nantes - les tests en pythonMeetup Python Nantes - les tests en python
Meetup Python Nantes - les tests en python
 
Operator Overloading
Operator Overloading  Operator Overloading
Operator Overloading
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
 

Similar to Java OOP Programming language (Part 7) - Swing

Java Swing Handson Session (1).ppt
Java Swing Handson Session (1).pptJava Swing Handson Session (1).ppt
Java Swing Handson Session (1).pptssuser076380
 
Complete java swing
Complete java swingComplete java swing
Complete java swingjehan1987
 
The java swing_tutorial
The java swing_tutorialThe java swing_tutorial
The java swing_tutorialsumitjoshi01
 
Java GUI Programming for beginners-graphics.pdf
Java GUI Programming for beginners-graphics.pdfJava GUI Programming for beginners-graphics.pdf
Java GUI Programming for beginners-graphics.pdfPBMaverick
 
mobile development with androiddfdgdfhdgfdhf.pptx
mobile development with androiddfdgdfhdgfdhf.pptxmobile development with androiddfdgdfhdgfdhf.pptx
mobile development with androiddfdgdfhdgfdhf.pptxNgLQun
 
ITFT - Java Coding
ITFT - Java CodingITFT - Java Coding
ITFT - Java CodingBlossom Sood
 
How to create a joomla component from scratch
How to create a joomla component from scratchHow to create a joomla component from scratch
How to create a joomla component from scratchTim Plummer
 
13 gui development
13 gui development13 gui development
13 gui developmentAPU
 
J2ME Lwuit, Storage & Connections (Ft Prasanjit Dey)
J2ME Lwuit, Storage & Connections (Ft   Prasanjit Dey)J2ME Lwuit, Storage & Connections (Ft   Prasanjit Dey)
J2ME Lwuit, Storage & Connections (Ft Prasanjit Dey)Fafadia Tech
 
Programming Java GUI using SWING, Event Handling
Programming Java GUI using SWING, Event HandlingProgramming Java GUI using SWING, Event Handling
Programming Java GUI using SWING, Event HandlingJadavsejal
 
Making the most of your Test Suite
Making the most of your Test SuiteMaking the most of your Test Suite
Making the most of your Test Suiteericholscher
 
jQuery 1.3 and jQuery UI
jQuery 1.3 and jQuery UIjQuery 1.3 and jQuery UI
jQuery 1.3 and jQuery UIjeresig
 

Similar to Java OOP Programming language (Part 7) - Swing (20)

14a-gui.ppt
14a-gui.ppt14a-gui.ppt
14a-gui.ppt
 
Java Swing Handson Session (1).ppt
Java Swing Handson Session (1).pptJava Swing Handson Session (1).ppt
Java Swing Handson Session (1).ppt
 
Gui
GuiGui
Gui
 
Swing
SwingSwing
Swing
 
Complete java swing
Complete java swingComplete java swing
Complete java swing
 
The java swing_tutorial
The java swing_tutorialThe java swing_tutorial
The java swing_tutorial
 
The java rogramming swing _tutorial for beinners(java programming language)
The java rogramming swing _tutorial for beinners(java programming language)The java rogramming swing _tutorial for beinners(java programming language)
The java rogramming swing _tutorial for beinners(java programming language)
 
Basic swing
Basic swingBasic swing
Basic swing
 
Java GUI Programming for beginners-graphics.pdf
Java GUI Programming for beginners-graphics.pdfJava GUI Programming for beginners-graphics.pdf
Java GUI Programming for beginners-graphics.pdf
 
mobile development with androiddfdgdfhdgfdhf.pptx
mobile development with androiddfdgdfhdgfdhf.pptxmobile development with androiddfdgdfhdgfdhf.pptx
mobile development with androiddfdgdfhdgfdhf.pptx
 
ITFT - Java Coding
ITFT - Java CodingITFT - Java Coding
ITFT - Java Coding
 
11basic Swing
11basic Swing11basic Swing
11basic Swing
 
How to create a joomla component from scratch
How to create a joomla component from scratchHow to create a joomla component from scratch
How to create a joomla component from scratch
 
13 gui development
13 gui development13 gui development
13 gui development
 
J2ME Lwuit, Storage & Connections (Ft Prasanjit Dey)
J2ME Lwuit, Storage & Connections (Ft   Prasanjit Dey)J2ME Lwuit, Storage & Connections (Ft   Prasanjit Dey)
J2ME Lwuit, Storage & Connections (Ft Prasanjit Dey)
 
Programming Java GUI using SWING, Event Handling
Programming Java GUI using SWING, Event HandlingProgramming Java GUI using SWING, Event Handling
Programming Java GUI using SWING, Event Handling
 
Making the most of your Test Suite
Making the most of your Test SuiteMaking the most of your Test Suite
Making the most of your Test Suite
 
Tuto jtatoo
Tuto jtatooTuto jtatoo
Tuto jtatoo
 
jQuery 1.3 and jQuery UI
jQuery 1.3 and jQuery UIjQuery 1.3 and jQuery UI
jQuery 1.3 and jQuery UI
 
Selenium Training in Chennai
Selenium Training in ChennaiSelenium Training in Chennai
Selenium Training in Chennai
 

More from OUM SAOKOSAL

Class Diagram | OOP and Design Patterns by Oum Saokosal
Class Diagram | OOP and Design Patterns by Oum SaokosalClass Diagram | OOP and Design Patterns by Oum Saokosal
Class Diagram | OOP and Design Patterns by Oum SaokosalOUM SAOKOSAL
 
Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectOUM SAOKOSAL
 
Aggregate rank bringing order to web sites
Aggregate rank  bringing order to web sitesAggregate rank  bringing order to web sites
Aggregate rank bringing order to web sitesOUM SAOKOSAL
 
How to succeed in graduate school
How to succeed in graduate schoolHow to succeed in graduate school
How to succeed in graduate schoolOUM SAOKOSAL
 
Data preparation for mining world wide web browsing patterns (1999)
Data preparation for mining world wide web browsing patterns (1999)Data preparation for mining world wide web browsing patterns (1999)
Data preparation for mining world wide web browsing patterns (1999)OUM SAOKOSAL
 
Consumer acceptance of online banking an extension of the technology accepta...
Consumer acceptance of online banking  an extension of the technology accepta...Consumer acceptance of online banking  an extension of the technology accepta...
Consumer acceptance of online banking an extension of the technology accepta...OUM SAOKOSAL
 
When Do People Help
When Do People HelpWhen Do People Help
When Do People HelpOUM SAOKOSAL
 
Correlation Example
Correlation ExampleCorrelation Example
Correlation ExampleOUM SAOKOSAL
 
Path Spss Amos (1)
Path Spss Amos (1)Path Spss Amos (1)
Path Spss Amos (1)OUM SAOKOSAL
 
How To Succeed In Graduate School
How To Succeed In Graduate SchoolHow To Succeed In Graduate School
How To Succeed In Graduate SchoolOUM SAOKOSAL
 
Actionscript 3 - Session 4 Core Concept
Actionscript 3 - Session 4 Core ConceptActionscript 3 - Session 4 Core Concept
Actionscript 3 - Session 4 Core ConceptOUM SAOKOSAL
 
Actionscript 3 - Session 3 Action Script And Flash
Actionscript 3 - Session 3 Action Script And FlashActionscript 3 - Session 3 Action Script And Flash
Actionscript 3 - Session 3 Action Script And FlashOUM SAOKOSAL
 
Actionscript 3 - Session 1 Introduction To As 3
Actionscript 3 - Session 1 Introduction To As 3Actionscript 3 - Session 1 Introduction To As 3
Actionscript 3 - Session 1 Introduction To As 3OUM SAOKOSAL
 
Actionscript 3 - Session 5 The Display Api And The Display List
Actionscript 3 - Session 5 The Display Api And The Display ListActionscript 3 - Session 5 The Display Api And The Display List
Actionscript 3 - Session 5 The Display Api And The Display ListOUM SAOKOSAL
 
Actionscript 3 - Session 6 Interactivity
Actionscript 3 - Session 6 InteractivityActionscript 3 - Session 6 Interactivity
Actionscript 3 - Session 6 InteractivityOUM SAOKOSAL
 

More from OUM SAOKOSAL (20)

Class Diagram | OOP and Design Patterns by Oum Saokosal
Class Diagram | OOP and Design Patterns by Oum SaokosalClass Diagram | OOP and Design Patterns by Oum Saokosal
Class Diagram | OOP and Design Patterns by Oum Saokosal
 
Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and Object
 
Aggregate rank bringing order to web sites
Aggregate rank  bringing order to web sitesAggregate rank  bringing order to web sites
Aggregate rank bringing order to web sites
 
How to succeed in graduate school
How to succeed in graduate schoolHow to succeed in graduate school
How to succeed in graduate school
 
Google
GoogleGoogle
Google
 
E miner
E minerE miner
E miner
 
Data preparation for mining world wide web browsing patterns (1999)
Data preparation for mining world wide web browsing patterns (1999)Data preparation for mining world wide web browsing patterns (1999)
Data preparation for mining world wide web browsing patterns (1999)
 
Consumer acceptance of online banking an extension of the technology accepta...
Consumer acceptance of online banking  an extension of the technology accepta...Consumer acceptance of online banking  an extension of the technology accepta...
Consumer acceptance of online banking an extension of the technology accepta...
 
When Do People Help
When Do People HelpWhen Do People Help
When Do People Help
 
Mc Nemar
Mc NemarMc Nemar
Mc Nemar
 
Correlation Example
Correlation ExampleCorrelation Example
Correlation Example
 
Sem Ski Amos
Sem Ski AmosSem Ski Amos
Sem Ski Amos
 
Sem+Essentials
Sem+EssentialsSem+Essentials
Sem+Essentials
 
Path Spss Amos (1)
Path Spss Amos (1)Path Spss Amos (1)
Path Spss Amos (1)
 
How To Succeed In Graduate School
How To Succeed In Graduate SchoolHow To Succeed In Graduate School
How To Succeed In Graduate School
 
Actionscript 3 - Session 4 Core Concept
Actionscript 3 - Session 4 Core ConceptActionscript 3 - Session 4 Core Concept
Actionscript 3 - Session 4 Core Concept
 
Actionscript 3 - Session 3 Action Script And Flash
Actionscript 3 - Session 3 Action Script And FlashActionscript 3 - Session 3 Action Script And Flash
Actionscript 3 - Session 3 Action Script And Flash
 
Actionscript 3 - Session 1 Introduction To As 3
Actionscript 3 - Session 1 Introduction To As 3Actionscript 3 - Session 1 Introduction To As 3
Actionscript 3 - Session 1 Introduction To As 3
 
Actionscript 3 - Session 5 The Display Api And The Display List
Actionscript 3 - Session 5 The Display Api And The Display ListActionscript 3 - Session 5 The Display Api And The Display List
Actionscript 3 - Session 5 The Display Api And The Display List
 
Actionscript 3 - Session 6 Interactivity
Actionscript 3 - Session 6 InteractivityActionscript 3 - Session 6 Interactivity
Actionscript 3 - Session 6 Interactivity
 

Recently uploaded

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 

Recently uploaded (20)

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 

Java OOP Programming language (Part 7) - Swing

  • 1. Java Programming – Swing Oum Saokosal Master’s Degree in information systems,Jeonju University,South Korea 012 252 752 / 070 252 752 oumsaokosal@gmail.com
  • 2. Contact Me • Tel: 012 252 752 / 070 252 752 • Email: oumsaokosal@gmail.com • FB Page: https://facebook.com/kosalgeek • PPT: http://www.slideshare.net/oumsaokosal • YouTube: https://www.youtube.com/user/oumsaokosal • Twitter: https://twitter.com/okosal • Web: http://kosalgeek.com
  • 3. Swing Components • Swing is a collection of libraries that contains primitive widgets or controls used for designing GraphicalUser Interfaces(GUIs). • Commonly used classes in javax.swing package: • JButton, JTextBox, JTextArea, JPanel, JFrame, JMenu, JSlider, JLabel, JIcon, … • There are many, many such classesto do anything imaginablewithGUIs • Here we onlystudy the basic architecture and do simpleexamples
  • 4. Swing components, cont. • Each componentis a Java classwith a fairlyextensive inheritencyhierarchy: Object Component Container JComponent JPanel Window Frame JFrame
  • 5. Using Swing Components •Very simple, just create object from appropriate class – examples: • JButton but = new JButton(); • JTextField text = new JTextField(); • JTextArea text = new JTextArea(); • JLabel lab = new JLabel(); •Many more classes. Don’t need to know every one to get started.
  • 6. Adding components • Once a component is created, it can be added to a container by calling the container’s add method: Container cp = getContentPane(); cp.add(new JButton(“cancel”)); cp.add(new JButton(“go”)); How these are laid out is determined by the layout manager. This is required
  • 7. Laying out components •Not so difficult but takes a little practice •Do not use absolute positioning – not very portable, does not resize well, etc.
  • 8. Laying out components • Use layout managers – basically tells form how to align components when they’re added. • Each Container has a layout manager associated with it. • A JPanel is a Container– to have different layout managers associated with different parts of a form, tile with JPanels and set the desired layout manager for each JPanel, then add components directly to panels.
  • 9. Layout Managers •Java comes with 7 or 8. Most common and easiest to use are • FlowLayout • BorderLayout • GridLayout •Using just these three it is possible to attain fairly precise layout for most simple applications.
  • 10. Setting layout managers • Very easy to associate a layout manager with a component. Simply call the setLayout method on theContainer: JPanel p1 = new JPanel(); p1.setLayout(new FlowLayout(FlowLayout.LEFT)); JPanel p2 = new JPanel(); p2.setLayout(new BorderLayout()); As Componentsare added to the container,the layout manager determinestheir size and positioning.
  • 12. What are events? • All componentscan listen for one or more events. • Typical examples are: • Mouse movements • Mouse clicks • Hitting any key • Hitting return key • etc. • Telling the GUI what to do when a particular event occurs is the role of the event handler.
  • 13. ActionEvent • In Java, most components have a special event called an ActionEvent. • This is loosely speaking the most common or canonical event for that component. • A good example is a click for a button. • To have any component listen for ActionEvents, you must register the component with anActionListener. e.g. button.addActionListener(new MyAL());
  • 14. Delegation, cont. • This is referred to as the Delegation Model. • When you register an ActionListener with a component, you must pass it the class which will handle the event – that is, do the work when the event is triggered. • For anActionEvent, this class must implement the ActionListener interface. • This is simple a way of guaranteeing that the actionPerformed method is defined.
  • 15. actionPerformed • The actionPerformed method has the following signature: void actionPerformed(ActionEvent) • The object of type ActionEvent passed to the event handler is used to query information about the event. • Some common methods are: • getSource() • object reference to component generating event • getActionCommand() • some text associated with event (text on button, etc).
  • 16. actionPerformed, cont. •These methods are particularly useful when using one eventhandler for multiple components.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23. Simplest GUI import javax.swing.JFrame; class SimpleGUI extends JFrame{ SimpleGUI(){ setSize(400,400); //set frames size in pixels setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main(String[] args){ SimpleGUI gui = new SimpleGUI(); System.out.println("main thread continues"); } }
  • 24. Another Simple GUI import javax.swing.*; class SimpleGUI extends JFrame{ SimpleGUI(){ setSize(400,400); //set frames size in pixels setDefaultCloseOperation(EXIT_ON_CLOSE); JButton but1 = new JButton(“Click me”); Container cp = getContentPane();//must do this cp.add(but1); } public static void main(String[] args){ SimpleGUI gui = new SimpleGUI(); System.out.println("main thread continues"); } }
  • 25. Add Layout Manager import javax.swing.*; import java.awt.*; class SimpleGUI extends JFrame{ SimpleGUI(){ setSize(400, 400); //set frames size in pixels setDefaultCloseOperation(EXIT_ON_CLOSE); JButton but1 = new JButton("Click me"); Container cp = getContentPane();//must do this cp.setLayout(new FlowLayout(FlowLayout.CENTER)); cp.add(but1); } public static void main(String[] args){ SimpleGUI gui = new SimpleGUI(); System.out.println("main thread continues"); } }
  • 26. Add call to event handler import javax.swing.*; import java.awt.*; class SimpleGUI extends JFrame{ SimpleGUI(){ setSize(400,400); setDefaultCloseOperation(EXIT_ON_CLOSE); JButton but1 = new JButton("Click me"); Container cp = getContentPane(); cp.setLayout(new FlowLayout(FlowLayout.CENTER); but1.addActionListener(new MyActionListener()); cp.add(but1); } public static void main(String[] args){ SimpleGUI gui = new SimpleGUI(); } }
  • 27. Event Handler Code class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent ae) { JOptionPane.showMessageDialog( "I got clicked", null ); } }
  • 28. Add second button/event class SimpleGUI extends JFrame{ SimpleGUI(){ JButton but1 = new Jbutton("Click me"); JButton but2 = new JButton(“exit”); MyActionListener al = new MyActionListener(); but1.addActionListener(al); but2.addActionListener(al); cp.add(but1); cp.add(but2); } }
  • 29. How to distinguish events –Less good way class MyActionListener implents ActionListener{ public void actionPerformed(ActionEvent ae){ if (ae.getActionCommand().equals("Exit"){ System.exit(1); } else if (ae.getActionCommand().equals("Click me"){ JOptionPane.showMessageDialog(null, "I’m clicked"); } } }
  • 30. Good way class MyActionListener implents ActionListener{ public void actionPerformed(ActionEvent ae){ if (ae.getSource() == but2){ System.exit(1); } else if (ae.getSource() == but1){ JOptionPane.showMessageDialog( null, "I’m clicked"); } } Question: How are but1, but2 brought into scope to do this? Question:Why is this better?