CS-0401 INTERMEDIATE PROGRAMMING USING JAVA

Slides:



Advertisements
Similar presentations
Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of.
Advertisements

Graphical User Interfaces
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.
IEEM 110 Computing in Industrial Applications Basic User Interface in Java.
GUI Layout Managers Arkadiusz Edward Komenda. Outline Components and Containers Layout Managers Flow Layout Grid Layout Border Layout Nested Containers.
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.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
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.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
A First Look At GUI Applications Chapter Introduction Many Java applications use a graphical user interface or GUI (pronounced “gooey”). A GUI.
MSc Workshop - © S. Kamin, U.Reddy Lect 5 – GUI Prog - 1 Lecture 5 – GUI Programming r Inner classes  this and super r Layout r Reading: m.
Layout Management Containers can arrange their components. Our container is a JPanel, and it can set the way it’s components will be laid out : mypanel.setLayout.
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.
Chapter 12: A First Look at GUI Applications Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis.
© 2010 Pearson Addison-Wesley. All rights reserved. 7-1 Chapter Topics Chapter 7 discusses the following main topics: –Introduction –Creating Windows –Equipping.
Starting Out with Java: From Control Structures through Objects.
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
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.
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.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Layout Managers Arranges and lays out the GUI components on a container.
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.
Kim B. Bruce, Andrea Danyluk & Tom Murtagh Williams College † Partially supported by NSF CCLI grant DUE Java: An Eventful Approach An innovative.
Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets.
GUI Basics. Agenda What GUI How to make in java Creating frames Frequently used GUI components Layout Managers.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: A First Look at GUI Applications Starting Out with Java From Control.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: From Control Structures through Objects Third Edition.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
Graphical User Interfaces (GUI). PART ONE About GUI’s.
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,
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.
1 Lecture 8: User Interface Components with Swing.
Introduction to GUI in 1 Graphical User Interface 3 Nouf Almunyif.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
CIS 270—Application Development II Chapter 11—GUI Components: Part I.
CHAPTER 12 A First Look at GUI Applications Copyright © 2016 Pearson Education, Ltd.
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.
Chapter 7 A First Look at GUI Applications Layout Managers.
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
A First Look at GUI Applications Radio Buttons and Check Boxes
Christopher Budo, Davis Nygren, spencer franks, Luke miller
Swing JComponents.
A First Look at GUI Applications
Modern Programming Language Java
Chapter 7: A First Look at GUI Applications
Ellen Walker Hiram College
Chap 7. Building Java Graphical User Interfaces
Chapter 13: Advanced GUIs and Graphics
Graphical User Interfaces -- Introduction
Chapter 7: A First Look at GUI Applications
Timer class and inner classes
Containers and Components
Creating Graphical User Interfaces
Graphical User Interface
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

CS-0401 INTERMEDIATE PROGRAMMING USING JAVA Prof. Dr. Paulo Brasko Ferreira Spring 2015

Chapter 12 Java Graphical User Interface

Pop Quiz !!! What is the difference between these three types of classes? Regular classe Abstract Classe Interface

You will learn how to do this GUI in this chapter

Creating our First Window

Steps to create a window Steps to create a window (“Frame” in Java terms) Create a new frame object with “new Frame( )” JFrame frame = new JFrame(); Set its title frame.setTitle("A Simple Window"); Set its size frame.setSize(200, 300); Set its default close operation frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Set it visible frame.setVisible(true); See SimpleWindow

Creating and Adding Components into a Frame

Process of adding components GUI components panel frame

How to create GUI components ObjectType objectName = new ObjectType(args); Examples: JButton submitRequestButton = new JButton(“Submit”); JLabel label1 = new JLabel(“File Name: ”); JTextField textField = new JTextField(20);

Creating the JPanel and adding components JPanel panel = new JPanel ( ); panel.add(submitRequestButton); panel.add(textField); panel.add(label1);

Adding the panel into the frame frame.add(panel); frame.visible(true); See KiloConverterWindowPhase_1

Handling Events with Action Listeners

Events and Action Listeners An event is a user interaction with your GUI Examples of events: A click of a mouse button Window being resized Typing words in a text area Selecting an option in a drop-down list An Action Listener is an object that responds to these events I was clicked! Button Event Assigned Action Listener

Action Listener An Action Listener is an object that responds to the events We need to create a new class just to be a listener of a given event! Object of what Class???

Creating an Event Listener Class

Creating an Event Listener Action Listener needs to be an object of a new class The class will be placed inside your class (inner class) public class YourRegularClass { private void yourRegularMethods() // doing some cool stuff here } private class Inner // doing some other cool stuff here

Let’s create a JButton action listener class Adding an inner class Let’s create a JButton action listener class Create this class at the end of your class, but before the last curly bracket: private class MyButtonListener implements ActionListener { // do your calculations here } Implements???

Interface??? Wow, it is getting more and more complicated! Time-out!!! “Implements” means that we are going to provide a code (an implementation) for a given interface Interface??? Wow, it is getting more and more complicated!

Interface An Interface is a java file containing only method definitions, but no implementation: Example:

Interfaces Interface just define the methods signature: Public type Returning type Method name Input arguments Interface does not implement the method

A specific method in your program Interfaces Interfaces are like contracts! Both parties must agree and obey the rules defined in the contract I’ll call a method of your program I’ll handle that! A specific method in your program Java Virtual Machine I have been pressed Button Pressed

Java Development Team at Sun Systems But What Method? Java Development Team at Sun Systems Is it the same as Jared’s? What is Mara’s method name? It would be nice it they use the same method name

Action Listener Interface public interface ActionListener extends EventListener { public void actionPerformed(ActionEvent e); }

Action Listener Interface You: “I promise to have such a method in my code” Java Team: “We will call your actionPerformed”

Action Listener Interface private class CalcButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) // your code here to handle the action // like converting kilometers to miles }

How Events are Handled Action Listener Object JButton Component actionPerformed(ActionEvent e) #1: The Mouse Clicks the Button #2: JButton Generates an Event #3: JVM receives the event and calls the action listener object’s actionPerformed method #4: actionPerformed method does whatever you have programmed

What you must do Create a JButton and register a listener to it button1.addActionListener(new MyButtonListener()) Create an inner class inside your class and add the keywords “implements ActionListener” private class ButtonListener implements ActionListener Add the method defined in that interface (ActionListener) public void actionPerformed(ActionEvent e) Code inside this method whatever functionality is wanted See KiloConverterWindow_Phase_2

How do we retrieve the text from the JTextField? JTextField kiloTextField = new JTextField(); input = kiloTextField.getText(); miles = Double.parseDouble(input) * 0.6214; JOptionPane.showMessageDialog(null, input + " kilometers is " + miles + " miles.");

GUI with multiple buttons

GUI with multiple buttons How would you implement action listeners for all three buttons? Two ways: Creating three inner classes, one for each action listener See code ColorWindow.java Creating one inner class and figure out which button has generated the event by using ActionEvent e See code ColorWindow2.java

Layout Managers

Layout Managers Run program ColorWindow.java Resize the window in many different ways What happen? Who is responsible for organizing the GUI components all the time?

Meet the Layout Manager!

Layout Managers Layout manager is an object that governs components’ Position Sizes The programmer does not normally specify the exact location of a component He/she just add the component into the panel panel.add(button1); panel.add(button2); panel.add(button3); panel.add(button4);

Layout Managers How to use a layout manager: You designate a layout for a given panel: JPanel panel = new JPanel(); BorderLayout layout = new BorderLayout(); panel.setLayout(layout); panel.setLayout(new BorderLayout());

Types of Layout Managers

Flow Layout Manager

Sample: ColorWindow.java Flow Layout Manager FlowLayout layout = new FlowLayout(); myPanel.setLayout(layout); After Resizing Arranges components of different sizes in rows Flow layout is the default layout manager for JPanels What does it mean? You can add as many components into the container as you want (no limit) You can include other panels inside a panel as well What happen if you resize the window during run-time? Sample: ColorWindow.java

FlowLayout Constructors Constructs a new FlowLayout with a centered alignment and a default 5-unit horizontal and vertical gap FlowLayout layout = new FlowLayout( ); Sample: ColorWindow.java

FlowLayout Constructors FlowLayout(int align): Constructs a new FlowLayout with the specified alignment and a default 5-unit horizontal and vertical gap. Align options: FlowLayout.LEADING (left alignment) FlowLayout.CENTER (default) FlowLayout.TRAILING (rigtht alignment) FlowLayout layout = new FlowLayout(FlowLayout.LEADING); Sample: ColorWindow.java

FlowLayout Constructors FlowLayout(int align, int hgap, int vgap): Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps. FlowLayout layout = new FlowLayout(FlowLayout. LEADING, 20, 50); Sample: ColorWindow.java

Border Layout Manager

Border Layout Manager Panel is separated by regions North, South, West, East, Center Jframe’s default layout manager You can add only 5 components

Sample: BorderWindow.java Border Layout Manager Example: JPanel panel = new JPanel( ); panel.setLayout(new BorderLayout( )); JButton button1 = new JButton(“Click me”); panel.add(button1, BorderLayout.NORTH); JButton button2 = new JButton(“Submit”); panel.add(button2); JButton button3 = new JButton(“Cancel”); panel.add(button3); In what regions will button2 and button3 be added? Sample: BorderWindow.java

Can I create this window with lots of components using Border Layout? Nesting components Can I create this window with lots of components using Border Layout?

Rules governing Border Layout North and South regions: Component will be resized horizontally to fills up the entire region West, Center, East regions: Component will be resized vertically to fills up the entire region

Rules governing Border Layout No need to place a component in all the regions Regions will shrink and expand as necessary You can adjust vertical and Horizontal gaps BorderLayout (int horizontalGap, int verticalGap); panel.setLayout(new BorderLayout(5,10)); BorderWindow.java

How can we avoid the buttons to get stretched? BorderPanelWindow.java How can we avoid the buttons to get stretched?

Grid Layout Manager

Grid Layout Manager Divides the container into cells (like in Excel spreadsheets) GridLayout(int rows, int columns) new GridLayout(2 , 3); No need to place a component in all the cells One component per cell The cells are filled up in the order that you add components There is no way of specifying cell location

How to create this GUI?

More about GUI components STOP

Radio Buttons

Radion Buttons How radio buttons work? If I click on “Regular coffee” should it remove my Bagel selection?

Grouping Radio Buttons Creating the radio buttons JRadioButton radio1 = new JRadioButton(“None”); JRadioButton radio2 = new JRadioButton(“Decaf”); JRadioButton radio3 = new JRadioButton(“Regular”); Group them together ButtonGroup group = new ButtonGroup( ); group.add(radio1); group.add(radio2); group.add(radio3); You still need to add the buttons into a JPanel panel.add(radio1); panel.add(radio2); panel.add(radio3); See CoffeePanel.java

Check Radio Button Programmatically During the definition of the button: regularCoffee = new JRadioButton("Regular coffee", true); During run-time: cappuccino.setSelected(true); cappuccino.doClick( );

Taking action as a radio button is clicked Depending on your application, you might want to add listeners to each of your radio buttons As soon as the radio button is selected you can take some action Like disabling some other components in your GUI Veteran? Some discounts might be available See MetricConverterWindow.java

Adding listener for a radion button milesButton.addActionListener(new RadioButtonListener()); private class RadioButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) if (e.getSource() == milesButton) // do stuff here }

Just checking if the button is selected public double getCoffeeCost() { double coffeeCost = 0.0; if (noCoffee.isSelected()) coffeeCost = NO_COFFEE; else if (regularCoffee.isSelected()) coffeeCost = REGULAR_COFFEE; else if (decafCoffee.isSelected()) coffeeCost = DECAF_COFFEE; else if (cappuccino.isSelected()) coffeeCost = CAPPUCCINO; return coffeeCost; }

Check Boxes

Check Boxes JCheckBox myCB = new JCheckBox(“Butter”); JCheckBox myCB = new JCheckBox(“Cream”, true);

Responding to CheckBox Event You must implement the ItemListener interface private Class MyInnerClass implements ItemListener You must implement the method itemStateChanged ( ) public void itemStateChanged(ItemEvent e) See ColorCheckBoxWindow.java

Checking programmatically if a checkbox is checked To check if a checkbox has been selected during run-time: public boolean checkBox.isSelected() Example: if (myCheckBox.isSelected()) { // do some stuff here } See ToppingPanel.java

Borders

What is a Border Factory??? The Border Class A component can appear with several different styles of borders around it A Border object specifies the details of a border You use the BorderFactory class to create a border object panel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); What is a Border Factory???

Border Factory A factory class is a class that provides different types of objects based on the specifications you give to it as input argument

Border Factory

Examples Border blackline, raisedetched, loweredetched, raisedbevel, loweredbevel, empty; blackline = BorderFactory.createLineBorder(Color.black); raisedetched = BorderFactory.createEtchedBorder(EtchedBorder.RAISED); loweredetched = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED); raisedbevel = BorderFactory.createRaisedBevelBorder(); loweredbevel = BorderFactory.createLoweredBevelBorder(); empty = BorderFactory.createEmptyBorder(); jComp1.setBorder(blackline); jComp2.setBorder(raisedbevel); jComp3.setBorder(loweredbevel); jComp4.setBorder(empty);

The Brandi’s Bagel House See CoffeePanel.java