GUI Tutorial 1. A Bit of Philosophy on what to Teach  There are numerous libraries, frameworks, options  Modern GUIs are often developed using XML (e.g.,

Slides:



Advertisements
Similar presentations
Graphic User Interfaces Layout Managers Event Handling.
Advertisements

Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
GUI Tutorial Day 3. Custom Dialog Create, display, hide, retrieve information.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
CS102--Object Oriented Programming Lecture 19: – The Swing Package (II) Copyright © 2008 Xiaoyan Li.
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.
Chapter 8: Graphical User Interfaces Objectives - by the end of this chapter, you should be able to do the following: –write a simple graphical user interface.
Advanced Java and Android Programming Day 1: Introduction to GUI Programming Intro to GUI Programming1.
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.
Programming With Java ICS201 University Of Ha’il1 Chapter 17 Graphical User Interfaces Swing I.
Combo Box, Check Boxes, and Radio Buttons. Radio Buttons User can click radio buttons, just like other buttons BUT Radio buttons are mutually exclusive.
Using Inheritance to Customize Frames Use inheritance for complex frames to make programs easier to understand Design a subclass of JFrame Store the components.
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,
CSE 219 Computer Science III Graphical User Interface.
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.
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,
Java GUI building with Swing. 2 AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
1 Why layout managers Can we perform layout without them? –Yes. A container’s layout property can be set to null. Absolute positioning: specify size and.
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
Chapters (ArrayList / Generic)
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
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.
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.
CompSci 100E 35.1 Graphical User Interfaces: GUIs  Components  Flat Layouts  Hierarchical Layouts  Designing a GUI  Coding a GUI.
Object Oriented programming Instructor: Dr. Essam H. Houssein.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
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.
University of Limerick1 Software Architecture Java Layout Managers.
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)
Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets.
Computer Science 209 GUIs Model/View/Controller Layouts.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
Creating a GUI Class An example of class design using inheritance and interfaces.
1 Layout Managers Layout managers –Provided for arranging GUI components –Provide basic layout capabilities –Processes layout details –Programmer can concentrate.
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 Tutorial 2. What did we do last time?  Basic flow  instance variables, set up in ctor, close operation, size, visible  JFrame  Event-driven programming.
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)
Event Handler Methods Text field Object Responder JAVA AWT Environment: Messages are sent between JAVA Objects Screen Event Notification Press Button.
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.
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:
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.
A Quick Java Swing Tutorial
GUIs and Events Rick Mercer.
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
Christopher Budo, Davis Nygren, spencer franks, Luke miller
GUIs Model/View/Controller Layouts
A Quick Java Swing Tutorial
Ellen Walker Hiram College
Timer class and inner classes
A Quick Java Swing Tutorial
Advanced Programming in Java
Graphical User Interface
Presentation transcript:

GUI Tutorial 1

A Bit of Philosophy on what to Teach  There are numerous libraries, frameworks, options  Modern GUIs are often developed using XML (e.g., Android, XAML, etc.)  My goals for 306:  Understand event-driven programming in general  Work with one object-oriented GUI library (Swing)  Feel confident you can learn other toolkits as needed  Cover only the basics (e.g., there are many layout managers, but I’ll only cover a couple)

Topics in GUI Tutorial 1  Event-driven programming  Layout managers  Text fields and labels  Responding to buttons  Simple dialogs  confirmation  message  simple input  JPanel  Borders  CheckBox and ComboBox

Event Programming  GUIs are under control of the user, not the program. This type of programming is referred to as event- driven.  Java programs react to a wide variety of user interface events – button pushes, mouse clicks, window manipulation, etc.  Program installs event listeners for events of interest  Need to know the event source – e.g., button, text box, window etc.  All listeners implement the particular interface for that type of event (e.g., button listeners must implement ActionListener)

FirstGUI Covers JFrame, BorderLayout, JTextField, JLabel, JButton, ActionListeners

Basic Strategy – very simple GUI 1. Create a JFrame (or JApplet) as the top-level container. Normally only 1 JFrame per application. 2. Define the components as instance variables (or possibly local variables) 3. In the constructor, allocate space for the components, add them to the JFrame (may call helper methods) 4. Main is usually very short: 1. call the constructor 2. set visible true. No events yet…

Create a JFrame public class FirstGUI extends JFrame{ public static void main(String[] args) { FirstGUI gui = new FirstGUI(); gui.setVisible(true); }  GUI displays… barely!

Use the constructor to configure it public FirstGUI() { // EXIT_ON_CLOSE is static int setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("My First GUI"); setSize(300, 100); }  set functions are defined because FirstGUI is-a JFrame

What’s a layout?  A layout manager determines how components will be arranged (order and size)  Layout managers enable programs to be more portable  The default layout manager for a JFrame is BorderLayout  The default layout manager for a JPanel (covered soon) is FlowLayout  Controlling the layout is not an important topic for this class. Suggested reading: from-A-to-Z-Minimum-Maximum-and-Preferred-Sizes.htm

BorderLayout In a BorderLayout, outer components (N/S/E/W) are sized to their natural size, if possible. Any extra space is given to CENTER. NORTH SOUTH CENTER EAST WEST

Now let’s add components  JTextField – used to accept information, single line  Our JTextField will be an instance variable – because we want to access it from other methods later.  Our JLabel field will be local – only set up and add to GUI, don’t need to access or modify later public class FirstGUI extends JFrame { private JTextField myName; private void createLayout() { JLabel nameLabel = new JLabel("Name"); myName = new JTextField(20); add(nameLabel, BorderLayout.NORTH); add(myName, BorderLayout.CENTER); } call createLayout from ctor only add 1 component/area

Basic Strategy – simple GUI w Events 1. Create a JFrame (or JApplet) as the top-level container. Normally only one JFrame per application. 2. Define the components as instance variables (or possibly local variables) 3. In the constructor or an initialization function, allocate space for the components, add them to the JFrame, do other JFrame set up (set default close operation, set size, etc.) 4. Write an event listener (can be anonymous or inner class) 5. Attach the event listener to the component 6. In main, call the constructor, set visible true. Main is usually very short.

Add a Button  In createLayout, define a button, allocate space, add to JFrame JButton nameButton = new JButton("OK"); add(nameButton, BorderLayout.SOUTH);  It displays… but no action yet Why is it OK for nameButton to be a local variable?

Create a listener  A class that responds to events must implement an interface named ActionListener  Remember that an interface:  Specifies methods that must be defined  Provides method signature (name, parameters)  Interface does not provide a method body – like pure virtual in C++. Method must be defined by implementing class.  By using an interface, Java knows what method to call Event Listener JButton actionPerformed

Note on packages  Just importing java.awt.* does not provide access to java.awt.event.ActionEvent. You can think of it as a directory structure that doesn’t automatically include subdirectories. (that’s not really what happens…)  import java.awt.event.*;

Simple action listener class  There are several syntax options for where the listener is defined.  We’ll define an inner class.  This should be in your source file, between public ClassName and the final }.  For now, put it just above your main method.  You can give the class any name, but it must implement ActionListener and you must have a method definition for actionPerformed. private class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Button pressed"); } COMMON ERRORS: misspelling actionPerformed, not making it public, not having ActionEvent as a parameter. Run it now… still nothing happens!

Add the listener to a button  Press the button…. nothing happens yet! Need to “attach” the listener to the buton.  Add the action listener to it (inside createLayout() ). nameButton.addActionListener(new ButtonListener());  But system.out.println is not very exciting

JOptionPane JOptionPane provides 3 quick options for dialogs:  Simple input  Simple message  Confirmation

Modifying the action listener  We can access the value of the JTextField because it’s an instance variable and our listener is an inner class  Put these lines in actionPerformed : String message = "Hello " + myName.getText(); JOptionPane.showMessageDialog(null, message);

More JOptionPane options String numStr = JOptionPane.showInputDialog("Enter your age"); int num = Integer.parseInt(numStr); int yearsLeft = num; JOptionPane.showMessageDialog(null, "You have " + yearsLeft + " years left"); NOTE: This example is just to show all JOptionPane options – for most applications you would probably add an age field to the JFrame.

Final JOptionPane example  showConfirmDialog returns an enumerated type int ready = JOptionPane.showConfirmDialog(null, "Are you ready to continue?"); if (ready == JOptionPane.YES_OPTION) JOptionPane.showMessageDialog(null, "Here we go!"); else JOptionPane.showMessageDialog(null, "OK, we'll wait");

JPanel  JPanel is a container to hold other components  A JPanel may be in its own class, or may be a variable inside another class  Which is best? Depends….

FlowLayout // default layout is flow JPanel panel = new JPanel(); panel.add(component);  Items displayed in order added  Fills horizontally, move to next line when not enough space for next field. FIELD-1 FIELD-3 FLD-4 FIELD-2 FLD-5 FLD-6

Using a JPanel with FirstGUI private void createLayout() { JLabel nameLabel = new JLabel("Name"); myName = new JTextField(20); // Create a JPanel JPanel panel = new JPanel(); // Add elements to the panel panel.add(nameLabel); panel.add(myName); // Add the panel to the layout add(panel, BorderLayout.CENTER); JButton nameButton = new JButton("OK"); add(nameButton, BorderLayout.SOUTH); nameButton.addActionListener( new ButtonListener()); }

CarpoolGUI JPanel, FlowLayout, GridLayout, JComboBox, CheckBox, RadioButton, Font Quick Intro: Panel Communication

CarpoolGUI  Used to sign up for carpooling  Will show lots of GUI components  Creates a more complex layout using panels  We’ll start today, finish next time NOTE: Clue layout will probably not need so many separate JPanel classes

Panel Communication Main panel Control Panel This is just a special case of message passing – common OO technique

GridLayout JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(4, 3)); buttonPanel.add(button7); buttonPanel.add(button8); … CE can set 1 of these to 0, will expand as needed

Nesting Panels JPanel keypadPanel = new JPanel(); keypadPanel.setLayout(new BorderLayout()); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(4, 3)); buttonPanel.add(button7); buttonPanel.add(button8); … keypadPanel.add(buttonPanel, BorderLayout.CENTER); JTextField display = new JTextField(); keypadPanel.add(display, BorderLayout.NORTH); CE

Get started: normal items in JFrame public class CarpoolGUI extends JFrame { public CarpoolGUI() { setSize(new Dimension(400, 250)); setTitle("Let's carpool"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { CarpoolGUI gui = new CarpoolGUI(); gui.setVisible(true); }

Create panel with combo boxes public class ToFromPanel extends JPanel { // JComboBox requires Java 1.7 or higher private JComboBox toCity, fromCity; public ToFromPanel() { toCity = createCityCombo(); fromCity = createCityCombo(); } private JComboBox createCityCombo() { JComboBox combo = new JComboBox (); combo.addItem("Golden"); combo.addItem("Boulder"); combo.addItem("Denver"); return combo; } Don’t Repeat Yourself (DRY) We create a createCityCombo method to avoid repeating code.

Continue combo panel  Add to ToFromPanel constructor: JLabel fromLabel = new JLabel("From"); JLabel toLabel = new JLabel("To"); setLayout(new GridLayout(0, 2)); add(fromLabel); add(toLabel); add(fromCity); add(toCity);  Add to CarpoolGUI constructor: ToFromPanel tfPanel = new ToFromPanel(); add(tfPanel, BorderLayout.CENTER);

Create panel with radio buttons public class PreferencePanel extends JPanel { private JRadioButton smokeButton, noSmokeButton; public PreferencePanel() { // Create the buttons smokeButton = new JRadioButton("Smokes"); noSmokeButton = new JRadioButton("No smoke"); // Set no smoke as the default noSmokeButton.setSelected(true); // Add the buttons to the panel add(smokeButton); add(noSmokeButton); }

Add the panel to the JFrame  In the JFrame constructor: PreferencePanel pPanel = new PreferencePanel(); add(pPanel, BorderLayout.EAST);  But it’s possible to click both!  Need a RadioGroup

Update Preference panel ButtonGroup group = new ButtonGroup(); group.add(smokeButton); group.add(noSmokeButton); setBorder(new TitledBorder (new EtchedBorder(), "Preferences"));  OK, but let’s get items in a column

We’ll use GridLayout setLayout(new GridLayout(2, 1));

Add a border  Add to the ToFromPanel constructor setBorder(new TitledBorder (new EtchedBorder(), "Location"));

CheckBox and Font public class WillDrivePanel extends JPanel { private JTextField name; private JCheckBox willDriveCB; public WillDrivePanel() { JLabel label = new JLabel("Name"); name = new JTextField(20); name.setFont(new Font("SansSerif", Font.BOLD, 12)); add(label); add(name); } add to JFrame, of course (NORTH)

Add to JFrame WillDrivePanel wdPanel = new WillDrivePanel(); add(wdPanel, BorderLayout.NORTH);

Now the check box willDriveCB = new JCheckBox("Will drive"); add(willDriveCB);