Graphical User Interfaces (GUIs)

Slides:



Advertisements
Similar presentations
Graphical User Interfaces
Advertisements

Graphical User Interfaces (Part IV)
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.
Corresponds with Chapter 12
Event Driven Programming and GUIs Part 3 CS221 – 4/15/09.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
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.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
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.
Java Programming Chapter 10 Graphical User Interfaces.
Introduction to GUI Java offers a great number of pre-defined classes to support the development of graphical user interfaces –These are broken down into.
OOP (Java): Layout/ OOP Objectives – –describe the basic layout managers for GUIs Semester 2, GUI Layout.
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.
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,
Introduction to GUI in Java 1. Graphical User Interface Java is equipped with many powerful,easy to use GUI component such as input and output dialog.
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
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,
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
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.
GUI Clients 1 Enterprise Applications CE00465-M Clients with Graphical User Interfaces.
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.
CompSci 100E 35.1 Graphical User Interfaces: GUIs  Components  Flat Layouts  Hierarchical Layouts  Designing a GUI  Coding a GUI.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Layout Managers Arranges and lays out the GUI components on a container.
Java Applets: GUI Components, Events, Etc. Ralph Westfall June, 2010.
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.
GUI Programming using NetBeans. RHS – SOC 2 GUI construction We have previously talked about elements in a (simple) GUI –Frames, Panes and Dialogs –Text.
GUI Basics. What is GUI? A graphical user interface (GUI) is a type of user interface item that allows people to interact with programs in more ways than.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
Object-Oriented Software Engineering
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
Computer Science 209 GUIs Model/View/Controller Layouts.
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.
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.
Creating a GUI Class An example of class design using inheritance and interfaces.
Graphical User Interfaces (GUI). PART ONE About GUI’s.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
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,
Graphical User Interface (GUI) Two-Dimensional Graphical Shapes.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
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.
AWT Vs SWING. 2 AWT (Abstract Window Toolkit) Present in all Java implementations Described in most Java textbooks Adequate for many applications Uses.
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.
GUIs and Events Rick Mercer.
Graphical User Interfaces -- GUIs
Christopher Budo, Davis Nygren, spencer franks, Luke miller
“Form Ever Follows Function” Louis Henri Sullivan
Java GUI.
GUIs Model/View/Controller Layouts
Ellen Walker Hiram College
Chapter 13: Advanced GUIs and Graphics
PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.
Timer class and inner classes
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

Graphical User Interfaces (GUIs) Chapter 13 (available on the Web)

Overview What is a GUI? Creating GUIs in Java GUI components & layout managers GUI (sub)classes Event control (getting the GUI to do something) NetBeans’ GUI design tool

What is a GUI? Graphical User Interface Lots less typing for the user a graphical way to use the program windows, icons, menus, pointing (WIMP) Lots less typing for the user Lots less things for them to remember see options by looking This is a GUI File Edit Help _ X File Edit Help Open Save —— Exit Mrph Blah Yuck Eeew Gross Dpbl Xvgl

Getting Started Java program that creates and shows a GUI JFrame object with JLabels & more inside it Program class has a main method compile & run program as usual GUI window will appear we’ll need to do something special to make sure our program ends when it’s supposed to!

Java GUI Java has two different GUI libraries The Swing Tutorial java.awt.* Frame, Label, … javax.swing.* JFrame, JLabel, … we need stuff from both of them The Swing Tutorial look up components in the following site: http://java.sun.com/books/tutorial/uiswing

The GUI Window GUI starts with a window object Nothing happened! give a title for the window JFrame win = new JFrame(“My Win”); Nothing happened! actually an invisible window was created win.setVisible(true); It’s tiny! but you can resize it See GUIStuff.java

The GUI Window JFrame win = new JFrame(“My Win”); win is a variable – will be the window object JFrame is the class we’re creating an instance of (class of windows) title of window (in title bar): “My Win” win.setVisible(true); win is the window object setVisible is the command true is the argument  true = visible

Making it Bigger at the Start Don’t want to have to re-size every window win.setSize(300, 200); 300 pixels wide 200 pixels tall exactly how big that is depends on your screen resolution (number of pixels per inch) NOTE: dimensions are of outer edges 200 300

Our Window So Far Title bar Note: cup of java icon title of window min., max. & close buttons otherwise empty Note: looks like other windows on your computer will look like Mac window on Mac computer

Things to Add to Your Window All in javax.swing: JLabel – text for user to read JTextField – box for user to type in JButton – button for user to push JCheckBox – box for user to check/uncheck JRadioButton – one radio button ButtonGroup – for grouping radio buttons …many more…

Labels Label needs to know its text need to tell the window to repaint itself JLabel lbl1 = new JLabel(“Hello, World!”); win.add(lbl1); win.setVisible(true); Didn’t say where to put the label, so it filled the pane add method can be told where to put the object

Component Placement Default “layout” gives you five places to put components: PAGE_START (NORTH) PAGE_END (SOUTH) LINE_START (WEST) LINE_END (EAST) CENTER Need to import java.awt.*; use like: BorderLayout.NORTH PAGE_START LINE_START CENTER LINE_END PAGE_END

Text Fields Labels don’t do anything For text you can edit, use JTextField JTextField tf = new JTextField(“Initial Text”); win.add(tf, BorderLayout.PAGE_END); win.setVisible(true); small amount of plain text JTextPane for more text

Buttons Buttons can be clicked lets the user select an action to carry out JButton b1 = new JButton(“OK”); win.add(b1); win.setVisible(true); computer put it CENTER, right over the label, because we didn’t say where it went

Window Layout Managers It’s possible to tell the window exactly where you want each piece you add to it how many pixels across, down looks real good if you do it right generally gets messed up if user resizes window Easier and more portable to use manager default manager: BorderLayout others available: we’ll look at two more

Window Layout Managers Window layout managers in java.awt BorderLayout CardLayout FlowLayout GridBagLayout GridLayout Each has its own way of determining what goes where… We’ll look at BorderLayout FlowLayout GridLayout See GUIStuff.java

BorderLayout Five locations to place objects objects in the same location are placed one on top of the other objects are stretched or squashed in order to fill the space allotted empty locations are not used (other objects expand) PAGE_START LINE_START CENTER LINE_END PAGE_END

FlowLayout FlowLayout just puts the objects into the window one after the other if there’s not enough room across, it goes down to the next “line” objects centred on each line objects move around when window gets resized FIRST SECOND THIRD FOURTH FIFTH

GridLayout Creates a small table each object goes in the next cell of the table Need to say how many rows and/or columns new GridLayout(5, 3)  don’t put more than 15 things in the grid! (0, 3) means 3 columns and as many rows as you need 1st 2nd 3rd Fourth Fifth

Choosing a Layout Manager Create a new layout object and tell the content pane to use it (setLayout method) flow layout win.setLayout(new FlowLayout()); border layout win.setLayout(new BorderLayout()); grid layout (2 rows, 3 columns) win.setLayout(new GridLayout(2, 3));

Some Windows

Putting it Together We have created a lot of objects window (JFrame), label (JLabel), text fields (JTextField), buttons (JButton) Want them all to work together but we’ve done it all in a very procedural way should do object oriented way Create a class for this kind of window create window objects as required (use main to test: create an object and show it)

GUI Window Class Create a window class that inherits from the Java window class (javax.swing.JFrame) public class MyWinClass extends JFrame { constructor sets the title using super public MyWinClass(String title) { super(title); … then constructor adds stuff to this window

GUI Window Class The object created will be a window object (in the class JFrame) use this — there is no variable named win here this.add(new JLabel(“Hello!”)); or use super – to get rid of NetBeans’ complaint super.add(new JButton(“OK”)); Don’t make it visible in the constructor let client decide when to make it visible

Enter two numbers to add together: Adder Dialog Mock-Up Adding Numbers Enter two numbers to add together: First number: 10 Second number: 25 Result: 35 Calculate Done

Adder Dialog Grid Mock-Up Adding Numbers Enter two numbers to add… note this empty cell… First number: 10 Second number: 25 Result: 35 Calculate Done

Adder Dialog (version 1) public class AdderDialog1 extends JFrame { public AdderDialog1() { super(“Adding Numbers”); this.setSize(450, 250); // or super.setSize(450, 250); this.setLayout( new GridLayout(0, 2, 10, 5) ); … // add labels/fields/buttons to this window } ? rows, 2 columns 10 pixels between columns 5 pixels between rows

Adder Dialog (version 1) main public class AdderDialog1 extends JFrame { … public static void main(String[] args) { AdderDialog1 ad1 = new AdderDialog1(); ad1.setVisible(true); } Create the window Make it visible

Now Do Something! Our windows do nothing (other than resize) Want actions to go with the buttons read values from text boxes, maybe add results & put back into another box Need event controllers methods that are called when something happens (e.g. button pushed)

Getting the Program to End First we want the program to end when the adder dialog box is closed JFrames have an easy way to do that setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add that line to the constructor, and then closing the adder window ends the application For other events, we need an ActionListener

The ActionListener Interface One method needs to be implemented: public void actionPerformed(ActionEvent ae) {…} this called whenever anything happens in a component of the window not when the minimize/resize/close buttons clicked methods needs to see what event happened… button clicked, text changed, … …and deal with it You don’t call this method! It gets called when it’s needed: “event control”

Implementing ActionListener You could make a separate class… and create an object of that class …but we will use the window class instead we already have an object of that class: this public class MyWindowClass extends JFrame implements ActionListener { … } need to import more classes import java.awt.event.*;

The actionPerformed Method Has one parameter an ActionEvent – an object representing the event that just occurred knows which component the event happened to ae.getSource() check which button it is if (ae.getSource() == done) { … } else if (ae.getSource() == calculate) { … }

Our actionPerformed Method If it’s the Done button: exit the program If it’s the Calculate button get and add the numbers we’ll have a separate method to do that if (ae.getSource() == done) { System.exit(0); } else if (ae.getSource() == calculate) { addTheNumbers(); }

Two More Things… Our buttons need to be instance variables so actionPerformed can talk to/about them private JButton done = new JButton(“Done”); private JButton calculate = new JButton(“Calculate”); We need to say this window is listening it’s the ActionListener for that button done.addActionListener(this); calculate.addActionListener(this);

Listening? User clicks a button Our window has the number fields in it button sends a message to every object listening those objects do what they need to do exit program add up the numbers Our window has the number fields in it it’s the one that can do the adding… …so it should be listening to calculate (and since it’s listening anyway, why not done)

Our Adder Dialog So Far Clicking the close box or Done button closes the window and ends the application Clicking on the Calculate button calls our addTheNumbers method currently a stub! Need to say how to add the numbers need to get the two numbers from the text fields add them up & put result in result field

Getting & Setting Text Fields Getter & setter for JTextFields gets/sets the text in the text field field1.setText(“Hello?”); String f1Text = field1.getText(); use getText to get the numbers the user typed in use setText to show the result Now we just need the text fields… they need to be instance variables, too!

Keeping Track of Your Fields Window needs to remember its fields instance variables private JTextField numField1 = new JTextField(); private JTextField numField2 = new JTextField(); private JTextField resultField = new JTextField(); constructor adds them to the window super.add(numField1); super.add(numField2); super.add(resultField);

addTheNumbers Get the text and parse it as an integer Add them up int n1 = Integer.parseInt(numField1.getText()); getText gets the text from the box parseInt tries to change it to an integer may throw a NumberFormatException Add them up int result = n1 + n2; Drop it back into resultField as text resultField.setText(Integer.toString(result));

addTheNumbers Catch the exception set the result field to an error message public void addTheNumbers() { try { int n1 = Integer.parseInt(numField1.getText()); int n2 = Integer.parseInt(numField2.getText()); int result = n1 + n2; resultField.setText(Integer.toString(result)); } catch (NumberFormatException e) { resultField.setText(“One of those is not a number!”);

Formatting the Text Fields Number fields should align to the right numField1.setHorizontalAlignment(JTextField.RIGHT); Result field shouldn’t be editable resultField.setEditable(false); Make some space around the box edges Insets object gives number of pixels to be blank top, left, bottom, right Insets margin = new Insets(5, 5, 5, 5); numField1.setMargin(margin);

Adding Sub-Panes You can create a JPanel and put objects inside it… using its own layout manager JPanel top = new JPanel(); top.setLayout(new FlowLayout()); top.add(new JLabel(“Enter two numbers to add…”)); …then put the JPanel into the window using the window’s layout manager super.add(top, BorderLayout.NORTH);

Exercise: Adding Sub-Panes BorderLayout for full window NORTH, CENTER, SOUTH FlowLayout for top pane already done! GridLayout for middle 3 rows, 2 columns FlowLayout for bottom Enter two numbers to add… First number: Second number: Result: Calculate Done

NetBeans GUI Designer NetBeans provides a design tool Add a new “JFrame Form…” to project opens in “Design” view (instead of “Source”) shows a “Palette” with containers & controls and more, but collapsed Sometimes NetBeans will switch to “Source” view. Just click on the “Design” button to get back.

Adding Items to the Window Drag and drop watch guidelines for placement wide space medium space align above and beside

Setting Labels Slow double-click label to set its text other items may move relative to new label contents fix them by dragging to line up with other text boxes

Sizing Text Boxes Slow double click text fields to change text inside the box box may resize Select box and drag corner/edge to resize it Similarly for buttons I put it below “Calculate” so I could make them the same width then I moved it to its final location

Resizing Window Drag from bottom-right corner until you get the size you want or double-click border and type in the dimensions you want

Changing Properties Select the items to change (e.g. all the text boxes) Right-click to get properties change as desired

Changing Name NetBeans gives blah names: Should change to better names jTextField1, jTextField2, jButton1, jButton2 Should change to better names variable name property in “Code” properties

Adding Actions Double-click button to add an action switches to “Source” mode… ...in the method that handles click of that button Add code to do what you want

Differences Code generated by NetBeans will look very different from what I told you before code to lay out the fields is very different code to add a listener to button is “anonymous” creates unnamed object that just listens to the button no need for window to listen no need to check which button was pushed!

Exercise Use NetBeans to make another adder form use NetBeans’ layout tool make the buttons work!

Questions?