241-211 OOP (Java): GUI I/12 1 241-211. OOP Objectives – –describe some of the GUI controls and their listeners; more appear in part 13 Semester 2, 2013-2014.

Slides:



Advertisements
Similar presentations
CS18000: Problem Solving and Object-Oriented Programming.
Advertisements

Fall 2007CS 225 Graphical User Interfaces Event Handling Appendix C.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Creating a GUI with Swing. Introduction Very useful link: Swing – is a part of JFC (Java Foundation.
Lecture 19 Graphics User Interfaces (GUIs)
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
1 Class 8. 2 Chapter Objectives Use Swing components to build the GUI for a Swing program Implement an ActionListener to handle events Add interface components.
AWT and Swing  Most GUI class libraries in C++ are platform specific Different hardware capabilities Different hardware capabilities Subtle differences.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 13 Creating User.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
JCheckBox and JRadioButton State buttons –On/Off or true / false values –Java provides three types JToggleButton JCheckBox JRadioButton.
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Introduction to Swing Components Chapter 14.  Part of the Java Foundation Classes (JFC)  Provides a rich set of GUI components  Used to create a Java.
GUI Chapter 10 Graphics context and objects Creating a window based application JFrame, JTextField, JButton Containers and Controls Graphics commands Layout.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
SWING. AbstractButton Swing Buttons are subclasses of the AbstractButton class, which extends JComponent. Abstract class javax.swing.AbstractButton AbstractButton.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
AWT and Swing Most GUI class libraries in C++ are platform specific
Introduction to GUI Programming with Java Graphical User Interfaces With AWT and Swing Towson University *Ref:
OOP (Java): GUI Intro/ OOP Objectives – –use an image viewer application to introduce Java's GUI features Semester 2,
Class Class 20 Objectives Use JCheckbox, JRadioButton, and a JComboBox in a UID.
 2002 Prentice Hall, Inc. All rights reserved. Graphical User Interface Components 1 Introduction 2 Swing Overview 3 JLabel 4 Event-Handling Model 5 JTextField.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
GUI Basics. Agenda What GUI How to make in java Creating frames Frequently used GUI components Layout Managers.
Swing. Introduction to Swing What is Swing? “ Swing is a diverse collection of lightweight components that can be used to build sophisticated user interfaces.”
Graphical User Interface Components: Part 1 Chapter 11.
Basics of GUI Programming Chapter 11 and Chapter 22.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
Java Programming, Second Edition Chapter Thirteen Understanding Swing Components.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 4 – Completing the Inventory Application.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
Computer Science [3] Java Programming II - Laboratory Course Lab 4 -1 : Introduction to Graphical user interface GUI Components Faculty of Engineering.
Event-Driven Programming F Procedural programming is executed in procedural order. F In event-driven programming, code is executed upon activation of events.
 Figure illustrates a hierarchy containing many event classes from the package java.awt.event.  Used with both AWT and Swing components.  Additional.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 12 - Graphical User Interface Components: Part 1 Outline 12.1 Introduction 12.2 Swing Overview.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 17.1 Test-Driving the Student Grades Application.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Graphical User Interface (GUI)
1 Chapter 13 – More GUI Components Introduction Graphical User Interface (GUI) –Gives program distinctive “look” and “feel” –Provides users with basic.
1 Lecture 8: User Interface Components with Swing.
Jozef Goetz Credits: Copyright  Pearson Education, Inc. All rights reserved. expanded by J. Goetz, 2016.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Java Swing. Graphical User Interfaces (GUIs) GUI: An application that uses graphical objects to interact with users GUI applications consist of: – Events:
CIS 270—Application Development II Chapter 11—GUI Components: Part I.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
Dept. of CSIE, National University of Tainan 10/21/2012 Working with Swing.
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
Dept. of CSIE, National University of Tainan 10/21/2012 Responding to User Input.
Chapter 6 Building Java GUIs. MVC Model View Controller The model passes its data to the view for rendering The view determines which events are passed.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
GUIs and Events Rick Mercer.
CSC 205 Programming II Lecture 5 AWT - I.
Introduction to Graphics
Appendix I GUI Components and Event Handling
A First Look at GUI Applications
Graphical User Interface (GUI) Components: Part 1 Java How to Program, 9 th Edition Chapter 14.
Chapter 13: Advanced GUIs and Graphics
IFS410: Advanced Analysis and Design
Chapter 13 - Graphical User Interface Components: Part 1
AWT and Swing Most GUI class libraries in C++ are platform specific
Advanced GUIs and Graphics
Presentation transcript:

OOP (Java): GUI I/ OOP Objectives – –describe some of the GUI controls and their listeners; more appear in part 13 Semester 2, GUI Examples I

OOP (Java): GUI I/12 2 Contents 1.Three Step GUI 2.Swing GUI Overview 3.Swing Hierarchy 4.Listener Interfaces 5.Button Example 6.TextField Example 7. Check Boxes Example 8.Radio Buttons Example 9.Combo Box Example

OOP (Java): GUI I/ Three Step GUI There are three main steps to creating a GUI for a Java application: – –1. Declare the GUI components; – –2. Implement the event handlers for the components; – –3. Position the components on the screen by using layout managers and/or containers. this part and part 13

OOP (Java): GUI I/ Swing GUI Overview The Swing GUI has six categories: – –basic components – –uneditable displays – –interactive displays of highly formatted info – –general-purpose containers – –top-level containers – –special-purpose containers We will look at code examples using the GUI components listed in bold.

OOP (Java): GUI I/ Basic Components ComponentSwing Class Name – –buttonJButton, JCheckBox, JRadioButton – –combo boxJComboBox – –listJList – –menuJMenu, JMenuBar, JMenuItem – –sliderJSlider – –text fieldJTextField, JPasswordField

OOP (Java): GUI I/12 6 These pictures are from the Java tutorial on Swing also known as a pop-down list

OOP (Java): GUI I/ Uneditable Displays DisplaySwing Class Name – –labelJLabel – –TooltipJToolTip – –Progress barJProgressBar

OOP (Java): GUI I/ Interactive Displays DisplaySwing Class Name – –tableJTable – –textJTextPane, JTextArea, JEditorPane – –treeJColorChooser – –file chooserJFileChooser

OOP (Java): GUI I/12 9

General Purpose Containers ContainerSwing Class Name – –panelJPanel – –scroll paneJScrollPane, JScrollBar – –split paneJSplitPane – –tabbed paneJTabbedPane – –toolbarJToolbar

OOP (Java): GUI I/12 11

OOP (Java): GUI I/ Top-level Containers ContainerSwing Class Name – –frameJFrame – –appletJApplet – –dialogJDialog, JOptionPane

OOP (Java): GUI I/12 13

OOP (Java): GUI I/ Special-Purpose Containers ContainerSwing Class Name – –internal frame JInternalFrame – –layered paneJLayeredPane – –root paneJRootPane indirectly used by top-level containers to gain access to the content pane and other 'layers' of a container

OOP (Java): GUI I/12 15

OOP (Java): GUI I/ Swing Hierarchy (partial) java.lang.Object java.awt.Component (abstract) java.awt.Container javax.swing.JComponent (abstract) continued extends Swing uses a AWT component to draw the blank window area. The GUI in the window is drawn by Swing.

OOP (Java): GUI I/12 17 AbstractButton (abstract) JMenuItemJMenu JToggleButtonJRadioButton JCheckBox JButton JTextComponent (abstract) JEditorPane JTextField JTextArea JLabel JPanel JScrollPane GUI controls inherit many methods. JToolTip Not the whole hierarchy extends

OOP (Java): GUI I/12 18 What is JComponent? JComponent is the Swing ancestor of most things that appear in a GUI. It holds common information such as: – –size (preferred, minimum, maximum) – –accessibility, internationalization – –keyboard control support – –thickness of lines around controls – –debugging features

OOP (Java): GUI I/ Listener Interfaces I'll look at 4 listener interfaces that can handle events from different GUI components – –ActionListener – –ItemListener – –MouseListener – –MouseMotionListener There are several other listener interfaces. I'll use these two in this part in part 13

OOP (Java): GUI I/ ActionListener ActionListener can deal with events from: – –JButton (most common) – –JMenu, JMenuItem, JRadioButton, JCheckBox when pressed – –JTextField when is typed The interface has one method: public void actionPerformed(ActionEvent e)

OOP (Java): GUI I/12 21 Using the Listener The GUI component must be linked to code which implements the method in the listener. button GUI Window the link which sends an event e public class Foo implements ActionListener { public void actionPerformed( ActionEvent e ) { // do something with e System.out.println("Ouch"); } }

OOP (Java): GUI I/ ItemListener ItemListener can deal with events from: – –JMenu, JMenuItem, JRadioButton, JCheckBox (most common) – –JButton when an item is selected/pressed The interface has one method: public void itemStateChanged(ItemEvent e)

OOP (Java): GUI I/12 23 Using the Listener The GUI component must be linked to code which implements the method in the listener. GUI Window the link which sends an event e public class Foo2 implements ItemListener { public void itemStateChanged( ItemEvent e ) { // do something with e System.out.println("EEEk"); } } menu

OOP (Java): GUI I/ Button Example Output to the DOS window after three presses: Pressed 1 Pressed 2 Pressed 3

OOP (Java): GUI I/12 25 Event Model Press me GUI int pressCount = 1; methods actionPerfomed() anon class press event

OOP (Java): GUI I/12 26 Steps in GUI Creation The GUI is initialised in the class' constructor method. Initialisation steps: – –1. get the container for the frame – –2. set the layout manager ( FlowLayout ) – –3. declare the GUI components – –4. add them to the container – –5. register the components with event handlers – –6. set window properties

OOP (Java): GUI I/12 27 ButtonTest.java import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ButtonTest extends JFrame { private int pressCount = 1; public ButtonTest() { super( "Testing JButton" ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); : step 1 step 2

OOP (Java): GUI I/12 28 // JButton with a string argument JButton jb = new JButton( "Press me" ); c.add( jb ); // Handle events from pressing the button jb.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Pressed " + pressCount++ ); } } ); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack( ); setVisible( true ); } // end of LabelTest() step 3 step 4 step 6 step 5

OOP (Java): GUI I/12 29 public static void main( String args[] ) { new ButtonTest(); } } // end of ButtonTest class

OOP (Java): GUI I/12 30 Notes The global variable pressCount remembers the number of presses between calls to actionPerformed(). The only information passed as an argument to actionPerformed() is the event object e – –other information must be stored globally

OOP (Java): GUI I/ TextField Example After typing enter, the text disappears from the field, and " You entered andrew " appears in the DOS window.

OOP (Java): GUI I/12 32 Event Model GUI methods actionPerfomed() anon class type enter event Enter...: jtf

OOP (Java): GUI I/12 33 TextFieldTest.java // The JTextField GUI in a Java app import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TextFieldTest extends JFrame { private JTextField jtf; // global since used in actionPerformed() public TextFieldTest() { super( "Testing JTextField" ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); :

OOP (Java): GUI I/12 34 // label and text entry field JLabel jl = new JLabel("Enter your name:"); jtf = new JTextField(25); // 25 chars wide c.add( jl ); c.add( jtf ); // Handle events from pressing return jtf.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("You entered " + e.getActionCommand() ); jtf.setText( "" ); } } ); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(500,100); setVisible(true); } // end of TextFieldTest()

OOP (Java): GUI I/12 35 public static void main( String args[] ) { new TextFieldTest(); } } // end of TextFieldTest class

OOP (Java): GUI I/12 36 Notes The JTextField object, jtf, is global – –this means that actionPerformed() can affect it – –it sets the text to empty ( "" ) after printing a message to stdout The text inside the text field is accessed through the event object: – –e.getActionCommand()

OOP (Java): GUI I/ Check Boxes Example Output to DOS window when first two boxes are checked/ unchecked

OOP (Java): GUI I/12 38 Event Model GUI methods actionPerfomed() anon classes itemStateChanged() select/ deselect event press event I could use itemStateChanged() to process all the events

OOP (Java): GUI I/12 39 Features – –creates 4 JCheckBox objects in an application – –an anonymous class implements actionListener actionPerformed() is called when the user presses the "Pepperoni" check box – –an anonymous class implements itemListener itemStateChanged() is called when the "Mushroom" box is 'ticked' or 'unticked'

OOP (Java): GUI I/12 40 CheckBoxTest.java import javax.swing.*; import java.awt.*; import java.awt.event.*; public class CheckBoxTest extends JFrame { public CheckBoxTest() { super( "Testing JCheckBox" ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); :

OOP (Java): GUI I/12 41 // 4 checkboxes JCheckBox jck1 = new JCheckBox("Pepperoni"); JCheckBox jck2 = new JCheckBox("Mushroom"); JCheckBox jck3 = new JCheckBox("Black olives"); JCheckBox jck4 = new JCheckBox("Tomato"); c.add( jck1 ); c.add( jck2 ); c.add( jck3 ); c.add( jck4 ); // actionListener for pepperoni box jck1.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("event = " + e); } } ); :

OOP (Java): GUI I/12 42 // itemListener for mushroom box jck2.addItemListener( new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == e.SELECTED) System.out.print("selected "); else System.out.print("de-selected "); System.out.print("Mushroom\n"); } } ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); setSize(500,100); setVisible(true); } // end of CheckBoxTest()

OOP (Java): GUI I/12 43 public static void main( String args[] ) { new CheckBoxTest(); } } // end of CheckBoxTest class

OOP (Java): GUI I/12 44 Notes addItemListener() is used to register an ItemListener with a control. The anonymous class must implement ItemListener 's itemStateChanged() method. itemStateChanged() uses e.getStateChanged() to see if the box was ticked or unticked. continued

OOP (Java): GUI I/12 45 actionPerformed() shows that an event object can be printed – –sometimes useful for debugging

OOP (Java): GUI I/ Radio Buttons Example click on radio buttons

OOP (Java): GUI I/12 47 Event Model methods Watch the font... RadioButtonHandler inner class itemStateChanged(...) { // alter t }

OOP (Java): GUI I/12 48 Features – –creates four JRadioButton objects in the application – –a RadioButtonHandler inner class implements ItemListener itemStateChanged() is called when the user selects/deselects any of the radio buttons – –a ButtonGroup object which forces only one radio button to be 'on' at a time

OOP (Java): GUI I/12 49 RadioButtonTest.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class RadioButtonTest extends JFrame { private JTextField t; private Font plainFont, boldFont, italicFont, boldItalicFont; private JRadioButton plain, bold, italic, boldItalic; :

OOP (Java): GUI I/12 50 public RadioButtonTest() { super( "RadioButton Test" ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); t = new JTextField( "Watch the font style change", 25 ); c.add( t ); // Create radio buttons plain = new JRadioButton( "Plain", true ); c.add( plain ); bold = new JRadioButton( "Bold", false); c.add( bold ); italic = new JRadioButton( "Italic", false ); c.add( italic ); boldItalic = new JRadioButton( "Bold/Italic", false ); c.add( boldItalic ); :

OOP (Java): GUI I/12 51 // register all controls with 1 handler RadioButtonHandler handler = new RadioButtonHandler(); plain.addItemListener( handler ); bold.addItemListener( handler ); italic.addItemListener( handler ); boldItalic.addItemListener( handler ); // create link between JRadioButtons ButtonGroup radioGroup = new ButtonGroup(); radioGroup.add( plain ); radioGroup.add( bold ); radioGroup.add( italic ); radioGroup.add( boldItalic ); :

OOP (Java): GUI I/12 52 plainFont = new Font( "TimesRoman", Font.PLAIN, 14 ); boldFont = new Font( "TimesRoman", Font.BOLD, 14 ); italicFont = new Font( "TimesRoman", Font.ITALIC, 14 ); boldItalicFont = new Font( "TimesRoman", Font.BOLD + Font.ITALIC, 14 ); t.setFont( plainFont ); :

OOP (Java): GUI I/12 53 setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); setSize(300,100); setVisible(true); } // end of RadioButtonTest() public static void main( String args[] ) { new RadioButtonTest() }

OOP (Java): GUI I/12 54 class RadioButtonHandler implements ItemListener { public void itemStateChanged( ItemEvent e ) { if (e.getStateChange() == ItemEvent.SELECTED) { if ( e.getSource() == plain ) t.setFont( plainFont ); else if ( e.getSource() == bold ) t.setFont( boldFont ); else if ( e.getSource() == italic ) t.setFont( italicFont ); else if ( e.getSource() == boldItalic ) t.setFont( boldItalicFont ); t.repaint(); } } } // end of RadioButtonHandler class } // end of RadioButtonTest class Still inside RadioButtonTest

OOP (Java): GUI I/12 55 Notes This example shows the use of an inner class to implement event handling: – –RadioButtonHandler implements ItemListener The other two approaches: – –anonymous classes – –have the program implement the event listener itself continued

OOP (Java): GUI I/12 56 This example shows that several controls can have the same event handler – –all 4 buttons use a single RadioButtonHandler object The ButtonGroup object is not visible on the screen.

OOP (Java): GUI I/ Combo Box Example select travelbug.gif

OOP (Java): GUI I/12 58 Event Model methods anon class itemStateChanged() select item event

OOP (Java): GUI I/12 59 Features – –creates a JComboBox object in an application (a combo box is a drop-down list) – –the selection updates an image inside a label – –an anonymous class implements itemListener itemStateChanged() is called when the user clicks on one of the items on the list

OOP (Java): GUI I/12 60 ComboBoxTest.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ComboBoxTest extends JFrame { private JComboBox imNmsList; private JLabel label; private String names[] = { "bug1.gif", "bug2.gif", "travelbug.gif", "buganim.gif"}; private ImageIcon icons[]; :

OOP (Java): GUI I/12 61 public ComboBoxTest() { super("Testing JComboBox"); icons = new Icon[names.length]; for(int i=0; i < names.length; i++) icons[i] = new ImageIcon(names[i]); Container c = getContentPane(); c.setLayout(new FlowLayout()); label = new JLabel(icons[0]); c.add(label); :

OOP (Java): GUI I/12 62 imNmsList = new JComboBox(names); imNmsList.setMaximumRowCount(3); c.add(imNmsList); imNmsList.addItemListener( new ItemListener() { public void itemStateChanged(ItemEvent e) { label.setIcon(icons[ imNmsList.getSelectedIndex() ]); } }); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(350, 100); setVisible(true); } // end of ComboBoxTest() public static void main(String args[]) { new ComboBoxTest(); } } // end of ComboBoxTest class

OOP (Java): GUI I/12 63 Notes itemStateChanged() does not use the e event object; it checks the imNmsList combo box – –imNmsList.getSelectedIndex() – –returns the index of the item selected The image filenames are stored in an icon[] array, and used to update the label: – –label.setIcon( icon[...])