SlideShare a Scribd company logo
GUI – Programming with Java
JFRAME
Creating WindowsWindowsjavax.swing.JFrame – Empty windowBy default, JFrame is not visiblesetVisible(true)!Java Look And Feel (Metal) by default
Creating JFrameimport javax.swing.JFrame;class Testing {    public static void main(String [] args) {        JFrame mywin = new JFrame();        mywin.setVisible(true);    }}
Inheritanceimport javax.swing.JFrame;class MyJFrame extends JFrame {    public MyJFrame() {        setTitle("My Window!");    }}class Testing {    public static void main(String [] args) {        MyJFrame mywin = new MyJFrame();        mywin.setVisible(true);    }}
GUI
AWT vs. SwingAWT = Abstract Window Toolkitjava.awt.*;Old class library for JavaUses native GUI - componentsSwingjavax.swing.*;From Java 1.2 ->Extends AWTGUI – components 100% JavaPluggable look and feel
LayoutsUI is build on top of layoutsLayout determinates where UI-elements are layed.You can add a layout to JframeLayoutsFlowLayoutGridLayoutBorderLayoutGridBagLAyoutCardLayout
Layout and Componentsimport javax.swing.*;import java.awt.*;class MyJFrame extends JFrame {    public MyJFrame() {        setTitle("My Window!");        JButton clickMe = new JButton("Click me!");        FlowLayout layout = new FlowLayout();        setLayout(layout);        add(clickMe);    }}class Testing {    public static void main(String [] args) {        MyJFrame mywin = new MyJFrame();        mywin.setVisible(true);    }}
FlowLayout
GridLayout
BorderLayoutFive cellsnorthsoutheastwestcenter
Other layoutsBoxLayout- Components in row or columnCardLayoutWindow holds "cards", which can hold other componentsGridBagLayout- Lot of possibilities, hard to use
JPanelIt's possible to combine layouts using JPanelJPanel can have it's own layout. JPanel may hold other componentsJFrame can hold JPanels, that hold components..
Combining LayoutsJPanel left = new JPanel();left.setLayout(new GridLayout(2,1));JPanel right = new JPanel();right.setLayout(new GridLayout(3,1));leftrightsetLayout(new Gridlayout(1,2));add(left);add(right);MyJFrame
Combining Layoutspublic MyJFrame(){  setLayout(new GridLayout(1,2));JPanel left = new JPanel();left.setLayout(new GridLayout(2,1));left.add(new JButton("1"));left.add(new JButton("2"));JPanel right = new JPanel();right.setLayout(new GridLayout(3,1));right.add(new JButton("3"));right.add(new JButton("4"));  right.add(new JButton("5"));add(left);  add(right);}
Components
ComponentsUI – components can be added to window (JFrame) using the add() – methodAll components derive from JComponentUI – components?JButtonJLabelJMenuItemJTableJTextAreaJTextField...
JComponentSome component's common methodssetVisible(boolean)setFont(Font)setEnabled(boolean)... See JComponent APIhttp://java.sun.com/javase/6/docs/api/javax/swing/JComponent.html
ComponentsJButtonJButton mybutton = new JButton("Click!");JLabelJLabel mylabel = new JLabel("Some text");JTextFieldJTextField myfield = new JTextField();String text = myfield.getText();JTextArea...
Event handling
Delegation Event HandlingDelegation Event  Model:Simple and easy to learnSupport a clean separation between application and GUI codeFacilitate the creation of robust event handling code which is less error-prone (strong compile-time checking)Flexible enough to enable varied application models for event flow and propagationFor visual tool builders, enable run-time discovery of both events that a component generates as well as the events it may observeSupport backward binary compatibility with the old model
Separation of GUI and BLSourceListenerRegistration
Concepts: Event SourceEvent source is usually some component that can raise eventsExamples of event sourceJButton (button is clicked)JMenuItemJTextField
ListenerAny class that can handle the events=> Any class that implements some interface
Separation of GUI and BLSourceListenerRegistration
Recap on Polymorphisminterface AbleToMove {    public void start();    public void stop();}class Car implements AbleToMove {	public void start() {		// do something   }   public void stop() {    // do something   }}
Recap on Polymorphismclass Test {	public static void main(String [] args) {	    Airplane a = new Airplane();		   someMethod(a);   }   public static void someMethod(AbleToMove x) {			x.start();   }}You can pass whateverobject you desire as  long asthe object implements AbleToMoveinterface!
ExampleJButton is a event source.JButton source = new JButton();When the button is clicked we want that something happensWe need a class that listens to the button.We register the source and the listener with each other!
Separation of GUI and BLJButtonListenerRegistration
RegistrationJButton holds a method addActionListenerpublic void addActionListener(ActionListener l)So you can call it likeJButton source = new JButton("Click!");source.addActionListener(...);Parameter ActionListener? What is it?It's an interface!This means that you can pass whatever object as long as the object implements the interface!
ActionListenerSo the listener can be what ever object as long as it implements the ActionListener.ActionListener:interface ActionListener {public void actionPerformed(ActionEvent e);}
ListenerSome class that implements the ActionListenerclass MyListener implements ActionListener {    public void actionPerformed(ActionEvent e) {       // do something   }}
Separation of GUI and BLJButtonMyListeneraddActionListenerActionListener
Example Usage// Create the sourceJButton button = new JButton("click me");// Create the listenerMyListener listener = new MyListener();// Registrationbutton.addActionListener(listener);
RegistrationDifferent sources have different methods and interfaces for the registration.Registration:addXXXListenerExamplesaddMouseMotionListener(...)addMouseListener(...)addKeyListener(...)
Example: Listening to Mouse in Window// SourceJFrame a = new JFrame();// ListenerSomeClass listener = new SomeClass();// Registrationa.addMouseMotionListener(listener);
BL and GUI in the same classIn small programs it is usual that the GUI - and the application code is implemented in the same class.No the listener is the same class:class MyJFrame extends JFrame implements ActionListenerAnd registration:source.addActionListener(this);
Menus
MenuBarJFrame can contain MenuBarNeeded classesJMenuBarJMenuJMenuItemEvent handling the same as in JButton (addActionListener)
Creating MenuBarJMenuBar menubar = new JMenuBar();JMenu edit = new JMenu("Edit");JMenuItem pref = new JMenu("Preferen..edit.add(pref);menubar.add(edit);setJMenuBar(menubar);
Dialogs
About DialogsJFrame is used for windows, JDialog for dialogs.You can inherit the JDialog.Every dialog needs to know who the host window isdialog belongs to the window
Standard DialogsReally easy way to create dialogs is use standard dialogsJOptionPaneJFileChooserJColorChooser...
JOptionPaneWith one line of code, you can pop up a dialogJOptionPane.showMessageDialog(hostframe, "Hello!");Also availableshowConfirmDialogyes/no/cancelshowInputDialogprompt user
JFileChooserJFileChooser chooser = new JFileChooser(); int returnVal = chooser.showOpenDialog(parent); if(returnVal == JFileChooser.APPROVE_OPTION)    String file = chooser.getSelectedFile().getName();
Ad

Recommended

GUI Programming In Java
GUI Programming In Java
yht4ever
 
Java- GUI- Mazenet solution
Java- GUI- Mazenet solution
Mazenetsolution
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) - A Review
Fernando Torres
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
PRN USM
 
Gui
Gui
Sardar Alam
 
Swing and Graphical User Interface in Java
Swing and Graphical User Interface in Java
babak danyal
 
Swing and AWT in java
Swing and AWT in java
Adil Mehmoood
 
GUI components in Java
GUI components in Java
kirupasuchi1996
 
Awt
Awt
Rakesh Patil
 
The AWT and Swing
The AWT and Swing
adil raja
 
Awt and swing in java
Awt and swing in java
Shehrevar Davierwala
 
GUI programming
GUI programming
Vineeta Garg
 
Java: GUI
Java: GUI
Tareq Hasan
 
tL19 awt
tL19 awt
teach4uin
 
Swings
Swings
Balwinder Kumar
 
Complete java swing
Complete java swing
jehan1987
 
java swing
java swing
Waheed Warraich
 
Awt controls ppt
Awt controls ppt
soumyaharitha
 
JAVA AWT
JAVA AWT
shanmuga rajan
 
Graphical User Interface (Gui)
Graphical User Interface (Gui)
Bilal Amjad
 
Java swing
Java swing
Apurbo Datta
 
Chapter 1 swings
Chapter 1 swings
Jafar Nesargi
 
Basic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in Java
suraj pandey
 
Java swing
Java swing
Arati Gadgil
 
Graphical User Interface in JAVA
Graphical User Interface in JAVA
suraj pandey
 
Java awt tutorial javatpoint
Java awt tutorial javatpoint
Ricardo Garcia
 
28 awt
28 awt
Prachi Vijh
 
java2 swing
java2 swing
guest0282b71
 
Gu iintro(java)
Gu iintro(java)
Satish Verma
 
Mental models
Mental models
aukee
 

More Related Content

What's hot (20)

Awt
Awt
Rakesh Patil
 
The AWT and Swing
The AWT and Swing
adil raja
 
Awt and swing in java
Awt and swing in java
Shehrevar Davierwala
 
GUI programming
GUI programming
Vineeta Garg
 
Java: GUI
Java: GUI
Tareq Hasan
 
tL19 awt
tL19 awt
teach4uin
 
Swings
Swings
Balwinder Kumar
 
Complete java swing
Complete java swing
jehan1987
 
java swing
java swing
Waheed Warraich
 
Awt controls ppt
Awt controls ppt
soumyaharitha
 
JAVA AWT
JAVA AWT
shanmuga rajan
 
Graphical User Interface (Gui)
Graphical User Interface (Gui)
Bilal Amjad
 
Java swing
Java swing
Apurbo Datta
 
Chapter 1 swings
Chapter 1 swings
Jafar Nesargi
 
Basic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in Java
suraj pandey
 
Java swing
Java swing
Arati Gadgil
 
Graphical User Interface in JAVA
Graphical User Interface in JAVA
suraj pandey
 
Java awt tutorial javatpoint
Java awt tutorial javatpoint
Ricardo Garcia
 
28 awt
28 awt
Prachi Vijh
 
java2 swing
java2 swing
guest0282b71
 

Viewers also liked (20)

Gu iintro(java)
Gu iintro(java)
Satish Verma
 
Mental models
Mental models
aukee
 
Modul oop with java application mauludin
Modul oop with java application mauludin
Mauludin Ahmad
 
The Game Of Life - Java‘s Siblings and Heirs are populating the Ecosystem
The Game Of Life - Java‘s Siblings and Heirs are populating the Ecosystem
jexp
 
KC Java Android Talk (March 2011)
KC Java Android Talk (March 2011)
osake
 
First Steps in Android
First Steps in Android
Rich Helton
 
Introduction to Android Development
Introduction to Android Development
Prof. Erwin Globio
 
Google I/O 2013 報告会 Android Studio と Gradle
Google I/O 2013 報告会 Android Studio と Gradle
Keishin Yokomaku
 
12 gui concepts 1
12 gui concepts 1
Jomel Penalba
 
OOP in Java
OOP in Java
wiradikusuma
 
Games and Java ME - Have fun and earn some money
Games and Java ME - Have fun and earn some money
Marcelo Quinta
 
Practical OOP In Java
Practical OOP In Java
wiradikusuma
 
java swing
java swing
vannarith
 
Gui programming (awt)
Gui programming (awt)
Ravi_Kant_Sahu
 
Android Development: The Basics
Android Development: The Basics
Mike Desjardins
 
Contingency theory of management
Contingency theory of management
ARUN NAIK
 
Android ppt
Android ppt
Ansh Singh
 
Android for Java Developers
Android for Java Developers
Marko Gargenta
 
Object Oriented Programming Concepts
Object Oriented Programming Concepts
thinkphp
 
Introduction to java
Introduction to java
Veerabadra Badra
 
Mental models
Mental models
aukee
 
Modul oop with java application mauludin
Modul oop with java application mauludin
Mauludin Ahmad
 
The Game Of Life - Java‘s Siblings and Heirs are populating the Ecosystem
The Game Of Life - Java‘s Siblings and Heirs are populating the Ecosystem
jexp
 
KC Java Android Talk (March 2011)
KC Java Android Talk (March 2011)
osake
 
First Steps in Android
First Steps in Android
Rich Helton
 
Introduction to Android Development
Introduction to Android Development
Prof. Erwin Globio
 
Google I/O 2013 報告会 Android Studio と Gradle
Google I/O 2013 報告会 Android Studio と Gradle
Keishin Yokomaku
 
Games and Java ME - Have fun and earn some money
Games and Java ME - Have fun and earn some money
Marcelo Quinta
 
Practical OOP In Java
Practical OOP In Java
wiradikusuma
 
Android Development: The Basics
Android Development: The Basics
Mike Desjardins
 
Contingency theory of management
Contingency theory of management
ARUN NAIK
 
Android for Java Developers
Android for Java Developers
Marko Gargenta
 
Object Oriented Programming Concepts
Object Oriented Programming Concepts
thinkphp
 
Ad

Similar to GUI Programming with Java (20)

14a-gui.ppt
14a-gui.ppt
DrDGayathriDevi
 
Swing basics
Swing basics
Medi-Caps University
 
Logic and Coding of Java Interfaces & Swing Applications
Logic and Coding of Java Interfaces & Swing Applications
kjkleindorfer
 
28-GUI application.pptx.pdf
28-GUI application.pptx.pdf
NguynThiThanhTho
 
Windows Programming with AWT
Windows Programming with AWT
backdoor
 
Creating GUI.pptx Gui graphical user interface
Creating GUI.pptx Gui graphical user interface
pikachu02434
 
ch20.pptx
ch20.pptx
EnriqueMartinezTelle2
 
Java OOP Programming language (Part 7) - Swing
Java OOP Programming language (Part 7) - Swing
OUM SAOKOSAL
 
Chapter 5 GUI for introduction of java and gui .ppt
Chapter 5 GUI for introduction of java and gui .ppt
HabibMuhammed2
 
CORE JAVA-2
CORE JAVA-2
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
13457272.ppt
13457272.ppt
aptechaligarh
 
SWING USING JAVA WITH VARIOUS COMPONENTS
SWING USING JAVA WITH VARIOUS COMPONENTS
bharathiv53
 
Introduction to java netbeans
Introduction to java netbeans
Shrey Goswami
 
Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892
renuka gavli
 
Swing
Swing
Jaydeep Viradiya
 
Getting started with GUI programming in Java_1
Getting started with GUI programming in Java_1
Muhammad Shebl Farag
 
A Simple Java GUI Application.pptx
A Simple Java GUI Application.pptx
raedriyad
 
L11cs2110sp13
L11cs2110sp13
karan saini
 
Md10 building java gu is
Md10 building java gu is
Rakesh Madugula
 
Java_gui_with_AWT_and_its_components.ppt
Java_gui_with_AWT_and_its_components.ppt
JyothiAmpally
 
Logic and Coding of Java Interfaces & Swing Applications
Logic and Coding of Java Interfaces & Swing Applications
kjkleindorfer
 
28-GUI application.pptx.pdf
28-GUI application.pptx.pdf
NguynThiThanhTho
 
Windows Programming with AWT
Windows Programming with AWT
backdoor
 
Creating GUI.pptx Gui graphical user interface
Creating GUI.pptx Gui graphical user interface
pikachu02434
 
Java OOP Programming language (Part 7) - Swing
Java OOP Programming language (Part 7) - Swing
OUM SAOKOSAL
 
Chapter 5 GUI for introduction of java and gui .ppt
Chapter 5 GUI for introduction of java and gui .ppt
HabibMuhammed2
 
SWING USING JAVA WITH VARIOUS COMPONENTS
SWING USING JAVA WITH VARIOUS COMPONENTS
bharathiv53
 
Introduction to java netbeans
Introduction to java netbeans
Shrey Goswami
 
Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892
renuka gavli
 
Getting started with GUI programming in Java_1
Getting started with GUI programming in Java_1
Muhammad Shebl Farag
 
A Simple Java GUI Application.pptx
A Simple Java GUI Application.pptx
raedriyad
 
Md10 building java gu is
Md10 building java gu is
Rakesh Madugula
 
Java_gui_with_AWT_and_its_components.ppt
Java_gui_with_AWT_and_its_components.ppt
JyothiAmpally
 
Ad

More from Jussi Pohjolainen (20)

Moved to Speakerdeck
Moved to Speakerdeck
Jussi Pohjolainen
 
Java Web Services
Java Web Services
Jussi Pohjolainen
 
Box2D and libGDX
Box2D and libGDX
Jussi Pohjolainen
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
Jussi Pohjolainen
 
libGDX: Tiled Maps
libGDX: Tiled Maps
Jussi Pohjolainen
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
Jussi Pohjolainen
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDX
Jussi Pohjolainen
 
Advanced JavaScript Development
Advanced JavaScript Development
Jussi Pohjolainen
 
Introduction to JavaScript
Introduction to JavaScript
Jussi Pohjolainen
 
Introduction to AngularJS
Introduction to AngularJS
Jussi Pohjolainen
 
libGDX: Scene2D
libGDX: Scene2D
Jussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame Animation
Jussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame Animation
Jussi Pohjolainen
 
libGDX: User Input
libGDX: User Input
Jussi Pohjolainen
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
Jussi Pohjolainen
 
Building Android games using LibGDX
Building Android games using LibGDX
Jussi Pohjolainen
 
Android Threading
Android Threading
Jussi Pohjolainen
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Jussi Pohjolainen
 
Creating Games for Asha - platform
Creating Games for Asha - platform
Jussi Pohjolainen
 
Intro to Asha UI
Intro to Asha UI
Jussi Pohjolainen
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
Jussi Pohjolainen
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
Jussi Pohjolainen
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDX
Jussi Pohjolainen
 
Advanced JavaScript Development
Advanced JavaScript Development
Jussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame Animation
Jussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame Animation
Jussi Pohjolainen
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
Jussi Pohjolainen
 
Building Android games using LibGDX
Building Android games using LibGDX
Jussi Pohjolainen
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Jussi Pohjolainen
 
Creating Games for Asha - platform
Creating Games for Asha - platform
Jussi Pohjolainen
 

Recently uploaded (20)

Q1_TLE 8_Week 1- Day 1 tools and equipment
Q1_TLE 8_Week 1- Day 1 tools and equipment
clairenotado3
 
Photo chemistry Power Point Presentation
Photo chemistry Power Point Presentation
mprpgcwa2024
 
2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
VCE Literature Section A Exam Response Guide
VCE Literature Section A Exam Response Guide
jpinnuck
 
Hurricane Helene Application Documents Checklists
Hurricane Helene Application Documents Checklists
Mebane Rash
 
Tanja Vujicic - PISA for Schools contact Info
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
This is why students from these 44 institutions have not received National Se...
This is why students from these 44 institutions have not received National Se...
Kweku Zurek
 
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
parmarjuli1412
 
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
 
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
sumadsadjelly121997
 
INDUCTIVE EFFECT slide for first prof pharamacy students
INDUCTIVE EFFECT slide for first prof pharamacy students
SHABNAM FAIZ
 
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
KaryanaTantri21
 
How to Add New Item in CogMenu in Odoo 18
How to Add New Item in CogMenu in Odoo 18
Celine George
 
LDMMIA Yoga S10 Free Workshop Grad Level
LDMMIA Yoga S10 Free Workshop Grad Level
LDM & Mia eStudios
 
Values Education 10 Quarter 1 Module .pptx
Values Education 10 Quarter 1 Module .pptx
JBPafin
 
Gladiolous Cultivation practices by AKL.pdf
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
SHERAZ AHMAD LONE
 
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
Aprendendo Arquitetura Framework Salesforce - Dia 02
Aprendendo Arquitetura Framework Salesforce - Dia 02
Mauricio Alexandre Silva
 
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
Ultimatewinner0342
 
Q1_TLE 8_Week 1- Day 1 tools and equipment
Q1_TLE 8_Week 1- Day 1 tools and equipment
clairenotado3
 
Photo chemistry Power Point Presentation
Photo chemistry Power Point Presentation
mprpgcwa2024
 
2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
VCE Literature Section A Exam Response Guide
VCE Literature Section A Exam Response Guide
jpinnuck
 
Hurricane Helene Application Documents Checklists
Hurricane Helene Application Documents Checklists
Mebane Rash
 
Tanja Vujicic - PISA for Schools contact Info
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
This is why students from these 44 institutions have not received National Se...
This is why students from these 44 institutions have not received National Se...
Kweku Zurek
 
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
parmarjuli1412
 
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
 
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
sumadsadjelly121997
 
INDUCTIVE EFFECT slide for first prof pharamacy students
INDUCTIVE EFFECT slide for first prof pharamacy students
SHABNAM FAIZ
 
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
KaryanaTantri21
 
How to Add New Item in CogMenu in Odoo 18
How to Add New Item in CogMenu in Odoo 18
Celine George
 
LDMMIA Yoga S10 Free Workshop Grad Level
LDMMIA Yoga S10 Free Workshop Grad Level
LDM & Mia eStudios
 
Values Education 10 Quarter 1 Module .pptx
Values Education 10 Quarter 1 Module .pptx
JBPafin
 
Gladiolous Cultivation practices by AKL.pdf
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
SHERAZ AHMAD LONE
 
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
Aprendendo Arquitetura Framework Salesforce - Dia 02
Aprendendo Arquitetura Framework Salesforce - Dia 02
Mauricio Alexandre Silva
 
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
Ultimatewinner0342
 

GUI Programming with Java

  • 3. Creating WindowsWindowsjavax.swing.JFrame – Empty windowBy default, JFrame is not visiblesetVisible(true)!Java Look And Feel (Metal) by default
  • 4. Creating JFrameimport javax.swing.JFrame;class Testing { public static void main(String [] args) { JFrame mywin = new JFrame(); mywin.setVisible(true); }}
  • 5. Inheritanceimport javax.swing.JFrame;class MyJFrame extends JFrame { public MyJFrame() { setTitle("My Window!"); }}class Testing { public static void main(String [] args) { MyJFrame mywin = new MyJFrame(); mywin.setVisible(true); }}
  • 6. GUI
  • 7. AWT vs. SwingAWT = Abstract Window Toolkitjava.awt.*;Old class library for JavaUses native GUI - componentsSwingjavax.swing.*;From Java 1.2 ->Extends AWTGUI – components 100% JavaPluggable look and feel
  • 8. LayoutsUI is build on top of layoutsLayout determinates where UI-elements are layed.You can add a layout to JframeLayoutsFlowLayoutGridLayoutBorderLayoutGridBagLAyoutCardLayout
  • 9. Layout and Componentsimport javax.swing.*;import java.awt.*;class MyJFrame extends JFrame { public MyJFrame() { setTitle("My Window!"); JButton clickMe = new JButton("Click me!"); FlowLayout layout = new FlowLayout(); setLayout(layout); add(clickMe); }}class Testing { public static void main(String [] args) { MyJFrame mywin = new MyJFrame(); mywin.setVisible(true); }}
  • 13. Other layoutsBoxLayout- Components in row or columnCardLayoutWindow holds "cards", which can hold other componentsGridBagLayout- Lot of possibilities, hard to use
  • 14. JPanelIt's possible to combine layouts using JPanelJPanel can have it's own layout. JPanel may hold other componentsJFrame can hold JPanels, that hold components..
  • 15. Combining LayoutsJPanel left = new JPanel();left.setLayout(new GridLayout(2,1));JPanel right = new JPanel();right.setLayout(new GridLayout(3,1));leftrightsetLayout(new Gridlayout(1,2));add(left);add(right);MyJFrame
  • 16. Combining Layoutspublic MyJFrame(){ setLayout(new GridLayout(1,2));JPanel left = new JPanel();left.setLayout(new GridLayout(2,1));left.add(new JButton("1"));left.add(new JButton("2"));JPanel right = new JPanel();right.setLayout(new GridLayout(3,1));right.add(new JButton("3"));right.add(new JButton("4")); right.add(new JButton("5"));add(left); add(right);}
  • 18. ComponentsUI – components can be added to window (JFrame) using the add() – methodAll components derive from JComponentUI – components?JButtonJLabelJMenuItemJTableJTextAreaJTextField...
  • 19. JComponentSome component's common methodssetVisible(boolean)setFont(Font)setEnabled(boolean)... See JComponent APIhttp://java.sun.com/javase/6/docs/api/javax/swing/JComponent.html
  • 20. ComponentsJButtonJButton mybutton = new JButton("Click!");JLabelJLabel mylabel = new JLabel("Some text");JTextFieldJTextField myfield = new JTextField();String text = myfield.getText();JTextArea...
  • 22. Delegation Event HandlingDelegation Event Model:Simple and easy to learnSupport a clean separation between application and GUI codeFacilitate the creation of robust event handling code which is less error-prone (strong compile-time checking)Flexible enough to enable varied application models for event flow and propagationFor visual tool builders, enable run-time discovery of both events that a component generates as well as the events it may observeSupport backward binary compatibility with the old model
  • 23. Separation of GUI and BLSourceListenerRegistration
  • 24. Concepts: Event SourceEvent source is usually some component that can raise eventsExamples of event sourceJButton (button is clicked)JMenuItemJTextField
  • 25. ListenerAny class that can handle the events=> Any class that implements some interface
  • 26. Separation of GUI and BLSourceListenerRegistration
  • 27. Recap on Polymorphisminterface AbleToMove { public void start(); public void stop();}class Car implements AbleToMove { public void start() { // do something } public void stop() { // do something }}
  • 28. Recap on Polymorphismclass Test { public static void main(String [] args) { Airplane a = new Airplane(); someMethod(a); } public static void someMethod(AbleToMove x) { x.start(); }}You can pass whateverobject you desire as long asthe object implements AbleToMoveinterface!
  • 29. ExampleJButton is a event source.JButton source = new JButton();When the button is clicked we want that something happensWe need a class that listens to the button.We register the source and the listener with each other!
  • 30. Separation of GUI and BLJButtonListenerRegistration
  • 31. RegistrationJButton holds a method addActionListenerpublic void addActionListener(ActionListener l)So you can call it likeJButton source = new JButton("Click!");source.addActionListener(...);Parameter ActionListener? What is it?It's an interface!This means that you can pass whatever object as long as the object implements the interface!
  • 32. ActionListenerSo the listener can be what ever object as long as it implements the ActionListener.ActionListener:interface ActionListener {public void actionPerformed(ActionEvent e);}
  • 33. ListenerSome class that implements the ActionListenerclass MyListener implements ActionListener { public void actionPerformed(ActionEvent e) { // do something }}
  • 34. Separation of GUI and BLJButtonMyListeneraddActionListenerActionListener
  • 35. Example Usage// Create the sourceJButton button = new JButton("click me");// Create the listenerMyListener listener = new MyListener();// Registrationbutton.addActionListener(listener);
  • 36. RegistrationDifferent sources have different methods and interfaces for the registration.Registration:addXXXListenerExamplesaddMouseMotionListener(...)addMouseListener(...)addKeyListener(...)
  • 37. Example: Listening to Mouse in Window// SourceJFrame a = new JFrame();// ListenerSomeClass listener = new SomeClass();// Registrationa.addMouseMotionListener(listener);
  • 38. BL and GUI in the same classIn small programs it is usual that the GUI - and the application code is implemented in the same class.No the listener is the same class:class MyJFrame extends JFrame implements ActionListenerAnd registration:source.addActionListener(this);
  • 39. Menus
  • 40. MenuBarJFrame can contain MenuBarNeeded classesJMenuBarJMenuJMenuItemEvent handling the same as in JButton (addActionListener)
  • 41. Creating MenuBarJMenuBar menubar = new JMenuBar();JMenu edit = new JMenu("Edit");JMenuItem pref = new JMenu("Preferen..edit.add(pref);menubar.add(edit);setJMenuBar(menubar);
  • 43. About DialogsJFrame is used for windows, JDialog for dialogs.You can inherit the JDialog.Every dialog needs to know who the host window isdialog belongs to the window
  • 44. Standard DialogsReally easy way to create dialogs is use standard dialogsJOptionPaneJFileChooserJColorChooser...
  • 45. JOptionPaneWith one line of code, you can pop up a dialogJOptionPane.showMessageDialog(hostframe, "Hello!");Also availableshowConfirmDialogyes/no/cancelshowInputDialogprompt user
  • 46. JFileChooserJFileChooser chooser = new JFileChooser(); int returnVal = chooser.showOpenDialog(parent); if(returnVal == JFileChooser.APPROVE_OPTION) String file = chooser.getSelectedFile().getName();