SlideShare a Scribd company logo
 
GUI Programming in Java
Introduction Graphical User Interface (GUI) Gives program distinctive “look” and “feel” Provides users with basic level of familiarity Built from GUI components (controls, widgets, etc.) User interacts with GUI component via mouse, keyboard, etc.
GUI Programming Concepts in Java Java GUI ("Swing") has  components Windows GUI has  controls Unix GUI has  widgets examples: labels,   buttons, check boxes, radio buttons, text input boxes, pull down lists Java Swing components: JLabel, JButton, JCheckBox, JRadioButton, JTextField, JTextArea, JComboBox
Java GUI history: the AWT AWT(JDK 1.0, 1.1):  Abstract Window Toolkit package: java.awt, java.awt.event heavyweight components using native GUI system elements used for applets until most browsers supported JRE 1.2
Swing in Java Swing(Java 2, JDK 1.2+)  lightweight components that do not rely on the native GUI or OS “ look and feel” of Swing components are identical on different platforms can be customized Swing inherits from AWT AWT still used for events, layouts
Swing Components in Java advanced GUI support. e.g. drag-and-drop package names: javax.swing, javax.swing.event components inherit from JComponent components are added to a top-level container: JFrame, JDialog, or JApplet.
Lightweight vs. Heavyweight GUI Components Lightweight components Not tied directly to GUI components supported by underlying platform Heavyweight components Tied directly to the local platform AWT components Some Swing components
Basic GUI Programming Steps in Java declare a container and components add components to one or more containers using a layout manager register event listener(s) with the components create event listener method(s)
AWT Event Class Hierarchy EventObject AWTEvent ActionEvent ComponentEvent AdjustmentEvent TextEvent ItemEvent ContainerEvent MouseEvent keyEvent FocusEvent InputEvent PaintEvent WindowEvent
AWT Events Component Event  Generated Generate When Button ActionEvent Clicked Selected or deselected Moved, resized, hidden or shown Checkbox CheckboxMenuItem Gained or loses fccus Pressed or released ComponentEvent Component Double Clicked ItemEvent Container ContainerEvent Added or removed ItemEvent ItemEvent Selected or deselected Selected or deselected Choice FocusEvent KeyEvent List ActionEvent ItemEvent Selected or deselected Selected ActionEvent MenuItem Moved AdjustmentEvent Scrollbar Changed TextEvent TextComponent Completed editing TextEvent TextField Opened, closed, iconified, deiconified, etc. WindowEvent Window
Events Delegation Model User  Action Source Object Triggering an event Target/Listener Object Event Object Registering   for an event Creating an event Notify Event Listener  Handle event Event  Handler
Some basic GUI components.
Swing Overview Swing GUI components Package  javax.swing Components originate from AWT (package  java.awt ) Contain  look and feel Appearance and how users interact with program Lightweight components Written completely in Java
12.2  Swing Overview (cont.) Class  Component Contains method  paint  for drawing  Component  onscreen Class  Container Collection of related components Contains method  add  for adding components Class  JComponent Pluggable look and feel  for customizing look and feel Shortcut keys ( mnemonics ) Common event-handling capabilities
Fig. 12.3  Common superclasses of many of the Swing components.
12.3  JLabel Label Provide text on GUI Defined with class  JLabel Can display: Single line of read-only text Image Text and image
1  // Fig. 12.4: LabelTest.java   2  // Demonstrating the JLabel class.   3    4  // Java core packages   5  import  java.awt.*;   6  import  java.awt.event.*;   7    8  // Java extension packages   9  import  javax.swing.*; 10  11  public class  LabelTest  extends  JFrame { 12  private  JLabel label1, label2, label3; 13  14  // set up GUI 15  public  LabelTest() 16  { 17  super (  "Testing JLabel"  ); 18  19  // get content pane and set its layout 20  Container container = getContentPane(); 21  container.setLayout(  new  FlowLayout() ); 22  23  // JLabel constructor with a string argument 24  label1 =  new  JLabel(  "Label with text"  ); 25  label1.setToolTipText(  "This is label1"  ); 26  container.add( label1 ); 27  28  // JLabel constructor with string, Icon and 29  // alignment arguments 30  Icon bug =  new  ImageIcon(  "bug1.gif"  ); 31  label2 =  new  JLabel(  "Label with text and icon" , 32  bug, SwingConstants. LEFT  ); 33  label2.setToolTipText(  "This is label2"  ); 34  container.add( label2 ); 35  LabelTest.java Line 12 Line 24 Line 25 Lines 31-32 Declare three  JLabel s Create first  JLabel  with text “ Label   with   text ” Create second  JLabel  with text to left of image Tool tip is text that appears when user moves cursor over  JLabel
36  // JLabel constructor no arguments 37  label3 =  new  JLabel(); 38  label3.setText(  "Label with icon and text at bottom"  ); 39  label3.setIcon( bug ); 40  label3.setHorizontalTextPosition( SwingConstants. CENTER  ); 41  label3.setVerticalTextPosition( SwingConstants. BOTTOM  ); 42  label3.setToolTipText(  "This is label3"  ); 43  container.add( label3 ); 44  45  setSize(  275 ,  170  ); 46  setVisible(  true  ); 47  } 48  49  // execute application 50  public static void  main( String args[] ) 51  {  52  LabelTest application =  new  LabelTest(); 53  54  application.setDefaultCloseOperation( 55  JFrame. EXIT_ON_CLOSE  ); 56  } 57  58  }  // end class LabelTest LabelTest.java Lines 37-41 Create third  JLabel  with text below image
12.4  Event-Handling Model GUIs are  event driven Generate  events  when user interacts with GUI e.g., moving mouse, pressing button, typing in text field, etc. Class  java.awt.AWTEvent
Fig. 12.5  Some event classes of package  java.awt.event
12.4  Event-Handling Model (cont.) Event-handling model Three parts Event source GUI component with which user interacts Event object Encapsulates information about event that occurred Event listener Receives event object when notified, then responds Programmer must perform two tasks Register event listener for event source Implement event-handling method (event handler)
Fig. 12.6  Event-listener interfaces of package  java.awt.event
12.5  JTextField  and  JPasswordField JTextField Single-line area in which user can enter text JPasswordField Extends  JTextField Hides characters that user enters
1  // Fig. 12.7: TextFieldTest.java   2  // Demonstrating the JTextField class.   3    4  // Java core packages   5  import  java.awt.*;   6  import  java.awt.event.*;   7    8  // Java extension packages   9  import  javax.swing.*; 10  11  public class  TextFieldTest  extends  JFrame { 12  private  JTextField textField1, textField2, textField3; 13  private  JPasswordField passwordField; 14  15  // set up GUI 16  public  TextFieldTest() 17  { 18  super (  "Testing JTextField and JPasswordField"  ); 19  20  Container container = getContentPane(); 21  container.setLayout(  new  FlowLayout() ); 22  23  // construct textfield with default sizing 24  textField1 =  new  JTextField(  10  ); 25  container.add( textField1 ); 26  27  // construct textfield with default text 28  textField2 =  new  JTextField(  "Enter text here"  ); 29  container.add( textField2 ); 30  31  // construct textfield with default text and 32  // 20 visible elements and no event handler 33  textField3 =  new  JTextField(  "Uneditable text field" ,  20  ); 34  textField3.setEditable(  false  ); 35  container.add( textField3 ); TextFieldTest.java Lines 12-13 Line 24 Line 28 Lines 33-34 Declare three  JTextField s and one  JPasswordField First  JTextField  contains empty string Second  JTextField  contains text “ Enter   text   here ” Third  JTextField  contains uneditable text
36  37  // construct textfield with default text 38  passwordField =  new  JPasswordField(  "Hidden text"  ); 39  container.add( passwordField ); 40  41  // register event handlers 42  TextFieldHandler handler =  new  TextFieldHandler(); 43  textField1.addActionListener( handler ); 44  textField2.addActionListener( handler ); 45  textField3.addActionListener( handler ); 46  passwordField.addActionListener( handler ); 47  48  setSize(  325 ,  100  ); 49  setVisible(  true  ); 50  } 51  52  // execute application 53  public static void  main( String args[] ) 54  {  55  TextFieldTest application =  new  TextFieldTest(); 56  57  application.setDefaultCloseOperation(  58  JFrame. EXIT_ON_CLOSE  ); 59  } 60  61  // private inner class for event handling 62  private class  TextFieldHandler  implements  ActionListener { 63  64  // process text field events 65  public void  actionPerformed( ActionEvent event ) 66  { 67  String string =  "" ; 68  69  // user pressed Enter in JTextField textField1 70  if  ( event.getSource() == textField1 ) TextFieldTest.java Line 38 Lines 43-46 Line 62 Line 65 JPasswordField  contains text “ Hidden   text ,” but text appears as series of asterisks ( * ) Every  TextFieldHandler  instance is an  ActionListener Register GUI components with  TextFieldHandler  (register for  ActionEvent s) Method  actionPerformed  invoked when user presses  Enter  in GUI field
71  string =  "textField1: "  + event.getActionCommand(); 72  73  // user pressed Enter in JTextField textField2 74  else if  ( event.getSource() == textField2 ) 75  string =  "textField2: "  + event.getActionCommand(); 76  77  // user pressed Enter in JTextField textField3 78  else if  ( event.getSource() == textField3 ) 79  string =  "textField3: "  + event.getActionCommand(); 80  81  // user pressed Enter in JTextField passwordField 82  else if  ( event.getSource() == passwordField ) { 83  JPasswordField pwd = 84  ( JPasswordField ) event.getSource(); 85  string =  "passwordField: "  + 86  new  String( passwordField.getPassword() ); 87  } 88  89  JOptionPane.showMessageDialog(  null , string ); 90  } 91  92  }  // end private inner class TextFieldHandler 93  94  }  // end class TextFieldTest TextFieldTest.java
TextFieldTest.java
12.5.1  How Event Handling Works Two open questions from Section 12.4 How did event handler get registered? Answer: Through component’s method  addActionListener Lines 43-46 of  TextFieldTest.java How does component know to call  actionPerformed ? Answer: Event is dispatched only to listeners of appropriate type Each event type has corresponding event-listener interface Event ID specifies event type that occurred
Fig 12.8  Event registration for  JTextField   textField1 .
12.6  JButton Button Component user clicks to trigger a specific action Several different types Command buttons Check boxes Toggle buttons Radio buttons javax.swing.AbstractButton  subclasses Command buttons are created with class  JButton Generate  ActionEvent s when user clicks button
Fig. 12.9  The button heirarchy.
1  // Fig. 12.10: ButtonTest.java   2  // Creating JButtons.   3    4  // Java core packages   5  import  java.awt.*;   6  import  java.awt.event.*;   7    8  // Java extension packages   9  import  javax.swing.*; 10  11  public class  ButtonTest  extends  JFrame { 12  private  JButton plainButton, fancyButton; 13  14  // set up GUI 15  public  ButtonTest() 16  { 17  super (  "Testing Buttons"  ); 18  19  // get content pane and set its layout 20  Container container = getContentPane(); 21  container.setLayout(  new  FlowLayout() ); 22  23  // create buttons 24  plainButton =  new  JButton(  "Plain Button"  ); 25  container.add( plainButton ); 26  27  Icon bug1 =  new  ImageIcon(  "bug1.gif"  ); 28  Icon bug2 =  new  ImageIcon(  "bug2.gif"  ); 29  fancyButton = new JButton(  "Fancy Button" , bug1 ); 30  fancyButton.setRolloverIcon( bug2 ); 31  container.add( fancyButton ); 32  33  // create an instance of inner class ButtonHandler 34  // to use for button event handling  35  ButtonHandler handler =  new  ButtonHandler(); ButtonTest.java Line 12 Line 24 Lines 27-30 Line 35 Create two references to  JButton  instances Instantiate  JButton  with text Instantiate  JButton  with image and  rollover  image Instantiate  ButtonHandler  for  JButton  event handling
36  fancyButton.addActionListener( handler ); 37  plainButton.addActionListener( handler ); 38  39  setSize(  275 ,  100  ); 40  setVisible(  true  ); 41  } 42  43  // execute application 44  public static void  main( String args[] ) 45  {  46  ButtonTest application =  new  ButtonTest(); 47  48  application.setDefaultCloseOperation( 49  JFrame. EXIT_ON_CLOSE  ); 50  } 51  52  // inner class for button event handling 53  private class  ButtonHandler  implements  ActionListener { 54  55  // handle button event 56  public void  actionPerformed( ActionEvent event ) 57  { 58  JOptionPane.showMessageDialog(  null , 59  "You pressed: "  + event.getActionCommand() ); 60  } 61  62  }   // end private inner class ButtonHandler 63  64  }  // end class ButtonTest ButtonTest.java Lines 36-37 Lines 56-60 Register  JButton s to receive events from  ButtonHandler When user clicks  JButton ,  ButtonHandler  invokes method  actionPerformed  of all registered listeners
ButtonTest.java
Ad

More Related Content

What's hot (20)

Java swing
Java swingJava swing
Java swing
Apurbo Datta
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
shanmuga rajan
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
Elizabeth alexander
 
GUI Programming In Java
GUI Programming In JavaGUI Programming In Java
GUI Programming In Java
yht4ever
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
Adil Mehmoood
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
Haldia Institute of Technology
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
Lovely Professional University
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
Pooja Jaiswal
 
Applets
AppletsApplets
Applets
Prabhakaran V M
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
Elizabeth Thomas
 
Applets in java
Applets in javaApplets in java
Applets in java
Wani Zahoor
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
VINOTH R
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
PravinYalameli
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
jaimefrozr
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Java awt
Java awtJava awt
Java awt
Arati Gadgil
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 

Viewers also liked (20)

Graphical User Interface (Gui)
Graphical User Interface (Gui)Graphical User Interface (Gui)
Graphical User Interface (Gui)
Bilal Amjad
 
Gui
GuiGui
Gui
Sardar Alam
 
JAVA GUI PART I
JAVA GUI PART IJAVA GUI PART I
JAVA GUI PART I
OXUS 20
 
Swing and Graphical User Interface in Java
Swing and Graphical User Interface in JavaSwing and Graphical User Interface in Java
Swing and Graphical User Interface in Java
babak danyal
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A Review
Fernando Torres
 
Java GUI PART II
Java GUI PART IIJava GUI PART II
Java GUI PART II
OXUS 20
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART III
OXUS 20
 
Java swing
Java swingJava swing
Java swing
Nataraj Dg
 
Java Swing
Java SwingJava Swing
Java Swing
Shraddha
 
java swing tutorial for beginners(java programming tutorials)
java swing tutorial for beginners(java programming tutorials)java swing tutorial for beginners(java programming tutorials)
java swing tutorial for beginners(java programming tutorials)
Daroko blog(www.professionalbloggertricks.com)
 
java swing
java swingjava swing
java swing
vannarith
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
PRN USM
 
Graphical User Interface
Graphical User Interface Graphical User Interface
Graphical User Interface
Bivek Pakuwal
 
USER INTERFACE DESIGN PPT
USER INTERFACE DESIGN PPTUSER INTERFACE DESIGN PPT
USER INTERFACE DESIGN PPT
vicci4041
 
Java Swing
Java SwingJava Swing
Java Swing
Komal Gandhi
 
Java
JavaJava
Java
mbruggen
 
Real Life Java EE Performance Tuning
Real Life Java EE Performance TuningReal Life Java EE Performance Tuning
Real Life Java EE Performance Tuning
C2B2 Consulting
 
Gui in java
Gui in javaGui in java
Gui in java
Gaurav Raj
 
Java
JavaJava
Java
Anand Grewal
 
Java swings
Java swingsJava swings
Java swings
Alisha Korpal
 
Graphical User Interface (Gui)
Graphical User Interface (Gui)Graphical User Interface (Gui)
Graphical User Interface (Gui)
Bilal Amjad
 
JAVA GUI PART I
JAVA GUI PART IJAVA GUI PART I
JAVA GUI PART I
OXUS 20
 
Swing and Graphical User Interface in Java
Swing and Graphical User Interface in JavaSwing and Graphical User Interface in Java
Swing and Graphical User Interface in Java
babak danyal
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A Review
Fernando Torres
 
Java GUI PART II
Java GUI PART IIJava GUI PART II
Java GUI PART II
OXUS 20
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART III
OXUS 20
 
Java Swing
Java SwingJava Swing
Java Swing
Shraddha
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
PRN USM
 
Graphical User Interface
Graphical User Interface Graphical User Interface
Graphical User Interface
Bivek Pakuwal
 
USER INTERFACE DESIGN PPT
USER INTERFACE DESIGN PPTUSER INTERFACE DESIGN PPT
USER INTERFACE DESIGN PPT
vicci4041
 
Real Life Java EE Performance Tuning
Real Life Java EE Performance TuningReal Life Java EE Performance Tuning
Real Life Java EE Performance Tuning
C2B2 Consulting
 
Ad

Similar to Java: GUI (20)

13.ppt Java power point presentation Java
13.ppt Java power point presentation Java13.ppt Java power point presentation Java
13.ppt Java power point presentation Java
yojot18076
 
Graphical User Components Part 1
Graphical User Components Part 1Graphical User Components Part 1
Graphical User Components Part 1
Andy Juan Sarango Veliz
 
Unit 4_1.pptx JDBC AND GUI FOR CLIENT SERVER
Unit 4_1.pptx JDBC AND GUI FOR CLIENT SERVERUnit 4_1.pptx JDBC AND GUI FOR CLIENT SERVER
Unit 4_1.pptx JDBC AND GUI FOR CLIENT SERVER
Salini P
 
javaprogramming framework-ppt frame.pptx
javaprogramming framework-ppt frame.pptxjavaprogramming framework-ppt frame.pptx
javaprogramming framework-ppt frame.pptx
DrDGayathriDevi
 
Java awt
Java awtJava awt
Java awt
GaneshKumarKanthiah
 
Swing
SwingSwing
Swing
Jaydeep Viradiya
 
Chapter 5 GUI for introduction of java and gui .ppt
Chapter 5 GUI  for  introduction of java and gui .pptChapter 5 GUI  for  introduction of java and gui .ppt
Chapter 5 GUI for introduction of java and gui .ppt
HabibMuhammed2
 
Swing
SwingSwing
Swing
Bharat17485
 
it's about the swing programs in java language
it's about the swing programs in  java languageit's about the swing programs in  java language
it's about the swing programs in java language
arunkumarg271
 
CORE JAVA-2
CORE JAVA-2CORE JAVA-2
CORE JAVA-2
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
sharanyak0721
 
Unit 5 Notes For Java Programming for BCA Madras Univ
Unit 5 Notes For Java Programming for BCA Madras UnivUnit 5 Notes For Java Programming for BCA Madras Univ
Unit 5 Notes For Java Programming for BCA Madras Univ
lavanyasujat1
 
Chap1 1 1
Chap1 1 1Chap1 1 1
Chap1 1 1
Hemo Chella
 
Chap1 1.1
Chap1 1.1Chap1 1.1
Chap1 1.1
Hemo Chella
 
Android Application Development Programming
Android Application Development ProgrammingAndroid Application Development Programming
Android Application Development Programming
Kongu Engineering College, Perundurai, Erode
 
Introduction to Griffon
Introduction to GriffonIntroduction to Griffon
Introduction to Griffon
James Williams
 
Basic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in JavaBasic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in Java
suraj pandey
 
New microsoft office word document
New microsoft office word documentNew microsoft office word document
New microsoft office word document
nidhileena
 
Gui programming a review - mixed content
Gui programming   a review - mixed contentGui programming   a review - mixed content
Gui programming a review - mixed content
Yogesh Kumar
 
Z blue introduction to gui (39023299)
Z blue   introduction to gui (39023299)Z blue   introduction to gui (39023299)
Z blue introduction to gui (39023299)
Narayana Swamy
 
13.ppt Java power point presentation Java
13.ppt Java power point presentation Java13.ppt Java power point presentation Java
13.ppt Java power point presentation Java
yojot18076
 
Unit 4_1.pptx JDBC AND GUI FOR CLIENT SERVER
Unit 4_1.pptx JDBC AND GUI FOR CLIENT SERVERUnit 4_1.pptx JDBC AND GUI FOR CLIENT SERVER
Unit 4_1.pptx JDBC AND GUI FOR CLIENT SERVER
Salini P
 
javaprogramming framework-ppt frame.pptx
javaprogramming framework-ppt frame.pptxjavaprogramming framework-ppt frame.pptx
javaprogramming framework-ppt frame.pptx
DrDGayathriDevi
 
Chapter 5 GUI for introduction of java and gui .ppt
Chapter 5 GUI  for  introduction of java and gui .pptChapter 5 GUI  for  introduction of java and gui .ppt
Chapter 5 GUI for introduction of java and gui .ppt
HabibMuhammed2
 
it's about the swing programs in java language
it's about the swing programs in  java languageit's about the swing programs in  java language
it's about the swing programs in java language
arunkumarg271
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
sharanyak0721
 
Unit 5 Notes For Java Programming for BCA Madras Univ
Unit 5 Notes For Java Programming for BCA Madras UnivUnit 5 Notes For Java Programming for BCA Madras Univ
Unit 5 Notes For Java Programming for BCA Madras Univ
lavanyasujat1
 
Introduction to Griffon
Introduction to GriffonIntroduction to Griffon
Introduction to Griffon
James Williams
 
Basic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in JavaBasic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in Java
suraj pandey
 
New microsoft office word document
New microsoft office word documentNew microsoft office word document
New microsoft office word document
nidhileena
 
Gui programming a review - mixed content
Gui programming   a review - mixed contentGui programming   a review - mixed content
Gui programming a review - mixed content
Yogesh Kumar
 
Z blue introduction to gui (39023299)
Z blue   introduction to gui (39023299)Z blue   introduction to gui (39023299)
Z blue introduction to gui (39023299)
Narayana Swamy
 
Ad

More from Tareq Hasan (20)

Grow Your Career with WordPress
Grow Your Career with WordPressGrow Your Career with WordPress
Grow Your Career with WordPress
Tareq Hasan
 
Caching in WordPress
Caching in WordPressCaching in WordPress
Caching in WordPress
Tareq Hasan
 
How to Submit a plugin to WordPress.org Repository
How to Submit a plugin to WordPress.org RepositoryHow to Submit a plugin to WordPress.org Repository
How to Submit a plugin to WordPress.org Repository
Tareq Hasan
 
Composer - The missing package manager for PHP
Composer - The missing package manager for PHPComposer - The missing package manager for PHP
Composer - The missing package manager for PHP
Tareq Hasan
 
WordPress Theme & Plugin development best practices - phpXperts seminar 2011
WordPress Theme & Plugin development best practices - phpXperts seminar 2011WordPress Theme & Plugin development best practices - phpXperts seminar 2011
WordPress Theme & Plugin development best practices - phpXperts seminar 2011
Tareq Hasan
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
Tareq Hasan
 
02 c++ Array Pointer
02 c++ Array Pointer02 c++ Array Pointer
02 c++ Array Pointer
Tareq Hasan
 
01 c++ Intro.ppt
01 c++ Intro.ppt01 c++ Intro.ppt
01 c++ Intro.ppt
Tareq Hasan
 
chapter22.ppt
chapter22.pptchapter22.ppt
chapter22.ppt
Tareq Hasan
 
chapter - 6.ppt
chapter - 6.pptchapter - 6.ppt
chapter - 6.ppt
Tareq Hasan
 
Algorithm.ppt
Algorithm.pptAlgorithm.ppt
Algorithm.ppt
Tareq Hasan
 
chapter-8.ppt
chapter-8.pptchapter-8.ppt
chapter-8.ppt
Tareq Hasan
 
chapter23.ppt
chapter23.pptchapter23.ppt
chapter23.ppt
Tareq Hasan
 
chapter24.ppt
chapter24.pptchapter24.ppt
chapter24.ppt
Tareq Hasan
 
Algorithm: priority queue
Algorithm: priority queueAlgorithm: priority queue
Algorithm: priority queue
Tareq Hasan
 
Algorithm: Quick-Sort
Algorithm: Quick-SortAlgorithm: Quick-Sort
Algorithm: Quick-Sort
Tareq Hasan
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
Tareq Hasan
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
Tareq Hasan
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
Tareq Hasan
 
Java: Class Design Examples
Java: Class Design ExamplesJava: Class Design Examples
Java: Class Design Examples
Tareq Hasan
 
Grow Your Career with WordPress
Grow Your Career with WordPressGrow Your Career with WordPress
Grow Your Career with WordPress
Tareq Hasan
 
Caching in WordPress
Caching in WordPressCaching in WordPress
Caching in WordPress
Tareq Hasan
 
How to Submit a plugin to WordPress.org Repository
How to Submit a plugin to WordPress.org RepositoryHow to Submit a plugin to WordPress.org Repository
How to Submit a plugin to WordPress.org Repository
Tareq Hasan
 
Composer - The missing package manager for PHP
Composer - The missing package manager for PHPComposer - The missing package manager for PHP
Composer - The missing package manager for PHP
Tareq Hasan
 
WordPress Theme & Plugin development best practices - phpXperts seminar 2011
WordPress Theme & Plugin development best practices - phpXperts seminar 2011WordPress Theme & Plugin development best practices - phpXperts seminar 2011
WordPress Theme & Plugin development best practices - phpXperts seminar 2011
Tareq Hasan
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
Tareq Hasan
 
02 c++ Array Pointer
02 c++ Array Pointer02 c++ Array Pointer
02 c++ Array Pointer
Tareq Hasan
 
01 c++ Intro.ppt
01 c++ Intro.ppt01 c++ Intro.ppt
01 c++ Intro.ppt
Tareq Hasan
 
Algorithm: priority queue
Algorithm: priority queueAlgorithm: priority queue
Algorithm: priority queue
Tareq Hasan
 
Algorithm: Quick-Sort
Algorithm: Quick-SortAlgorithm: Quick-Sort
Algorithm: Quick-Sort
Tareq Hasan
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
Tareq Hasan
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
Tareq Hasan
 
Java: Class Design Examples
Java: Class Design ExamplesJava: Class Design Examples
Java: Class Design Examples
Tareq Hasan
 

Recently uploaded (20)

Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Timber Pitch Roof Construction Measurement-2024.pptx
Timber Pitch Roof Construction Measurement-2024.pptxTimber Pitch Roof Construction Measurement-2024.pptx
Timber Pitch Roof Construction Measurement-2024.pptx
Tantish QS, UTM
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Fundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic CommunicationsFundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic Communications
Jordan Williams
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-26-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-26-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-26-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-26-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Unit 4: Long term- Capital budgeting and its types
Unit 4: Long term- Capital budgeting and its typesUnit 4: Long term- Capital budgeting and its types
Unit 4: Long term- Capital budgeting and its types
bharath321164
 
Envenomation---Clinical Toxicology. pptx
Envenomation---Clinical Toxicology. pptxEnvenomation---Clinical Toxicology. pptx
Envenomation---Clinical Toxicology. pptx
rekhapositivity
 
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd yearVitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
ARUN KUMAR
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Timber Pitch Roof Construction Measurement-2024.pptx
Timber Pitch Roof Construction Measurement-2024.pptxTimber Pitch Roof Construction Measurement-2024.pptx
Timber Pitch Roof Construction Measurement-2024.pptx
Tantish QS, UTM
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Fundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic CommunicationsFundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic Communications
Jordan Williams
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Unit 4: Long term- Capital budgeting and its types
Unit 4: Long term- Capital budgeting and its typesUnit 4: Long term- Capital budgeting and its types
Unit 4: Long term- Capital budgeting and its types
bharath321164
 
Envenomation---Clinical Toxicology. pptx
Envenomation---Clinical Toxicology. pptxEnvenomation---Clinical Toxicology. pptx
Envenomation---Clinical Toxicology. pptx
rekhapositivity
 
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd yearVitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
ARUN KUMAR
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 

Java: GUI

  • 1.  
  • 3. Introduction Graphical User Interface (GUI) Gives program distinctive “look” and “feel” Provides users with basic level of familiarity Built from GUI components (controls, widgets, etc.) User interacts with GUI component via mouse, keyboard, etc.
  • 4. GUI Programming Concepts in Java Java GUI ("Swing") has components Windows GUI has controls Unix GUI has widgets examples: labels, buttons, check boxes, radio buttons, text input boxes, pull down lists Java Swing components: JLabel, JButton, JCheckBox, JRadioButton, JTextField, JTextArea, JComboBox
  • 5. Java GUI history: the AWT AWT(JDK 1.0, 1.1): Abstract Window Toolkit package: java.awt, java.awt.event heavyweight components using native GUI system elements used for applets until most browsers supported JRE 1.2
  • 6. Swing in Java Swing(Java 2, JDK 1.2+) lightweight components that do not rely on the native GUI or OS “ look and feel” of Swing components are identical on different platforms can be customized Swing inherits from AWT AWT still used for events, layouts
  • 7. Swing Components in Java advanced GUI support. e.g. drag-and-drop package names: javax.swing, javax.swing.event components inherit from JComponent components are added to a top-level container: JFrame, JDialog, or JApplet.
  • 8. Lightweight vs. Heavyweight GUI Components Lightweight components Not tied directly to GUI components supported by underlying platform Heavyweight components Tied directly to the local platform AWT components Some Swing components
  • 9. Basic GUI Programming Steps in Java declare a container and components add components to one or more containers using a layout manager register event listener(s) with the components create event listener method(s)
  • 10. AWT Event Class Hierarchy EventObject AWTEvent ActionEvent ComponentEvent AdjustmentEvent TextEvent ItemEvent ContainerEvent MouseEvent keyEvent FocusEvent InputEvent PaintEvent WindowEvent
  • 11. AWT Events Component Event Generated Generate When Button ActionEvent Clicked Selected or deselected Moved, resized, hidden or shown Checkbox CheckboxMenuItem Gained or loses fccus Pressed or released ComponentEvent Component Double Clicked ItemEvent Container ContainerEvent Added or removed ItemEvent ItemEvent Selected or deselected Selected or deselected Choice FocusEvent KeyEvent List ActionEvent ItemEvent Selected or deselected Selected ActionEvent MenuItem Moved AdjustmentEvent Scrollbar Changed TextEvent TextComponent Completed editing TextEvent TextField Opened, closed, iconified, deiconified, etc. WindowEvent Window
  • 12. Events Delegation Model User Action Source Object Triggering an event Target/Listener Object Event Object Registering for an event Creating an event Notify Event Listener Handle event Event Handler
  • 13. Some basic GUI components.
  • 14. Swing Overview Swing GUI components Package javax.swing Components originate from AWT (package java.awt ) Contain look and feel Appearance and how users interact with program Lightweight components Written completely in Java
  • 15. 12.2 Swing Overview (cont.) Class Component Contains method paint for drawing Component onscreen Class Container Collection of related components Contains method add for adding components Class JComponent Pluggable look and feel for customizing look and feel Shortcut keys ( mnemonics ) Common event-handling capabilities
  • 16. Fig. 12.3 Common superclasses of many of the Swing components.
  • 17. 12.3 JLabel Label Provide text on GUI Defined with class JLabel Can display: Single line of read-only text Image Text and image
  • 18. 1 // Fig. 12.4: LabelTest.java 2 // Demonstrating the JLabel class. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class LabelTest extends JFrame { 12 private JLabel label1, label2, label3; 13 14 // set up GUI 15 public LabelTest() 16 { 17 super ( "Testing JLabel" ); 18 19 // get content pane and set its layout 20 Container container = getContentPane(); 21 container.setLayout( new FlowLayout() ); 22 23 // JLabel constructor with a string argument 24 label1 = new JLabel( "Label with text" ); 25 label1.setToolTipText( "This is label1" ); 26 container.add( label1 ); 27 28 // JLabel constructor with string, Icon and 29 // alignment arguments 30 Icon bug = new ImageIcon( "bug1.gif" ); 31 label2 = new JLabel( "Label with text and icon" , 32 bug, SwingConstants. LEFT ); 33 label2.setToolTipText( "This is label2" ); 34 container.add( label2 ); 35 LabelTest.java Line 12 Line 24 Line 25 Lines 31-32 Declare three JLabel s Create first JLabel with text “ Label with text ” Create second JLabel with text to left of image Tool tip is text that appears when user moves cursor over JLabel
  • 19. 36 // JLabel constructor no arguments 37 label3 = new JLabel(); 38 label3.setText( "Label with icon and text at bottom" ); 39 label3.setIcon( bug ); 40 label3.setHorizontalTextPosition( SwingConstants. CENTER ); 41 label3.setVerticalTextPosition( SwingConstants. BOTTOM ); 42 label3.setToolTipText( "This is label3" ); 43 container.add( label3 ); 44 45 setSize( 275 , 170 ); 46 setVisible( true ); 47 } 48 49 // execute application 50 public static void main( String args[] ) 51 { 52 LabelTest application = new LabelTest(); 53 54 application.setDefaultCloseOperation( 55 JFrame. EXIT_ON_CLOSE ); 56 } 57 58 } // end class LabelTest LabelTest.java Lines 37-41 Create third JLabel with text below image
  • 20. 12.4 Event-Handling Model GUIs are event driven Generate events when user interacts with GUI e.g., moving mouse, pressing button, typing in text field, etc. Class java.awt.AWTEvent
  • 21. Fig. 12.5 Some event classes of package java.awt.event
  • 22. 12.4 Event-Handling Model (cont.) Event-handling model Three parts Event source GUI component with which user interacts Event object Encapsulates information about event that occurred Event listener Receives event object when notified, then responds Programmer must perform two tasks Register event listener for event source Implement event-handling method (event handler)
  • 23. Fig. 12.6 Event-listener interfaces of package java.awt.event
  • 24. 12.5 JTextField and JPasswordField JTextField Single-line area in which user can enter text JPasswordField Extends JTextField Hides characters that user enters
  • 25. 1 // Fig. 12.7: TextFieldTest.java 2 // Demonstrating the JTextField class. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class TextFieldTest extends JFrame { 12 private JTextField textField1, textField2, textField3; 13 private JPasswordField passwordField; 14 15 // set up GUI 16 public TextFieldTest() 17 { 18 super ( "Testing JTextField and JPasswordField" ); 19 20 Container container = getContentPane(); 21 container.setLayout( new FlowLayout() ); 22 23 // construct textfield with default sizing 24 textField1 = new JTextField( 10 ); 25 container.add( textField1 ); 26 27 // construct textfield with default text 28 textField2 = new JTextField( "Enter text here" ); 29 container.add( textField2 ); 30 31 // construct textfield with default text and 32 // 20 visible elements and no event handler 33 textField3 = new JTextField( "Uneditable text field" , 20 ); 34 textField3.setEditable( false ); 35 container.add( textField3 ); TextFieldTest.java Lines 12-13 Line 24 Line 28 Lines 33-34 Declare three JTextField s and one JPasswordField First JTextField contains empty string Second JTextField contains text “ Enter text here ” Third JTextField contains uneditable text
  • 26. 36 37 // construct textfield with default text 38 passwordField = new JPasswordField( "Hidden text" ); 39 container.add( passwordField ); 40 41 // register event handlers 42 TextFieldHandler handler = new TextFieldHandler(); 43 textField1.addActionListener( handler ); 44 textField2.addActionListener( handler ); 45 textField3.addActionListener( handler ); 46 passwordField.addActionListener( handler ); 47 48 setSize( 325 , 100 ); 49 setVisible( true ); 50 } 51 52 // execute application 53 public static void main( String args[] ) 54 { 55 TextFieldTest application = new TextFieldTest(); 56 57 application.setDefaultCloseOperation( 58 JFrame. EXIT_ON_CLOSE ); 59 } 60 61 // private inner class for event handling 62 private class TextFieldHandler implements ActionListener { 63 64 // process text field events 65 public void actionPerformed( ActionEvent event ) 66 { 67 String string = "" ; 68 69 // user pressed Enter in JTextField textField1 70 if ( event.getSource() == textField1 ) TextFieldTest.java Line 38 Lines 43-46 Line 62 Line 65 JPasswordField contains text “ Hidden text ,” but text appears as series of asterisks ( * ) Every TextFieldHandler instance is an ActionListener Register GUI components with TextFieldHandler (register for ActionEvent s) Method actionPerformed invoked when user presses Enter in GUI field
  • 27. 71 string = "textField1: " + event.getActionCommand(); 72 73 // user pressed Enter in JTextField textField2 74 else if ( event.getSource() == textField2 ) 75 string = "textField2: " + event.getActionCommand(); 76 77 // user pressed Enter in JTextField textField3 78 else if ( event.getSource() == textField3 ) 79 string = "textField3: " + event.getActionCommand(); 80 81 // user pressed Enter in JTextField passwordField 82 else if ( event.getSource() == passwordField ) { 83 JPasswordField pwd = 84 ( JPasswordField ) event.getSource(); 85 string = "passwordField: " + 86 new String( passwordField.getPassword() ); 87 } 88 89 JOptionPane.showMessageDialog( null , string ); 90 } 91 92 } // end private inner class TextFieldHandler 93 94 } // end class TextFieldTest TextFieldTest.java
  • 29. 12.5.1 How Event Handling Works Two open questions from Section 12.4 How did event handler get registered? Answer: Through component’s method addActionListener Lines 43-46 of TextFieldTest.java How does component know to call actionPerformed ? Answer: Event is dispatched only to listeners of appropriate type Each event type has corresponding event-listener interface Event ID specifies event type that occurred
  • 30. Fig 12.8 Event registration for JTextField textField1 .
  • 31. 12.6 JButton Button Component user clicks to trigger a specific action Several different types Command buttons Check boxes Toggle buttons Radio buttons javax.swing.AbstractButton subclasses Command buttons are created with class JButton Generate ActionEvent s when user clicks button
  • 32. Fig. 12.9 The button heirarchy.
  • 33. 1 // Fig. 12.10: ButtonTest.java 2 // Creating JButtons. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class ButtonTest extends JFrame { 12 private JButton plainButton, fancyButton; 13 14 // set up GUI 15 public ButtonTest() 16 { 17 super ( "Testing Buttons" ); 18 19 // get content pane and set its layout 20 Container container = getContentPane(); 21 container.setLayout( new FlowLayout() ); 22 23 // create buttons 24 plainButton = new JButton( "Plain Button" ); 25 container.add( plainButton ); 26 27 Icon bug1 = new ImageIcon( "bug1.gif" ); 28 Icon bug2 = new ImageIcon( "bug2.gif" ); 29 fancyButton = new JButton( "Fancy Button" , bug1 ); 30 fancyButton.setRolloverIcon( bug2 ); 31 container.add( fancyButton ); 32 33 // create an instance of inner class ButtonHandler 34 // to use for button event handling 35 ButtonHandler handler = new ButtonHandler(); ButtonTest.java Line 12 Line 24 Lines 27-30 Line 35 Create two references to JButton instances Instantiate JButton with text Instantiate JButton with image and rollover image Instantiate ButtonHandler for JButton event handling
  • 34. 36 fancyButton.addActionListener( handler ); 37 plainButton.addActionListener( handler ); 38 39 setSize( 275 , 100 ); 40 setVisible( true ); 41 } 42 43 // execute application 44 public static void main( String args[] ) 45 { 46 ButtonTest application = new ButtonTest(); 47 48 application.setDefaultCloseOperation( 49 JFrame. EXIT_ON_CLOSE ); 50 } 51 52 // inner class for button event handling 53 private class ButtonHandler implements ActionListener { 54 55 // handle button event 56 public void actionPerformed( ActionEvent event ) 57 { 58 JOptionPane.showMessageDialog( null , 59 "You pressed: " + event.getActionCommand() ); 60 } 61 62 } // end private inner class ButtonHandler 63 64 } // end class ButtonTest ButtonTest.java Lines 36-37 Lines 56-60 Register JButton s to receive events from ButtonHandler When user clicks JButton , ButtonHandler invokes method actionPerformed of all registered listeners