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.

Slides:



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

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
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
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.
Chapter 121 Window Interfaces Using Swing Chapter 12.
Graphical User Interfaces
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.
Lesson 35: Review of the Java GUI. The JFrame, Container and JButton.
Java Programming Chapter 10 Graphical User Interfaces.
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.
Java Programming: From Problem Analysis to Program Design, Second Edition1  Learn about basic GUI components.  Explore how the GUI components JFrame,
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.
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.
Java GUI CSCE 190 – Java Instructor: Joel Gompert Mon, July 26, 2004.
GUI programming Graphical user interface-based programming.
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.
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
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
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.
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.
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 ( 李德成 )
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 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.
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
A simple swing example GETTING STARTED WITH WIND CHILL.
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.
Basics of GUI Programming Chapter 11 and Chapter 22.
Graphical User Interfaces A Graphical User Interface (GUI) in Java is created with at least three kinds of objects: –components, events, and listeners.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
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,
Event-Driven Programming F Procedural programming is executed in procedural order. F In event-driven programming, code is executed upon activation of events.
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.
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
©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.
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 -- GUIs
A First Look at GUI Applications
“Form Ever Follows Function” Louis Henri Sullivan
Graphical User Interface (pronounced "gooey")
Ellen Walker Hiram College
Chapter 13: Advanced GUIs and Graphics
Timer class and inner classes
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

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 roughly 3 categories containers – JFrames, JPanels, JApplets GUI objects – buttons, input and output boxes, etc event listeners – when a GUI object is interacted with, it often generates an Event, a listener is code that listens for the Event and handles it –Java implemented a primitive set of GUI classes in the java.awt package, but improved these for later releases and these are all in the javax.swing package we will primarily use the components in swing, they are far better, but one or two of the items we use are still in java.awt most class names in the swing library add a “J” to the previous versions’ names in awt, such as Button becoming JButton, Panel becoming JPanel

Types of GUI Components JFrame – a container, you place items inside the Frame JApplet – a container used to run code in web browsers JPanel – an intermediate container which cannot be viewed by itself, but can be placed inside a frame or applet, and used for graphics LayoutManager – an object that configures the components in a JPanel –types: FlowLayout, GridLayout and BorderLayout JButton – click to generate an Event to be handled JLabel – to output Strings JTextField – to input Strings (or other data) JTextArea – to input or output multi-lined text JCheckBox – boxes that can be clicked on and off JRadioButton – collection of buttons, only one can be selected at a time JComboBox – type of menu, click on the box and a menu or list appears JMenu – same as combo box but appears in the title bar JSlider – to offer a range of values JSpinner – click in the up or down arrow to increase/decrease the value

Creating a GUI import javax.swing.*;// needed for the GUI items import java.awt.*;// needed for LayoutManager public class Template extends JFrame { private static final int X_SIZE = 520, Y_SIZE = 520; public static void main(String[] args) { JFrame frame = new JFrame("GUI Example1"); frame.setSize(X_SIZE, Y_SIZE); GuiPanel panel = new GuiPanel(); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private static class GuiPanel extends JPanel { public GuiPanel() { } Here’s where most of our code will go

Example Here, we see the code to create some JButtons and a JLabel, and position them within the JFrame using JPanels JButton button1 = new JButton("Button 1"); JButton button2 = new JButton("Button 2"); JButton button3 = new JButton("Button 3"); JPanel panel1 = new JPanel( ); panel1.add(button1); panel1.add(button2); panel1.add(button3); JLabel output = new JLabel(“ ”); JPanel panel2 = new JPanel(new GridLayout(2, 1)); panel2.add(panel1); panel2.add(output); add(panel2); Two panels, one consists of 3 buttons, one consists of a panel in row 1 and the JLabel in row 2 – the JLabel will get be used later in these notes What happens when you click on one of the JButtons? Nothing. Why not?

Layouts There are 3 main layouts that we will use –FlowLayout – JPanels will default to this form if we don’t specify otherwise items are inserted in the same row until there is no room, then the next items go into the next row, etc (the previous slide used this default mode) –GridLayout – allows you to specify how many items per row by indicating a row and column number in general, you specify GridLayout(x, y) for x rows and y columns items are added to the first row until there is 1 item in each column, then it goes onto the next row, so it is similar to FlowLayout –BorderLayout – gives you five regions, NORTH, SOUTH, EAST, WEST and CENTER when adding an item to the container, specify which of the five regions you want it placed into the layout manager will space items out evenly so that each item takes up the same amount of space – this can lead to lopsided looking GUIs, so you will want to create JPanels and insert them into other JPanels – see the example on the next slide

Another Example The first set of code is sloppy, the second set makes the GUI look better JButton button1 = new JButton("Button 1 has a long title doesn't it?"); JButton button2 = new JButton("2"); JButton button3 = new JButton("3"); JButton button4 = new JButton("4"); JPanel panel = new JPanel(new GridLayout(2, 2)); panel.add(button1); panel.add(button2); panel.add(button3); panel.add(button4); add(panel); … set up the 4 JButtons as before JPanel panel1 = new JPanel( ); JPanel panel2 = new JPanel( ); JPanel panel3 = new JPanel(new GridLayout(2, 1)); panel1.add(button1); panel2.add(button2); panel2.add(button3); panel2.add(button4); panel3.add(panel1); panel3.add(panel2); add(panel3);

Reacting to the JButtons To this point, we have only set up the GUI, if you click on any JButton, nothing happens –why not? Clicking on a JButton generates an ActionEvent –but without an ActionListener, your program ignores that event We must then implement an ActionListener, how? –add import java.awt.event.*; (for the Event classes) –add “implements ActionListener” to the class header this says that a listener will be made available in this class –we must describe who will handle the event so add button1.addActionListener(this); and similarly for button2 and any other JButton) – this means this class –to implement the ActionListener include a method called actionPerformed in your class this method is called every time one of the JButtons is clicked, so whatever you want to have happen will be implemented in this method

Example Continued We enhance our previous example of 3 buttons by having the GUI output into the JLabel a message indicating which button was clicked public class Template implements ActionListener { private static JLabel output; public Template( ) { JButton button1 = new JButton("Button 1"); JButton button2 = new JButton("Button 2"); JButton button3 = new JButton("Button 3"); JPanel panel1 = new JPanel( ); button1.addActionListener(this); button2.addActionListener(this); button3.addActionListener(this); panel1.add(button1); panel1.add(button2); panel1.add(button3); output = new JLabel(" "); JPanel panel2 = new JPanel(new GridLayout(2, 1)); panel2.add(panel1); panel2.add(output); add(panel2); } All three buttons will have the same handler, written in this class public void actionPerformed(ActionEvent e) { String message = "You clicked on " + e.getActionCommand( ); output.setText(message); } } // ends Template inner class NOTE: main method omitted for space purposes

Some Comments We moved the declaration of the JLabel output to be placed before our constructor function –this allows the variable output to be known throughout the class, so it can be referenced in both the constructor (to add it to the JFrame) and in actionPerformed why didn’t we do this with any other GUI components? –actionPerformed is passed an event, the event contains the name of the JButton pressed, we use this information in our output, we get this String using getActionCommand( ) –we can change a label’s String by using setText(…) The word this is used in Java to say that the needed code will be implemented here, in this class –there are many alternative ways to specify where an event listener will be placed, we will stick with this approach because its easiest

JTextField for Input The JLabel allows you to output text –for instance, we might create a calculator program where the JButtons are the various digits and mathematical operators and the JLabel will display the total so far The JTextField allows the user to enter text –and then we can input whatever was typed in by using the getText( ) method –like JOptionPane, any text input is a String, so we might need to use Integer.parseInt to convert it to an int value The JTextField can also have a String placed into it to be displayed at times when the user is not entering information into it, but this is optional –use setText(text goes here); In the next example, we will use the JTextField for input

Temperature Conversion Example private static JTextField input; private static JLabel output; public Temperature( ) { JLabel label1 = new JLabel("Enter temperature: "); input = new JTextField("", 3); JButton ctof = new JButton("Celcius to Fahrenheit"); JButton ftoc = new JButton("Fahrenheit to Celcius"); output = new JLabel(" "); JPanel panel1 = new JPanel(); panel1.add(label1); panel1.add(input); JPanel panel2 = new JPanel(); panel2.add(output); JPanel panel3 = new JPanel(); panel3.add(ctof); panel3.add(ftoc); JPanel total = new JPanel(new BorderLayout()); total.add(panel1, BorderLayout.NORTH); total.add(panel2, BorderLayout.CENTER); total.add(panel3, BorderLayout.SOUTH); add(total); ctof.addActionListener(this); ftoc.addActionListener(this); } main method omitted, but is much like the previous main, but with the word Temperature used in place of Template Used for input

Rest of the Code public void actionPerformed(ActionEvent e) { String message = ""; double newTemp; int oldTemp = Integer.parseInt(input.getText()); input.setText("");// reset input field if(e.getActionCommand().equals("Celcius to Fahrenheit")) { newTemp = 9.0/5*oldTemp + 32; message = "" + oldTemp + "C becomes " + newTemp + "F"; } else { newTemp=5.0/9*(oldTemp-32); message = "" + oldTemp + "F becomes " + newTemp + "C"; } output.setText(message); } Unlike our previous example with 1 button, we now have 2. Since this actionPerformed method is called whether ctof or ftoc is clicked, we need to know which one was clicked to know which set of code to run

Developing a GUI Here, we go step-by-step in developing a GUI –Let’s create a “change counter” there will be a button for each type of change (penny, nickel, dime, quarter, half dollar, silver dollar) there will be a clear button to remove the current amount there will be a label to output the computed amount so far when the user clicks on a button, it will take that amount and add it to the total and update the total, or if the clear button is clicked on, it will change the total to 0 –We first set up the GUI itself 7 buttons and a label, lets organize them so that we have 2 rows of the 3 “change” buttons, and 1 row of the clear button and label we will use 3 JPanels –one will organize the 6 change buttons in a 2x3 grid –one will organize the clear button and label in one row –one will contain the other two panels

Code – Part 1 import javax.swing.*;// needed for the Jgui items import java.awt.*;// needed for LayoutManager import java.awt.event.*;// needed for ActionListener public class ChangeCounter extends JFrame implements ActionListener { public static void main(String[] args) { JFrame frame = new JFrame("Change Counting Program"); ChangePanel cp = new ChangePanel( ); frame.getContentPane( ).add(cp);frame.pack( ); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private static class ChangePanel extends JPanel implements ActionListener { private static JLabel output;// the output label private static double amount;// the current amount entered

Code – Part 2 public ChangeCounter( ) { JButton penny = new JButton("$.01"); // … same for the other 5 “change” buttons JButton clear = new JButton("Clear"); penny.addActionListener(this); // … same for the other 5 “change” buttons clear.addActionListener(this); output = new JLabel("$ 0.00"); JPanel panel1 = new JPanel(new GridLayout(2, 3)); panel1.add(penny); // … same for the other 5 “change” buttons JPanel panel2 = new JPanel( ); // uses FlowLayout panel2.add(clear); panel2.add(output); JPanel panel3 = new JPanel(new BorderLayout( )); panel3.add(panel1, BorderLayout.NORTH); panel3.add(panel2, BorderLayout.SOUTH); add(panel3); }

Code: Part 3 public void actionPerformed(ActionEvent e) { String button = e.getActionCommand(); if(button.equals("Clear")) amount = 0.00; else if(button.equals("$.01")) amount += 0.01; else if(button.equals("$.05")) amount += 0.05; else if(button.equals("$.10")) amount += 0.10; else if(button.equals("$.25")) amount += 0.25; else if(button.equals("$.50")) amount += 0.50; else if(button.equals("$1.00")) amount += 1; output.setText("$ " + amount); } Because this method and the constructor both reference output and amount, we must declare them as class variables The DecimalFormat class allows us to specify how double values will be output, here we use a dollar and cents format

More on JLabels and JButtons Aside from Strings, you can insert pictures into JLabels and JButtons –JLabel label1 = new JLabel(image); –JButton button1 = new JButton(image); image must be an ImageIcon which you can create by specifying the image’s location on disk (such as ImageIcon image = new ImageIcon(“flag.gif”); ) You can include both text and image in a JButton or JLabel –by specifying both a String and then an ImageIcon JLabel label2 = new JLabel(“Left”, new ImageIcon(“leftarrow.gif”)); You can change the item in the JButton or JLabel –using setText( ) or setIcon( ) as in label1.setText(“…”); You can also alter what appears in the JButton –based on whether the mouse is pointing at it (called Rollover) or if the button is currently being pressed JButton button2 = new JButton(icon1); button2.setPressedIcon(icon2); button2.setRolloverIcon(icon3);