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.

Slides:



Advertisements
Similar presentations
Java GUI building with the AWT. AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
Advertisements

Unit 3 Graphical User Interface (GUI) Dr. Magdi AMER.
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.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Java GUI Libraries Swing Programming. Swing Components Swing is a collection of libraries that contains primitive widgets or controls used for designing.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
Gui Interfaces a la Swing Up to speed with Swing by Steven Gutz is a good source It don’t mean a thing if it ain’t got that swing Duke Ellington.
Events ● Anything that happens in a GUI is an event. For example: – User clicks a button, presses return when typing text, or chooses a menu item ( ActionEvent.
Swing CS-328 Dick Steflik John Margulies. Swing vs AWT AWT is Java’s original set of classes for building GUIs Uses peer components of the OS; heavyweight.
IEEM 110 Computing in Industrial Applications Basic User Interface in Java.
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.
Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University.
Unit 11 Object-oriented programming: Graphical user interface Jin Sa.
Java Programming Chapter 10 Graphical User Interfaces.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.
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.
GUI programming Graphical user interface-based programming.
CS Lecture 01 Frames and Components and events Lynda Thomas
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.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
CompSci 100E 35.1 Graphical User Interfaces: GUIs  Components  Flat Layouts  Hierarchical Layouts  Designing a GUI  Coding a GUI.
Layout Managers Arranges and lays out the GUI components on a container.
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.
Java Programming Applets. Topics Write an HTML document to host an applet Understand simple applets Use Labels with simple AWT applets Write a simple.
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.
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.
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.
1 GUI programming Graphical user interface-based programming Chapter G1 (pages )
Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 14 : Swing II King Fahd University of Petroleum & Minerals College of Computer Science.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
Ajmer Singh PGT(IP) JAVA IDE Programming - I. Ajmer Singh PGT(IP) GUI (Graphical User Interface) It is an interface that uses a graphic entities along.
Creating a GUI Class An example of class design using inheritance and interfaces.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
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.
Lesson 28: More on the GUI button, frame and actions.
Graphical User Interface (GUI)
Applets. 9/04/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L12: Applets Slide 2 Applets Usually.
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.
GUIs & Event-Driven Programming Chapter 11 Review.
Java Visual Applications CSIS 3701: Advanced Object Oriented Programming.
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
Graphical User Interfaces
A First Look at GUI Applications
Graphical User Interface (pronounced "gooey")
Ellen Walker Hiram College
PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.
Window Interfaces Using Swing Objects Chapter 12
Window Interfaces Using Swing Objects Chapter 12
CiS 260: App Dev I Chapter 6: GUI and OOD.
Graphical User Interface
Presentation transcript:

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

GUI’s and theory.

What is a GUI? n GUI- Graphical User Interface. n Pronounced “Gooey.” n Before 1983, everything was command line interfaces and text menus. n Now have a pointing device, and clickable/moveable objects on the screen.

What our GUI’s have n Windows, menus, and buttons n Uses the Event Driven programming model. A fairly large shift from command line programming(what we have been doing so far).

Event Driven programming n The program sets up the GUI and waits to see what the user does. n Any user action fires an event. n This event is caught and handled by the appropriate listener (event handler).

Event model example. n Imagine the work of a worker who only does what their boss tells them to. n The worker just sits around until the boss comes up and tells them to “Write a report A” (an event is fired) The worker creates the report and is finished(the event is handled). The worker then begins waiting for the next request(continues listening).

Paradigm shift n You don’t determine the order of how the program is executed. The order of the events(which are fired when the user does something in a particular order) determines the order.

An example. n In our previous grocery program, we asked the user first how many oranges they want, then eggs, then apples, watermelons, and bagels. n In a graphical version of a shopping cart, the user can choose these items in any order, or not choose an item at all.

GUI’s, Java, and Swing

Swing-How Java does GUI’s n Ever since Java 1.2 (Java 2), the Graphical User Interfaces for Java have been created using Swing. Before Java 1.2, awt was used (it is still included and still gives us functionality we need sometimes). n Swing is faster and has more options.

Beginning tips for GUI programming. n Save your work often! If your GUI crashes in a way such that your computer becomes unresponsive you may need to restart your computer and lose unsaved work. n Copy someone else’s base work and modify it (This does not mean to cheat).

A (good) first window class import javax.swing.*; public class FirstWindow extends JFrame { public static final int WIDTH=300; public static final int HEIGHT=200; public FirstWindow() { setSize(WIDTH,HEIGHT); JLabel myLabel = new JLabel(“Howdy.”); getContentPane().add(myLabel); WindowDestroyer listener = new WindowDestroyer(); addWindowListener(listener); } Sets the size of the frame Adds the text “Howdy” to the frame. Makes the window close when you click on the X (event driven listener) Always extend from JFrame

Using the first window class import javax.swing.*; public class FirstWindowDemo { public static void main(String [] args) { FirstWindow window1 = new FirstWindow(); window1.setVisible(true); FirstWindow window2 = new FirstWindow(); window2.setVisible(true); } Makes one of our windows(frames) Allows us to see the frame that has been made.

Import statements n Usually want to import the following three libraries: –javax.swing.*; –java.awt.*; –java.awt.event.*;

JFrame n Used to create a window that we can put stuff into like buttons, text labels, text boxes, drop-down lists, menus, etc. For every method in the constructor that didn’t have an object to the left, the code was using this implicitly, so those are methods of JFrame.

SetSize(int width, int height) n Sets the size of the window in pixels. Makes it width x height. The larger the number, the bigger it is on the screen. Be careful that you don’t set it to something larger than the resolution on your screen.

JLabel n new Jlabel(String) creates a new JLabel and sets the text of the label to the string passed in. n Once you have created it, you need to make sure that you add it to a container for it to be seen.

getContentPane() n Returns a Container object that represents the area that you can put things into in a JFrame. n This is where you add things that you want to show up on the JFrame. n Don’t add things directly to the JFrame, it won’t work. Always add to the content pane.

Window listeners and destroyers. n Always need to create a window destroyer and add it to the JFrame. Else you won’t be able to close the window. n Use addWindowListener(WindowDestroyer object) to add the listener to the window(listens for the close-window event, basically).

WindowDestroyer code public class WindowDestroyer extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } Just copy this code directly. Don’t worry about trying to ever create it from scratch. It is provided on the Savitch CD.

To see your creation. n Create an object of that GUI type FirstWindow w = new FirstWindow(); n Must set it to be visible w.setVisible(true);

Other methods of JFrame n setBackground(Color c); n setForeground(Color c); n Where c is a color like: Color.black Color.darkGray Color.gray Color.white Color.red Color.green Color.blue

Extra Colors: n We can create any color that we want in the standard RGB color space with each component having values (or 0.0 – 1.0). int red=105, green=45, blue=205; Color aColor = new Color(red, green, blue); setBackground(aColor); // or like on the previous slide setForeground(Color.black);

New Layouts. n When we add things to containers, Java tries to figure out what it thinks is the best possible layout for the items. n We can override Java’s default way of placing things on the screen by changing our layout manager.

Default Layout Manager- BorderLayout. n The default layout manager that Java uses is BorderLayout. n See page 785 to see what the BorderLayout manager tries to do. n The BorderLayout manager will try to fill up the whole section with the object that you add(buttons look huge).

Adding content to specific positions in BorderLayout. n When you give your add command, put in a second argument to say where you want it to go(else it goes in BorderLayout.CENTER). Container contentPane = getContentPane(); contentPane.add(aLabel, BorderLayout.NORTH); contentPane.add(bLabel, BorderLayout.EAST); contentPane.add(cLabel, “South”); contentPane.add(dLabel);//adds to center. contentPane.add(eLabel, “Center”);

Setting your layout manager n Use the setLayout method of the container to set your manager Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); or contentPane.setLayout(new FlowLayout()); or contentPane.setLayout(new GridLayout(4,3));

FlowLayout() n Simplest manager. n Elements are added one after the other from left to right, and they are evenly spaced. n Laid out in the order you add them to the container. contentPane.add(aLabel); //no second argument. //nothing else to //specify.

GridLayout() n Constructed differently. n new GridLayout(int rows, int cols) creates a evenly spaced grid of the specified number of rows and columns. n Adds content to a single cell left to right, top to bottom, one cell at a time. n Can’t skip cells contentPane.add(aLabel); //no second argument.

Many more layout managers. n You are not limited to only these three layout managers. There are many more and you can create your own. Some other examples are: –GridBagLayout –CardLayout –BoxLayout. n See the documentation for more.

Basic Swing Review n What class do we use to create a window in Swing? n What class do we use to create some visible text in Swing? n What classes do we use to manage how content is added to a window in Swing?

Basic Swing Review n Can you add content directly to a JFrame? n Where should you add content to add something to a window? n How do you make your window visible? n How do you set your background color in a window?

Basic Swing Review n What is the default layout manager for Swing? n What are the names of the regions in the default layout manager for swing? n How would you add a label called “helloLabel” to the top part of the window?

Buttons

Interactive windows n Now know how to create windows and output information(through labels). n Now need to know how to take in information. n The most basic way of taking in information with GUI’s is with a button. n Buttons are how we signify selections, that we are done, etc.

JButton n We can use JButtons to create your basic push button. n We need to be able to tell when a user presses a button, so we need add a listener to the button. n We also need to make sure that we add these buttons to some container so that we can see them.

JButton Example public class ButtonDemo extends JFrame implements ActionListener { public ButtonDemo() { … Container contentPane = getContentPane(); Jbutton aButton = new JButton(“Howdy”); Create button with label Howdy on it. aButton.addActionListener(this); There will be a method actionPerformed in this class contentPane.add(aButton, “South”); Add the button to the content pane at the bottom. … }... }

Dealing with the button click public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals(“Howdy”)) { if the Howdy button getContentPane.setBackground(Color.black); do something }

ActionListeners n To allow a class to listen to button events need to add the following to the class declaration: implements ActionListener ActionListener is an interface. n This tells the computer that you will define a method in the class called actionPerformed that returns nothing and accepts an ActionEvent. n In actionPerformed, you will say how you deal with the events.

Creating the button. new JButton(String) creates a button that has the string as it’s label.

Registering the listener. n Once you create the button, you need to say just who will be listening to your button. We do this by registering our listener. aButton.addActionListener(this); //usually do this bButton.addActionListener(anActionListener); //if your listener is defined //in another class, use this way //after creating anActionListener.

Putting the button somewhere. n Once we have created the button and registered it, we need to put it somewhere. Use the add method for some container. Container contentPane = getContentPane(); contentPane.add(aButton, “West”); contentPane.add(bButton);

Catching the event. n If your class is implementing ActionListener, you need to define an actionPerformed method public void actionPerformed(ActionEvent e) { //do something. }

ActionEvents n When you get an ActionEvent object, you can check the actionCommand of the object to see where it came from e.getActionCommand() //returns a string The ActionCommand is usually the text of the button, unless someone has called setActionCommand(String) on the button object.

Shortcut keys n To set a shortcut key for a button use setMnemonic(char). n To do it for a JTextField or other JLabeled component, you can first use setLabelFor(Component) and then use setDisplayedMnemonic(char).

Button Review n What class do we use to make buttons? n If we want to catch the button push events what interface do we need to implement? n How do we register the listener of our buttons? n How do we tell what button an event came from?

Containers

Container classes n Containers are classes that can hold objects like buttons, text fields, labels, etc. n The content pane on a JFrame is one type of container. n We can have more than one container in a window. In fact, we can even put containers inside of containers.

JPanel, a new type of Container n A commonly used Container is the JPanel. n This allows us to group things together and create subsections of a frame. n We can use a different kind of layout manager for each different container that we have.

Using JPanels n First use new JPanels to create a panel. n Once you have created the panel, you can then add things directly to the panel(no need to use content panes with JPanels). n When you are done adding stuff to the panel, add the panel to the JFrame.

A note concerning JPanels, JFrames, and Layout Managers. n It is often a good idea to use a BorderLayout on the Frame and other layout managers (like FlowLayout) for your JPanel. n This will cause your panel to take up the whole section of the BorderLayout while keeping your pieces reasonably spaced and sized inside of your panel.

Review for Containers n Name a class of type Container? n Can we add things directly to JPanel? n Can we add things directly to JFrame? n How many Layout Managers can we have in a single container? n Can we have different layout managers for different containers?

Text I/O (for GUIs)

Text I/O n Now we get to learn how to take more input into our GUIs this time by allowing the user to type information into our program. n The text boxes and fields we will be using also allow us to output more information to the user.

JTextField n JTextFields are just a single line input field. n We create them with a constructor that takes a single integer, which specifies the width of input field. n Then add the JTextField to some container. JPanel aPanel = new JPanel(); JTextField text = new JTextField(20); aPanel.add(text);

Getting and setting the text n If we want to see the string that a user typed into a JTextField, we can use the getText() command to retrieve the string. n If we want to set the text, use setText(String). String someStuff = text.getString(); text.setString(“Wake up!”);

JTextArea n A JTextArea is just like a JTextField, except that it can contain multiple lines. n The main difference comes when we construct the JTextArea, we provide a number of lines as well as line width. JTextArea area = new JTextArea(5,20); //creates 5 lines each 20 characters //wide.

Methods of JTextArea. n The exact same as JTextField. getText() and setText(String). n If we want to allow a user to enter multiple lines, we will want to turn on line wrapping. setLineWrap(true).

Other methods of JTextField and JTextArea n We can make any kind of JTextArea or JTextField read-only (uneditable) by setting its editable property. n We can also set the background colors of the text areas by using setBackground(Color).

Reading numbers n Just like File I/O, reading things besides strings is more difficult. n Again we will want to use parsing and tokenizing. n A good idea before parsing numbers is to trim off whitespace. n Again, you will need to be prepared to catch a NumberFormatException.

Reading numbers example String response = aTextField.getText(); //if it is an integer. int someInt = Integer.parseInt(response.trim()); //if it is a double. double someDouble= Double.parseDouble(response.trim());

Review for Text I/O n What is the difference between a JTextArea and a JTextField? n How many arguments do we give when we call the JTextField constructor? What do the arguments do? n How many arguments do we give when we call the JTextArea constructor? What do the arguments do?

Review for Text I/O n How do we get the text that is inside of a JTextArea? n How do we set the text inside of a JTextArea? n How do we allow line wrapping in JTextArea? n How do we make a JTextField read- only?

Review for Text I/O n How do we get a number from a text box? n What kind of exception should we be prepared to catch when getting numbers from text boxes?

Review

n What does GUI stand for? n How is Event Driven programming different than what we have been doing up till now? n What libraries do we usually import for GUI work?

Review n What class do we inherit from to be able to make windows? n Can we add objects directly to this class that makes windows? n How do we get a container to add our objects to the window?

Review n What kind of event listener do we need to add to be able to close our window? n How do we make a window visible? n What does a Layout Manager do? n What are three Layout Managers we have discussed so far? What does each do?

Review n What class do we use to make simple text for merely displaying? n What class do we use to make buttons? n What interface do we have to implement if we want to listen to the actions of the buttons? n How do we tell what button was pushed when an event is triggered?

Review n What are two containers that we have talked about so far? n Why would you want to use a JPanel? n Can you add objects directly to the JPanel?

Review n What are two classes for taking in Text in a GUI? n How do you call the constructor for each class? n How do you get the text that is being displayed in either of these classes?