Programming With Java ICS201 University Of Ha’il1 Chapter 17 Graphical User Interfaces Swing I.

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.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
Graphical User Interface (GUI) Programming III. Lecture Objectives Exploring more GUI programming elements in Java Using labels in GUIs Using colors to.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
Swinging Into Swing Leo S. Primero III. Understanding what Swing Is Swing is a package that lets you create applications that use a flashy Graphical User.
Chapter 121 Window Interfaces Using Swing Chapter 12.
CS102--Object Oriented Programming Lecture 19: – The Swing Package (II) Copyright © 2008 Xiaoyan Li.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
CS102--Object Oriented Programming Lecture 18: – The Swing Package Copyright © 2008 Xiaoyan Li.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
Unit 11 Object-oriented programming: Graphical user interface Jin Sa.
Java Swing. Introduction to Swing A GUI (graphical user interface) is a windowing system that interacts with the user The Java AWT (Abstract Window Toolkit)
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.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Intro to GUIs (Graphical User Interfaces) Section 2.5Intro. to GUIs: a GUI Greeter Section 3.7Graphical/Internet Java: Einstein's Equation.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
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.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 13 : Swing I King Fahd University of Petroleum & Minerals College of Computer Science.
CMSC 202 Swing. Fall Introduction to Swing Swing is a Java package used to create GUIs The Java AWT (Abstract Window Toolkit) package is the original.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
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.
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.
Object Oriented programming Instructor: Dr. Essam H. Houssein.
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.
Introduction to GUI Programming with Java Graphical User Interfaces With AWT and Swing Towson University *Ref:
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.
Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,
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.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
Chapter 12Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 12 l Event-Driven Programming and GUIs l Swing Basics and.
Graphical User Interfaces. Graphical input and output with JOptionPane.
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 14 : Swing II King Fahd University of Petroleum & Minerals College of Computer Science.
Basics of GUI Programming Chapter 11 and Chapter 22.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
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.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Creating and Using Dialogs ● A dialog is a box that pops up and prompts the user for a value or informs them of something ● One way: directly create objects.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
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.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
Chapter 7 A First Look at GUI Applications Layout Managers.
A Quick Java Swing Tutorial
GUIs and Events Rick Mercer.
Chapter 17 Swing I Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
A First Look at GUI Applications
Java Swing.
Graphical User Interface (GUI) Programming III
Chapter 17 Swing I Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage Copyright © 2016 Pearson Inc. All.
Ellen Walker Hiram College
Timer class and inner classes
Comp 249 Programming Methodology
Advanced Programming in Java
Window Interfaces Using Swing Objects Chapter 12
GUI and Event-Handling Programming
Graphical User Interface
Presentation transcript:

Programming With Java ICS201 University Of Ha’il1 Chapter 17 Graphical User Interfaces Swing I

Programming With Java ICS201 Graphical input and output with JOptionPane University Of Ha’il2

Programming With Java ICS201 3 Types of JOptionPane s showMessageDialog(, ) Displays a message on a dialog with an OK button. showConfirmDialog(, ) Displays a message and list of choices Yes, No, Cancel; returns user's choice as an int with one of the following values: –JOptionPane.YES_OPTION –JOptionPane.NO_OPTION –JOptionPane.CANCEL_OPTION showInputDialog(, ) Displays a message and text field for input; returns the user's value entered as a String. –can pass null for the parent to all methods

Programming With Java ICS201 4 JOptionPane examples 1 showMessageDialog analogous to System.out.println for displaying a simple message import javax.swing.*; public class MessageDialogExample { public static void main(String[] args) { JOptionPane.showMessageDialog(null,"How's the weather?"); JOptionPane.showMessageDialog(null, "Second message"); }

Programming With Java ICS201 5 JOptionPane examples 2 showConfirmDialog analogous to a System.out.print that prints a question, then reading an input value from the user (can only be one of the provided choices) import javax.swing.*; public class ConfirmDialogExample { public static void main(String[] args) { int choice = JOptionPane.showConfirmDialog(null, "Erase your hard disk?"); if (choice == JOptionPane.YES_OPTION) { JOptionPane.showMessageDialog(null, "Disk erased!"); } else { JOptionPane.showMessageDialog(null, "Cancelled."); }

Programming With Java ICS201 6 JOptionPane examples 3 showInputDialog analogous to a System.out.print that prints a question, then reading an input value from the user (can be any value) import javax.swing.*; public class InputDialogExample { public static void main(String[] args) { String name = JOptionPane.showInputDialog(null,"What's yer name?"); JOptionPane.showMessageDialog(null, “Hello, " + name); }

Programming With Java ICS201 7 Java GUI: AWT and Swing The Java AWT (Abstract Window Toolkit) package is the original Java package for doing GUIs A GUI (graphical user interface) is a windowing system that interacts with the user The Swing package is an improved version of AWT –However, it does not completely replace AWT –Some AWT classes are replaced by Swing classes, but other AWT classes are needed when using Swing Swing GUIs are designed using a form of object-oriented programming known as event-driven programming When doing GUI programming, always import these packages: import java.awt.*; import javax.swing.*;

Programming With Java ICS201 8 Onscreen GUI elements GUIs contain the following elements: –frame: A graphical window on the screen. –components: such as buttons or text fields in a frame. –containers: Logical groups of components.

Programming With Java ICS201 Event-Driven Programming Event-driven programming is very different from most programming seen up until now –So far, programs have consisted of a list of statements executed in order –When that order changed, whether or not to perform certain actions (such as repeat statements in a loop, branch to another statement, or invoke a method) was controlled by the logic of the program In an event-driven program, the next thing that happens depends on the next event –methods are invoked automatically when an event signals that the method needs to be called

Programming With Java ICS201 Events Event-driven programming is a programming style that uses a signal-and-response approach to programming An event is an object that acts as a signal to another object know as a listener The sending of an event is called firing the event –such as a button that has been clicked

Programming With Java ICS201 Listeners A listener object performs some action in response to the event –A given component may have any number of listeners –Each listener may respond to a different kind of event, or multiple listeners might may respond to the same events

Programming With Java ICS Action events: ActionEvent most common / simple event type in Swing created by: –button clicks –check box checking / unchecking –menu clicks –pressing Enter in a text field –etc.

Programming With Java ICS201 Event Firing and an Event Listener

Programming With Java ICS Listening for events attach listener to component listener’s method will be called when event occurs (e.g. when the button is clicked) for Action events, use ActionListener

Programming With Java ICS201 A Simple Window A simple window can consist of an object of the JFrame class –A JFrame object includes a border and the usual three buttons for minimizing, changing the size of, and closing the window –The JFrame class is found in the javax.swing package JFrame firstWindow = new JFrame(); A JFrame can have components added to it, such as buttons, menus, and text labels – These components can be programmed for action firstWindow.add(endButton); –It can be made visible using the setVisible method firstWindow.setVisible(true);

Programming With Java ICS201 Example

Programming With Java ICS201 Some Methods in the Class JFrame (Part 1 of 3)

Programming With Java ICS201 Some Methods in the Class JFrame (Part 2 of 3)

Programming With Java ICS201 Some Methods in the Class JFrame (Part 3 of 3)

Programming With Java ICS201 Pixels and the Relationship between Resolution and Size A pixel is the smallest unit of space on a screen –Both the size and position of Swing objects are measured in pixels –The more pixels on a screen, the greater the screen resolution A high-resolution screen of fixed size has many pixels Therefore, a two-pixel figure on a low-resolution screen will look larger than a two-pixel figure on a high-resolution screen

Programming With Java ICS JFrame example 1 A simple program that creates and shows a JFrame: import javax.swing.*; public class SimpleFrame { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setVisible(true); } Graphical output:

Programming With Java ICS JFrame example 2 A program that sets several properties of the JFrame: import java.awt.*; import javax.swing.*; public class SimpleFrame2 { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setForeground(Color.WHITE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocation(new Point(10, 50)); frame.setSize(new Dimension(300, 120)); frame.setTitle("A frame"); frame.setVisible(true); } Graphical output:

Programming With Java ICS Pitfall: Forgetting to Program the Close-Window Button Adding the following lines to a constructor of a Frame or JFrame class will ensure that when the user clicks the close- window button, nothing happens firstWindow.setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE); If this were not set, the default action would be JFrame.HIDE_ON_CLOSE –This would make the window invisible and inaccessible, but would not end the program. –Therefore, given this scenario, there would be no way to click the "Click to end program" button.

Programming With Java ICS201 Buttons A button object is created from the class JButton and can be added to a JFrame –The argument to the JButton constructor is the string that appears on the button when it is displayed JButton endButton = new JButton("Click to end program."); firstWindow.add(endButton);

Programming With Java ICS201 Action Listeners and Action Events Clicking a button fires an event The event object is "sent" to another object called a listener –This means that a method in the listener object is invoked automatically

Programming With Java ICS Components example import java.awt.*; import javax.swing.*; public class ComponentsExample1 { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(new Dimension(300, 100)); frame.setTitle("A frame"); JButton button1 = new JButton(); button1.setText(“Click me!"); button1.setBackground(Color.RED); frame.add(button1); frame.setVisible(true); }

Programming With Java ICS201 Example - firstWindow import javax.swing.*; public class FirstSwingDemo { public static void main(String[] args) { JFrame firstWindow = new JFrame(); firstWindow.setSize(300, 200); firstWindow.setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE); JButton endButton = new JButton("Click to end program."); EndingListener buttonEar = new EndingListener(); endButton.addActionListener(buttonEar); firstWindow.add(endButton); firstWindow.setVisible(true); } University Of Ha’il27

Programming With Java ICS201 Example - firstWindow import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class EndingListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } University Of Ha’il28

Programming With Java ICS201 The Normal Way to Define a JFrame

Programming With Java ICS201 A Better Version of FirstWindow Swing GUI A better version of FirstWindow makes it a derived class of the class JFrame –This is the normal way to define a windowing interface The constructor in the new FirstWindow class starts by calling the constructor for the parent class using super(); –This ensures that any initialization that is normally done for all objects of type JFrame will be done Almost all initialization for the window FirstWindow is placed in the constructor for the class Note that this time, an anonymous object is used as the action listener for the endButton

Programming With Java ICS201 Old and New Versions Old New The normal way to define a JFrame

Programming With Java ICS201 Example - firstWindow import javax.swing.*; public class FirstWindow extends JFrame{ Public firstWindow() { super(); setSize(300, 200); setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE); JButton endButton = new JButton("Click to end program."); endButton.addActionListener(buttonEar); add(endButton); } University Of Ha’il32

Programming With Java ICS201 Example - firstWindow public class DemoWindow { public static void main(String[] args) { FirstWindow w = new FirstWindow(); w.setVisible(true); } University Of Ha’il33

Programming With Java ICS201 Tip: Ending a Swing Program GUI programs are often based on a kind of infinite loop –The windowing system normally stays on the screen until the user indicates that it should go away If the user never asks the windowing system to go away, it will never go away In order to end a GUI program, System.exit must be used when the user asks to end the program –It must be explicitly invoked, or included in some library code that is executed. –Otherwise, a Swing program will not end after it has executed all the code in the program

Programming With Java ICS201 Labels A label is an object of the class JLabel –Text can be added to a JFrame using a label –The text for the label is given as an argument when the JLabel is created –The label can then be added to a JFrame JLabel greeting = new JLabel("Hello"); add(greeting); 17-35

Programming With Java ICS201 Color In Java, a color is an object of the class Color – The class Color is found in the java.awt package –There are constants in the Color class that represent a number of basic colors A JFrame can not be colored directly –Instead, a program must color something called the content pane of the JFrame –Since the content pane is the "inside" of a JFrame, coloring the content pane has the effect of coloring the inside of the JFrame –Therefore, the background color of a JFrame can be set using the following code: getContentPane().setBackground(Color); 17-36

Programming With Java ICS201 The Color Constants 17-37

Programming With Java ICS201 A JFrame with Color

Programming With Java ICS201 A JFrame with Color (Cont’d)

Programming With Java ICS201 Layout Managers Most Swing UIs utilise a LayoutManager to control positioning of items There is a choice of these which work in different ways Initially we do without one, and position items ourselves: frame.setLayout(null); means that we will determine the size and position of components

Programming With Java ICS201 Absolute positioning JFrame frame = new JFrame("I am a JFrame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(20,30,300,100); frame.setLayout(null); JButton butt=new JButton("Click me"); frame.getContentPane().add(butt); butt.setBounds(20, 20, 200,20); frame.setVisible(true); setBounds gives the screen co- ordinates of the top left corner (20,30) and the width (300) and height(100) of the frame. setBounds fixes its position and size.

Programming With Java ICS201 Layout Managers Multiple components can be added to the content pane of a JFrame using the add method –However, the add method does not specify how these components are to be arranged To describe how multiple components are to be arranged, a layout manager is used –There are a number of layout manager classes: BorderLayout, FlowLayout, and GridLayout

Programming With Java ICS201 Border Layout Managers A BorderLayout manager places the components that are added to a JFrame object into five regions –BorderLayout.NORTH, –BorderLayout.SOUTH, –BorderLayout.EAST, –BorderLayout.WEST, –BorderLayout.Center A BorderLayout manager is added to a JFrame using the setLayout method setLayout(new BorderLayout());

Programming With Java ICS201 Border Layout Managers When using a BorderLayout manager, the location of the component being added is given as a second argument to the add method add(label1, BorderLayout.NORTH);

Programming With Java ICS201 Flow Layout Managers The FlowLayout manager is the simplest layout manager setLayout(new FlowLayout()); –It arranges components one after the other, going from left to right –Components are arranged in the order in which they are added The add method has only one argument when using the FlowLayoutManager add(label1);

Programming With Java ICS201 A GridLayout manager arranges components in a two-dimensional grid with some number of rows and columns setLayout(new GridLayout(rows, columns)); –Each entry is the same size –The two numbers given as arguments specify the number of rows and columns –Each component is stretched so that it completely fills its grid position –Note: None of the lines in the diagram are normally visible Grid Layout Managers

Programming With Java ICS201 Grid Layout Managers When using the GridLayout class, the method add has only one argument add(label1); –Items are placed in the grid from left to right –The top row is filled first, then the second, and so forth

Programming With Java ICS201 Grid Layout Managers

Programming With Java ICS201 Some Layout Managers

Programming With Java ICS201 Panels A panel is an object of the JPanel class that serves as a simple container –It is used to group smaller objects into a larger component (the panel) –One of the main functions of a JPanel object is to subdivide a JFrame or other container JPanel somePanel = new JPanel(); somePanel.setLayout(new FlowLayout()); 17-50

Programming With Java ICS201 JTextField For single-line text input Methods getText, setText A text field is an object of the class JTextField

Programming With Java ICS201 Text Fields There is also a constructor with one additional String parameter for displaying an initial String in the text field JTextField name = new JTextField( "Enter name here.", 30); A Swing GUI can read the text in a text field using the getText method String inputString = name.getText(); The method setText can be used to display a new text string in a text field name.setText("This is some output"); 17-52

Programming With Java ICS201 Text Areas A text area is an object of the class JTextArea –It is the same as a text field, except that it allows multiple lines –Two parameters to the JTextArea constructor specify the minimum number of lines, and the minimum number of characters per line that are guaranteed to be visible JTextArea theText = new JTextArea(5,20); –Another constructor has one addition String parameter for the string initially displayed in the text area JTextArea theText = new JTextArea( "Enter\ntext here." 5, 20); 17-53

Programming With Java ICS201 Text Areas The line-wrapping policy for a JTextArea can be set using the method setLineWrap –The method takes one boolean type argument –If the argument is true, then any additional characters at the end of a line will appear on the following line of the text area –If the argument is false, the extra characters will remain on the same line and not be visible theText.setLineWrap(true); 17-54

Programming With Java ICS201 Text Fields and Text Areas A JTextField or JTextArea can be set so that it can not be changed by the user theText.setEditable(false); –This will set theText so that it can only be edited by the GUI program, not the user –To reverse this, use true instead (this is the default) theText.setEditable(true); 17-55

Programming With Java ICS201 Example Calc.java University Of Ha’il56