COMP 150: Introduction to Object-Oriented Programming 1 Lecturer: Dr. AJ Bieszczad l Event-Driven Programming and GUIs l Swing Basics and a Simple Demo.

Slides:



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

Graphic User Interfaces Layout Managers Event Handling.
CMSC 341 Building Java GUIs. 09/26/2007 CMSC 341 GUI 2 Why Java GUI Development? Course is about Data Structures, not GUIs. We are giving you the opportunity.
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
1 Chapter 12 l Event-Driven Programming and GUIs l Swing Basics and a Simple Demo Program l Layout Managers l Buttons and Action Listeners l Container.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Unit 091 Introduction to GUI Programming Introduction to User Interfaces Introduction to GUI Programming GUI Design Issues GUI Programming Issues Java.
Graphical User Interface (GUI) Programming III. Lecture Objectives Exploring more GUI programming elements in Java Using labels in GUIs Using colors to.
IEEM 110 Computing in Industrial Applications Basic User Interface in Java.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
GUI and Event-Driven Programming Recitation – 3/6/2009 CS 180 Department of Computer Science, Purdue University.
Chapter 121 Window Interfaces Using Swing Chapter 12.
CS102--Object Oriented Programming Lecture 19: – The Swing Package (II) Copyright © 2008 Xiaoyan Li.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
CS102--Object Oriented Programming Lecture 18: – The Swing Package Copyright © 2008 Xiaoyan Li.
Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
Scott Grissom, copyright 2006Ch 11: GUI Slide 1 Graphical User Interfaces (Ch 11) Careful design of a graphical user interface is key to a viable software.
Unit 11 Object-oriented programming: Graphical user interface Jin Sa.
Java Swing. Introduction to Swing A GUI (graphical user interface) is a windowing system that interacts with the user The Java AWT (Abstract Window Toolkit)
Java Programming Chapter 10 Graphical User Interfaces.
Programming With Java ICS201 University Of Ha’il1 Chapter 17 Graphical User Interfaces Swing I.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
Chapter 12- GUI’s, Java, and Swing.. Overview n What are GUI’s n How Java does GUI’s- Swing n Buttons n Containers n Text I/O and Swing n Review.
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.
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
Copyright © 2002, Systems and Computer Engineering, Carleton University c-Gui3.ppt * Object-Oriented Software Development Part 18-c Building.
Timer class and inner classes. Processing timer events Timer is part of javax.swing helps manage activity over time Use it to set up a timer to generate.
Chapter 12 1 TOPIC 13B l Buttons and Action Listeners Window Interfaces Using Swing Objects.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
Introduction to GUI Programming with Java Graphical User Interfaces With AWT and Swing Towson University *Ref:
Java Programming Applets. Topics Write an HTML document to host an applet Understand simple applets Use Labels with simple AWT applets Write a simple.
Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Computer Programming with JAVA Chapter 7. Event-Driven Programming Using the AWT Event-Driven Programming GUIs and the AWT Simple Window Interfaces Components,
Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 7 l Event-Driven Programming »GUIs and the AWT l Simple Window.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
Chapter 12Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 12 l Event-Driven Programming and GUIs l Swing Basics and.
Basics of GUI Programming Chapter 11 and Chapter 22.
PANELS. Color Class Colour constants are as follows: –Color.black –Color.blue import java.awt.* to access Color Class.
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.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
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)
Introduction to GUI Programming in Java: Frames, Simple Components, and Layouts.
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 Programming Fifth Edition Chapter 13 Introduction to Swing Components.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
GUIs and Events Rick Mercer.
Chapter 17 Swing I Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Christopher Budo, Davis Nygren, spencer franks, Luke miller
A First Look at GUI Applications
Graphical User Interface (pronounced "gooey")
Graphical User Interface (GUI) Programming III
Chapter 17 Swing I Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage Copyright © 2016 Pearson Inc. All.
Ellen Walker Hiram College
Comp 249 Programming Methodology
Window Interfaces Using Swing Objects Chapter 12
Window Interfaces Using Swing Objects Chapter 12
Graphical User Interface
Presentation transcript:

COMP 150: Introduction to Object-Oriented Programming 1 Lecturer: Dr. AJ Bieszczad l Event-Driven Programming and GUIs l Swing Basics and a Simple Demo Program l Layout Managers l Buttons and Action Listeners l Container Classes l Text I/O for GUIs l Inner Classes Window Interfaces Using Swing Objects

COMP 150: Introduction to Object-Oriented Programming 2 Lecturer: Dr. AJ Bieszczad Swing l Special library of classes that allows Java programs to have a windowing interface l Part of larger collection called Java Foundation Classes or JFC l An improved version of older library called Abstract Window Toolkit (AWT) l Standard part of all versions of Java 2 (JDK 1.2)

COMP 150: Introduction to Object-Oriented Programming 3 Lecturer: Dr. AJ Bieszczad GUIs—Graphical User Interfaces Most modern programs use a GUI GUI (pronounced “gooey”): l Graphical—not just text or characters: windows, menus, buttons, etc. l User—person using the program l Interface—way to interact with the program Typical graphical elements: l Window—portion of screen that serves as a smaller screen within the screen l Menu—list of alternatives offered to user l Button—looks like a button that can be pressed

COMP 150: Introduction to Object-Oriented Programming 4 Lecturer: Dr. AJ Bieszczad Event-Driven Programming l Programs with GUIs often use Event-Driven Programming l Program waits for events to occur and then responds l Examples of events: »Clicking a mouse button »Dragging the mouse »Pressing a key on the keyboard l Firing an event—when an object generates an event l Listener—object that waits for events to occur l Event handler—method that responds to an event

COMP 150: Introduction to Object-Oriented Programming 5 Lecturer: Dr. AJ Bieszczad A New Approach to Programming Previous Style of Programming: l List of instructions performed in order l Next thing to happen is next thing in list l Program performed by one agent—the computer Event-Driven Style of Programming: l Objects that can fire events and objects that react to events l Next thing to happen depends on next event l Program is interaction between user and computer

COMP 150: Introduction to Object-Oriented Programming 6 Lecturer: Dr. AJ Bieszczad Very Simple Swing Demonstration import javax.swing.*; public class FirstSwingDemo { public static final int WIDTH = 300; public static final int HEIGHT = 200; public static void main(String[] args) { JFrame myWindow = new JFrame(); myWindow.setSize(WIDTH, HEIGHT); JLabel myLabel = new JLabel(“Please don’t…”); myWindow.getContentPanel().add(myLabel); WindowDestroyer myListener = new WindowDestroyer(); myWindow.addWindowListener(myListener); myWindow.setVisible(true); }

COMP 150: Introduction to Object-Oriented Programming 7 Lecturer: Dr. AJ Bieszczad Notes on the Simple Demo Program import javax.swing.*; public class FirstSwingDemo { public static final int WIDTH = 300; public static final int HEIGHT = 200; public static void main(String[] args) { JFrame myWindow = new JFrame(); myWindow.setSize(WIDTH, HEIGHT); JLabel myLabel = new JLabel(“Please don’t…”); myWindow.getContentPanel().add(myLabel); WindowDestroyer myListener = new WindowDestroyer(); myWindow.addWindowListener(myListener); myWindow.setVisible(true); } Used in all Swing programs Creates a JFrame window named myWindow Adds a label to the JFrame window—note use of getContentPane

COMP 150: Introduction to Object-Oriented Programming 8 Lecturer: Dr. AJ Bieszczad Notes on the Simple Demo Program import javax.swing.*; public class FirstSwingDemo { public static final int WIDTH = 300; public static final int HEIGHT = 200; public static void main(String[] args) { JFrame myWindow = new JFrame(); myWindow.setSize(WIDTH, HEIGHT); JLabel myLabel = new JLabel(“Please don’t…”); myWindow.getContentPanel().add(myLabel); WindowDestroyer myListener = new WindowDestroyer(); myWindow.addWindowListener(myListener); myWindow.setVisible(true); } Allows the program to respond to the event of a user clicking in the close box. WindowDestroyer is a programmer-defined class.

COMP 150: Introduction to Object-Oriented Programming 9 Lecturer: Dr. AJ Bieszczad The WindowDestroyer Class public class WindowDestroyer extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } WindowAdapter is a class that includes all the methods required for window events. When a window closing event occurs, this method will be called and the program will quit.

COMP 150: Introduction to Object-Oriented Programming 10 Lecturer: Dr. AJ Bieszczad The Results of the Simple Demo Program import javax.swing.*; public class FirstSwingDemo { public static final int WIDTH = 300; public static final int HEIGHT = 200; public static void main(String[] args) { JFrame myWindow = new JFrame(); myWindow.setSize(WIDTH, HEIGHT); JLabel myLabel = new JLabel(“Please don’t…”); myWindow.getContentPanel().add(myLabel); WindowDestroyer myListener = new WindowDestroyer(); myWindow.addWindowListener(myListener); myWindow.setVisible(true); } The window will not show up on the screen without a line like this one.

COMP 150: Introduction to Object-Oriented Programming 11 Lecturer: Dr. AJ Bieszczad Window Listeners l Must have seven methods l Each method is associated with a window event, such as a window closing Can inherit all seven methods from WindowAdapter and override some methods WindowDestroyer (in the Simple Demo Program) inherits from WindowAdapter and overrides only the windowClosing method.

COMP 150: Introduction to Object-Oriented Programming 12 Lecturer: Dr. AJ Bieszczad A Better Version of the Simple Demo Program l Separate class for the window FirstWindow class inherits from JFrame main method creates two instances of FirstWindow l Each window has its own listener setVisible called from main for each window object

COMP 150: Introduction to Object-Oriented Programming 13 Lecturer: Dr. AJ Bieszczad The FirstWindow Class import javax.swing.*; public class FirstWindow extends JFrame { public static final int WIDTH = 300; public static final int HEIGHT = 200; public FirstWindow() { super(); setSize(WIDTH, HEIGHT); JLabel myLabel = new JLabel(“Please don’t…”); getContentPanel().add(myLabel); WindowDestroyer myListener = new WindowDestroyer(); addWindowListener(myListener); } Inherits from JFrame Calls constructor of base class setSize, getContentPanel, and addWindowListener methods are inherited from JFrame

COMP 150: Introduction to Object-Oriented Programming 14 Lecturer: Dr. AJ Bieszczad Methods of the JFrame Class l JFrame(String title) constructor for creating a JFrame with a title Container getContentPane() returns the content pane of the JFrame, which has the add method for adding components l void setBackgroundColor(Color c) l void setForegroundColor(Color c) l void setSize(int width, int height) l void setVisible(boolean b) void show() sets visible and brings to front

COMP 150: Introduction to Object-Oriented Programming 15 Lecturer: Dr. AJ Bieszczad Layout Managers l Layout Manager—an object that decides how components will be arranged in a container l Used because containers can change size l Some types of layout managers: »BorderLayout »FlowLayout »GridLayout l Each type of layout manager has rules about how to rearrange components when the size or shape of the container changes.

COMP 150: Introduction to Object-Oriented Programming 16 Lecturer: Dr. AJ Bieszczad The Border Layout Manager Five regions that can each have one component added to them: BorderLayout.NORTH BorderLayout.SOUTH BorderLayout.CENTER BorderLayout. WEST BorderLayout. EAST content.setLayout(new BorderLayout());... content.add(label1, BorderLayout.NORTH); The CENTER region grows the most when the container grows and shrinks the most when the container shrinks

COMP 150: Introduction to Object-Oriented Programming 17 Lecturer: Dr. AJ Bieszczad The Flow Layout Manager l The simplest layout manager l Displays components from left to right in the order they are added to the container l Add method has one parameter which is the component to add Container content = getContentPane(); content.setLayout(new FlowLayout()); JLabel label1 = new JLabel(“First label here”); content.add(label1); JLabel label2 = new JLabel(“Second label there”); content.add(label2);

COMP 150: Introduction to Object-Oriented Programming 18 Lecturer: Dr. AJ Bieszczad The Grid Layout Manager l Specify a number of rows and columns l All regions in the grid are equal size l When the container changes size, each region grows or shrinks by the same amount Creates a grid layout with two rows and three columns. aContainer.setLayout(new GridLayout(2, 3));... aContainer.add(label1); aContainer.add(label2); Rows are filled before columns.

COMP 150: Introduction to Object-Oriented Programming 19 Lecturer: Dr. AJ Bieszczad Buttons and ActionListeners Basic steps for using a button in a Swing program: l Create a Button object l Add the Button object to a container Create an ActionListener object that has an actionPerformed method l Register the listener for the Button object The following slides show an example of each step.

COMP 150: Introduction to Object-Oriented Programming 20 Lecturer: Dr. AJ Bieszczad Create a Button Object and Add the Button to a Container JButton stopButton = new JButton(“Red”); contentPane.add(stopButton); String that will appear on the button The button will be added to this container. JButton is a predefined Swing class for buttons. This example uses the Flow Layout so the add method needs only one parameter.

COMP 150: Introduction to Object-Oriented Programming 21 Lecturer: Dr. AJ Bieszczad Create an ActionListener Object Make a class into an ActionListener: Add the phrase implements ActionListener to the beginning of the class definition: Define a method named actionPerformed public class ButtonDemo extends JFrame implements ActionListener {... public void actionPerformed(ActionEvent e) {...

COMP 150: Introduction to Object-Oriented Programming 22 Lecturer: Dr. AJ Bieszczad The actionPerformed Method An actionPerformed method must have only one parameter The parameter must be of type ActionEvent The parameter can be used to find the command for the ActionEvent : By default, the action command of a button will be the string displayed on the button. public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Red"))... }

COMP 150: Introduction to Object-Oriented Programming 23 Lecturer: Dr. AJ Bieszczad Register the Listener for the Button Object l If a button has no listener registered for it, there will be no response when the user clicks on the button. l An example of registering a listener for a button: JButton stopButton = new JButton("Red"); stopButton.addActionListener(this); contentPane.add(stopButton); this refers to the object that includes this code in a method. In this example the object is a JFrame class that implements ActionListener.

COMP 150: Introduction to Object-Oriented Programming 24 Lecturer: Dr. AJ Bieszczad Interfaces Want ButtonDemo class to be both a JFrame and an ActionListener »can only derive from one class »derived class of JFrame »implements ActionListener interface l An interface is a property of a class that says what methods it must have. l To implement an interface a class must do two things: 1.include the phrase implements Interface_Name 2.implement all the method headings in the interface definition A class that implements the ActionListener interface must implement the actionPerformed method.

COMP 150: Introduction to Object-Oriented Programming 25 Lecturer: Dr. AJ Bieszczad Java Tip : Code a GUI's Look and Actions Separately For a complicated GUI, breaking up the work into two parts can help simplify the problem: l Code the appearance: »Use a "do nothing" actionPerformed method while getting the appearance right. »Don't have to worry about possible mistakes in action code. l Code the actions: »When appearance is right, add code for actions to actionPerformed. »Since appearance code has been tested there is less chance of mistakes in appearance code causing problems. A temporary "do nothing" version of a method is called a stub. Using stubs is a good programming technique in many situations.

COMP 150: Introduction to Object-Oriented Programming 26 Lecturer: Dr. AJ Bieszczad The Model-View-Controller Pattern Coding look and action separately is an example of using the general Model-View-Controller pattern. l Model: performs the heart of the application l View: output part of the application; displays Model's state l Controller: input part; relays user commands to Model l The Model-View-Controller pattern is a good way to break up a difficult problem into more manageable pieces. l It also helps make an application more modular. l In a Swing GUI, the View and Controller might be separate classes combined into one larger class.

COMP 150: Introduction to Object-Oriented Programming 27 Lecturer: Dr. AJ Bieszczad Java Tip : Use the Method setActionCommand e.getActionCommand returns action command »by default, action command is string written on button »can specify a different string for action command by using setActionCommand method l Example: JButton stopButton = new JButton("Red"); stopButton.setActionCommand("Stop"); e.getActionCommand will return "Stop" l Allows you to have two different buttons with the same string displayed. l Also allows you to change what buttons say without changing the action command, and vice versa.

COMP 150: Introduction to Object-Oriented Programming 28 Lecturer: Dr. AJ Bieszczad Container Classes A container class can have components added to it. Every Swing container class has an add method. Some commonly used container classes are: l JPanel l Container Content pane of a JFrame The following slides have information about each of these types of containers.

COMP 150: Introduction to Object-Oriented Programming 29 Lecturer: Dr. AJ Bieszczad RedGreen JPanel l Used for hierarchical organization of GUIs: »A panel can contain other components »A panel can be added to another container JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout()); buttonPanel.add(stopButton); buttonPanel.add(goButton); contentPane.add(buttonPanel, BorderLayout.SOUTH);

COMP 150: Introduction to Object-Oriented Programming 30 Lecturer: Dr. AJ Bieszczad The Container Class Any descendant of the Container class can have components added to it. l Need to import the AWT library when using Container because it is not part of the Swing library: import java.awt.*; JComponent is derived from the Container class l Components in the container are arranged by the container’s layout manager

COMP 150: Introduction to Object-Oriented Programming 31 Lecturer: Dr. AJ Bieszczad Content Pane of a JFrame Components are added to the content pane of a JFrame rather than directly to the JFrame The method getContentPane returns a reference to the content pane, which is treated as type Container For containers other than JFrame used in this book, getContentPane is not used Container contentPane = getContentPane(); JLabel label = new JLabel(“blue”); contentPane.add(label);

COMP 150: Introduction to Object-Oriented Programming 32 Lecturer: Dr. AJ Bieszczad Component Object Container Window Frame JFrameJComponent JPanel JLabelJMenuBar AbstractButton JButton JMenu JMenuItem JTextFieldJTextArea JTextComponent Hierarchy of Swing Classes AWT Swing Class Abstract Class Layout manager classes are in the AWT.

COMP 150: Introduction to Object-Oriented Programming 33 Lecturer: Dr. AJ Bieszczad Text I/O for GUIs Text fields and text areas »getText method retrieves text in component »setText changes text in component If memo1 is a String and theText is either a JTextField or a JTextArea, then you could write: JTextFieldJTextArea JTextComponent memo1 = theText.getText(); theText.setText(“Hi Mom”);

COMP 150: Introduction to Object-Oriented Programming 34 Lecturer: Dr. AJ Bieszczad JTextField and JTextArea Both inherit from JTextComponent Both have setText and getText methods l Both can have initializing text as parameter to constructor JTextField can only have one line of text JTextArea can have many lines of text JTextArea can have scroll bars JTextField someText = new JTextField(40); JTextArea someMoreText = new JTextArea(10, 40); Big enough to hold 40 m characters Big enough to hold 10 lines where each line can hold 40 m characters

COMP 150: Introduction to Object-Oriented Programming 35 Lecturer: Dr. AJ Bieszczad Read-Only Text Components Specify that a JTextField or JTextArea cannot be changed by the user. »use method setEditable with argument false theText.setEditable(false); »Only the GUI program can change the text in the component. l Use the argument true to allow the user to edit. »theText.setEditable(true); If setEditable is not called at all, the user can change the text.

COMP 150: Introduction to Object-Oriented Programming 36 Lecturer: Dr. AJ Bieszczad Inputting and Outputting Numbers To get an int from a TextArea or TextField : Get a string using getText Trim extra white space using trim l Convert the String to an int using parseInt int n = Integer.parseInt(field.getText().trim());

COMP 150: Introduction to Object-Oriented Programming 37 Lecturer: Dr. AJ Bieszczad Inputting and Outputting Numbers To get an int from a TextArea or TextField : Get a String using getText Trim extra white space using trim Convert the String to an int using parseInt int n = Integer.parseInt(field.getText().trim()); To put an int into a TextArea or TextField : Convert the int to a String using toString Put the String in the text component using setText field.setText(Integer.toString(total));

COMP 150: Introduction to Object-Oriented Programming 38 Lecturer: Dr. AJ Bieszczad Catching a NumberFormatException parseDouble and similar methods will throw the NumberFormatException if the string is not the proper format for the numeric type l Your program should catch the exception so that it can do something "graceful". »display an error message rather than crashing Methods that throw the NumberFormatException do not have to have a throws clause. Double.parseDouble(stringObject.trim())

COMP 150: Introduction to Object-Oriented Programming 39 Lecturer: Dr. AJ Bieszczad Summary l GUIs (Graphical User Interfaces) are programmed using event- driven programming. The class JFrame is used to create a windowing GUI. A button is an object of class JButton. The add method of a container can be used to add components to the container. l Comonents are added to the content pane of a JFrame rather than directly to the JFrame. l A panel is a container object that is used to group components inside of a larger container. l Text fields and text areas are used for text input and output in a GUI constructed with Swing.