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();

More Related Content

PPT
GUI Programming In Java
PPTX
Java- GUI- Mazenet solution
PPTX
GUI Programming in JAVA (Using Netbeans) - A Review
PPT
Graphical User Interface (GUI) - 1
PDF
PPT
Swing and Graphical User Interface in Java
PPT
Swing and AWT in java
PPTX
GUI components in Java
GUI Programming In Java
Java- GUI- Mazenet solution
GUI Programming in JAVA (Using Netbeans) - A Review
Graphical User Interface (GUI) - 1
Swing and Graphical User Interface in Java
Swing and AWT in java
GUI components in Java

What's hot (20)

PPTX
PDF
The AWT and Swing
PPT
Awt and swing in java
PPTX
GUI programming
PPT
Java: GUI
PPTX
tL19 awt
PPTX
PPTX
Complete java swing
PPT
java swing
PPT
Awt controls ppt
PPTX
JAVA AWT
PPTX
Graphical User Interface (Gui)
PPTX
Java swing
PPTX
Chapter 1 swings
PPT
Basic of Abstract Window Toolkit(AWT) in Java
PPT
Java swing
PPT
Graphical User Interface in JAVA
PDF
Java awt tutorial javatpoint
PPT
28 awt
PPT
java2 swing
The AWT and Swing
Awt and swing in java
GUI programming
Java: GUI
tL19 awt
Complete java swing
java swing
Awt controls ppt
JAVA AWT
Graphical User Interface (Gui)
Java swing
Chapter 1 swings
Basic of Abstract Window Toolkit(AWT) in Java
Java swing
Graphical User Interface in JAVA
Java awt tutorial javatpoint
28 awt
java2 swing
Ad

Viewers also liked (20)

PPT
Gu iintro(java)
PPT
Mental models
DOCX
Modul oop with java application mauludin
ZIP
The Game Of Life - Java‘s Siblings and Heirs are populating the Ecosystem
PDF
KC Java Android Talk (March 2011)
PPT
First Steps in Android
PPTX
Introduction to Android Development
PDF
Google I/O 2013 報告会 Android Studio と Gradle
PPT
12 gui concepts 1
PPT
OOP in Java
PDF
Games and Java ME - Have fun and earn some money
KEY
Practical OOP In Java
PPT
java swing
PDF
Gui programming (awt)
KEY
Android Development: The Basics
PPTX
Contingency theory of management
PPT
Android ppt
PDF
Android for Java Developers
PPT
Object Oriented Programming Concepts
PPTX
Introduction to java
Gu iintro(java)
Mental models
Modul oop with java application mauludin
The Game Of Life - Java‘s Siblings and Heirs are populating the Ecosystem
KC Java Android Talk (March 2011)
First Steps in Android
Introduction to Android Development
Google I/O 2013 報告会 Android Studio と Gradle
12 gui concepts 1
OOP in Java
Games and Java ME - Have fun and earn some money
Practical OOP In Java
java swing
Gui programming (awt)
Android Development: The Basics
Contingency theory of management
Android ppt
Android for Java Developers
Object Oriented Programming Concepts
Introduction to java
Ad

Similar to GUI Programming with Java (20)

PPT
14a-gui.ppt
PPT
Swing basics
PPTX
Logic and Coding of Java Interfaces & Swing Applications
PDF
28-GUI application.pptx.pdf
PPT
Windows Programming with AWT
PPTX
Creating GUI.pptx Gui graphical user interface
PPTX
PDF
Java OOP Programming language (Part 7) - Swing
PPTX
awt and swing new (Abstract Window Toolkit).pptx
PPT
Chapter 5 GUI for introduction of java and gui .ppt
PPT
13457272.ppt
PPTX
SWING USING JAVA WITH VARIOUS COMPONENTS
PPTX
Introduction to java netbeans
PDF
Swingpre 150616004959-lva1-app6892
PDF
Getting started with GUI programming in Java_1
PPTX
A Simple Java GUI Application.pptx
PPT
L11cs2110sp13
PPT
Md10 building java gu is
14a-gui.ppt
Swing basics
Logic and Coding of Java Interfaces & Swing Applications
28-GUI application.pptx.pdf
Windows Programming with AWT
Creating GUI.pptx Gui graphical user interface
Java OOP Programming language (Part 7) - Swing
awt and swing new (Abstract Window Toolkit).pptx
Chapter 5 GUI for introduction of java and gui .ppt
13457272.ppt
SWING USING JAVA WITH VARIOUS COMPONENTS
Introduction to java netbeans
Swingpre 150616004959-lva1-app6892
Getting started with GUI programming in Java_1
A Simple Java GUI Application.pptx
L11cs2110sp13
Md10 building java gu is

More from Jussi Pohjolainen (20)

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

Recently uploaded (20)

PPTX
Onco Emergencies - Spinal cord compression Superior vena cava syndrome Febr...
PPTX
Virtual and Augmented Reality in Current Scenario
PDF
advance database management system book.pdf
PDF
AI-driven educational solutions for real-life interventions in the Philippine...
PDF
Empowerment Technology for Senior High School Guide
PDF
FORM 1 BIOLOGY MIND MAPS and their schemes
PDF
1.3 FINAL REVISED K-10 PE and Health CG 2023 Grades 4-10 (1).pdf
PDF
HVAC Specification 2024 according to central public works department
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
DOCX
Cambridge-Practice-Tests-for-IELTS-12.docx
PDF
احياء السادس العلمي - الفصل الثالث (التكاثر) منهج متميزين/كلية بغداد/موهوبين
PPTX
TNA_Presentation-1-Final(SAVE)) (1).pptx
PPTX
Computer Architecture Input Output Memory.pptx
PDF
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
PPTX
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
PDF
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
PDF
Complications of Minimal Access-Surgery.pdf
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PDF
Τίμαιος είναι φιλοσοφικός διάλογος του Πλάτωνα
Onco Emergencies - Spinal cord compression Superior vena cava syndrome Febr...
Virtual and Augmented Reality in Current Scenario
advance database management system book.pdf
AI-driven educational solutions for real-life interventions in the Philippine...
Empowerment Technology for Senior High School Guide
FORM 1 BIOLOGY MIND MAPS and their schemes
1.3 FINAL REVISED K-10 PE and Health CG 2023 Grades 4-10 (1).pdf
HVAC Specification 2024 according to central public works department
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
Cambridge-Practice-Tests-for-IELTS-12.docx
احياء السادس العلمي - الفصل الثالث (التكاثر) منهج متميزين/كلية بغداد/موهوبين
TNA_Presentation-1-Final(SAVE)) (1).pptx
Computer Architecture Input Output Memory.pptx
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
Complications of Minimal Access-Surgery.pdf
Paper A Mock Exam 9_ Attempt review.pdf.
LDMMIA Reiki Yoga Finals Review Spring Summer
Τίμαιος είναι φιλοσοφικός διάλογος του Πλάτωνα

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();