Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University.

Slides:



Advertisements
Similar presentations
CS18000: Problem Solving and Object-Oriented Programming.
Advertisements

Unit 3 Graphical User Interface (GUI) Dr. Magdi AMER.
Graphic User Interfaces Layout Managers Event Handling.
1 Chapter 12 l Event-Driven Programming and GUIs l Swing Basics and a Simple Demo Program l Layout Managers l Buttons and Action Listeners l Container.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Java GUI Libraries Swing Programming. Swing Components Swing is a collection of libraries that contains primitive widgets or controls used for designing.
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.
IEEM 110 Computing in Industrial Applications Basic User Interface in Java.
GUI and Event-Driven Programming Recitation – 3/6/2009 CS 180 Department of Computer Science, Purdue University.
Chapter 121 Window Interfaces Using Swing Chapter 12.
CS102--Object Oriented Programming Lecture 19: – The Swing Package (II) Copyright © 2008 Xiaoyan Li.
1 lecture 12Lecture 13 Event Handling (cont.) Overview  Handling Window Events.  Event Adapters Revisited.  Introduction to Components and 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.
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)
Chapter 6: Graphical User Interface (GUI) and Object-Oriented Design (OOD) J ava P rogramming: Program Design Including Data Structures Program Design.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
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,
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.
Chapter 12- GUI’s, Java, and Swing.. Overview n What are GUI’s n How Java does GUI’s- Swing n Buttons n Containers n Text I/O and Swing n Review.
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,
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
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.
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.
Chapter 12 1 TOPIC 13B l Buttons and Action Listeners Window Interfaces Using Swing Objects.
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.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
Chapter 12Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 12 l Event-Driven Programming and GUIs l Swing Basics and.
COMP 150: Introduction to Object-Oriented Programming 1 Lecturer: Dr. AJ Bieszczad l Event-Driven Programming and GUIs l Swing Basics and a Simple Demo.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 5 Objectives  Learn about basic GUI components.  Explore how the GUI.
PANELS. Color Class Colour constants are as follows: –Color.black –Color.blue import java.awt.* to access Color Class.
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.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 15 : Swing III King Fahd University of Petroleum & Minerals College of Computer.
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.
Lesson 28: More on the GUI button, frame and actions.
1 Lecture 8: User Interface Components with Swing.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
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:
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
Java Visual Applications CSIS 3701: Advanced Object Oriented Programming.
©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.
CSC 205 Programming II Lecture 5 AWT - I.
A First Look at GUI Applications
Graphical User Interface (pronounced "gooey")
Graphical User Interface (GUI) Programming III
A Quick Java Swing Tutorial
Chapter 13: Advanced GUIs and Graphics
Window Interfaces Using Swing Objects Chapter 12
A Quick Java Swing Tutorial
Window Interfaces Using Swing Objects Chapter 12
Graphical User Interface
Presentation transcript:

Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

GUIs Windowing systems that interact with users often are called GUIs. A GUI accepts information from a user and makes it available to the program for processing. Most of the interaction is graphical in nature.

Controls on GUI WINDOW FRAME MENU BUTTON TEXT BOX COMBO BOX Many more….

Event Driven Programming Most GUI programs involve events and event handlers. A GUI event is an object that represents some action such as clicking the mouse, dragging the mouse, pressing a keyboard key, clicking the close-window button on a window, etc. When an object generates an event, it is said to fire the event.

Programming Example: A Simple Window This simple program produces a window and displays some text. –We will explore the following Jframe : to create a window JLabel : to create a label getContentPane().add() : add a component such as a label to the content pane of the window setTitle() : set the title of the window setSize() : set the size of the window setVisible() : Method setVisible permits the programmer to specify when GUI objects should be displayed and when they should not

import javax.swing.*; import java.awt.*; public class makeWindow { public static void main(String args[]) { int width=300; int height=200; JFrame myWindow=new JFrame(); //create the window myWindow.setSize(width,height); //set the title of the window myWindow.setTitle("this is a window"); //create the label JLabel myLabel=new JLabel("this is a label"); //add the label to the content pane of the window myWindow.getContentPane().add(myLabel); //set color of the content pane myWindow.getContentPane().setBackground(Color.CYAN); //make the window visible myWindow.setVisible(true); } } A Frame This colored area is the content pane Example

Exploring JFrame : Some methods A window class normally is derived from class JFrame. A derived window class inherits all the methods from class JFrame.

Window Listeners A window listener listens to events from a window, such as a click on the close- window button. A window listener is registered when it becomes associated with the object(s) to which it listens.

Clicking the Close-Window Button

An Example Component : Window Event: Window Closing Listener: performs the following tasks –Display a dialog box – telling the user that you are exiting the system –Exit the window Note: If the window-close button is not programmed, a click causes the window to disappear, but does not cause the program to end.

Example Code import javax.swing.*; import java.awt.*; public class makeWindow { public static void main(String args[]) { int width=300; int height=200; JFrame myWindow=new JFrame(); ……… ………….. //same code as explained in slide 6 …………………… //set listener makeWindowListner myListener= new makeWindowListner(); myWindow.addWindowListener(myListener); } } import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JPopupMenu; import javax. swing.*; public class makeWindowListner extends WindowAdapter{ public void windowClosing(WindowEvent e) { // Modal dialog with OK button String message = "You are exiting this window"; JOptionPane.showMessageDialog(null, message); System.exit(0); } } Listener Class

Example: Output Step 1: user clicks this close button Step 2: user will see this dialog box Step 3: window is closed

Methods of Class WindowAdapter Some examples:

Methods of Class WindowAdapter, cont. When you define a derived class of abstract class WindowAdapter, you override and redefine only those methods that you need. Because class WindowAdapter is abstract, this class can be used only as a base class for defining other classes.

What to Import It may be simpler to use import javax.swing.*; import java.awt.*; import java.awt.event.*; rather than trying to determine which import statements are needed for a particular window interface. –event.* represents a package within java.awt.

Frame-Content Pane Layout A frame is a component container that displays its contents in a top-level window with a title bar and buttons to resize, iconify, maximize, and close the frame. Unlike most Swing containers, adding a component to a frame is not done with the JFrame.add() method. This is because the frame holds several panes and it is necessary to specify a particular pane to which to add the component. The pane that holds child components is called the content pane. By default the content pane has a border layout

Border Layout, cont. A BorderLayout manager can place a component into any of five regions. Regions which are unused give up their space to BorderLayout.CENTER. This layout limits the GUI to five objects, these are almost always five (or fewer) JPanels. equivalent forms: content.add(label3, BorderLayout.CENTER); and content.add(label3, “Center”); and (for center ONLY) content.add(label3);

Some Layout Managers

Buttons A button is a GUI component that looks like a button and does something when it is clicked using a mouse. Like a label, a button is created and added to a container. Unlike a label, a button can fire an event and the event can cause a GUI to perform some action.

Adding Buttons A button is created using JButton Button_Name = new JButton(“Button_Label”); A button is added to a container using Container_Name.add(Button_Name);

Adding Buttons, cont.

Close-Window Buttons and JButtons A button added to a GUI is an object of class JButton. A close-window button is not an object of class JButton. Instead, it is part of a JFrame object.

Action Listeners and Action Events For each button, the GUI needs to –register (specify) the listener object(s). –define the methods to be invoked when an event is fired. For a statement such as stopButton.addActionListener(this); the class ButtonDemo is itself the listener class. Buttons fire action events which are handled by action listeners. An action listener is an object of type ActionListener, and ActionListener is an interface

Action Listeners and Action Events, cont. To make a class into an ActionListener –add implements ActionListener to the heading of the class definition –define a method named ActionPerformed. –register the ActionListener object with the component that will fire the event using the method addActionListener –(A component may register with more than one listener.)

Buttons and an Action Listener

The actionPerformed Method An actionListener class must have a method named actionPerformed that has one parameter of type ActionEvent. syntax public void actionPerformed(ActionEvent e) { Code_for_Actions_Performed }

Code a GUIs Appearance and Actions Separately Code for a Swing GUI is simpler if it is divided into two parts: –the GUI’s appearance on the screen –the GUI’s actions. In a complicated Swing GUI, either of these tasks by itself can be formidable.

The Model-View-Controller Pattern

What is MVC? Model-view-controller (MVC) is an architectural pattern. Pattern isolates business logic from user interface.business logicuser interface Results in an application where it is easier to modify either the visual appearance or the underlying business rules without affecting the other. Model represents the information (the data) of the application and the business rules used to manipulate the data View corresponds to elements of the user interface such as text, checkbox items, and so forth Controller manages details involving the communication to the model of user actions such as keystrokes and mouse movements.

Method setActionCommand Every object that fires an action event has an associated string known as the action command for that component. e.getActionCommand() returns the action command for the component that fired e. The default action command for a button is the string written on it. Method setActionCommand can be used to change the action command for the object.

Method setActionCommand, cont. example JButton stopButton = new JButton(“Red”); stopButton.setActionCommand(“Stop”); This permits the same string to be written on two different buttons, but with the two buttons distinguished from one another by the program.

Container Classes The JPanel Class The Container Class Class JPanel java.lang.Object – java.awt.Componentjava.awt.Component java.awt.Container – javax.swing.JComponentjavax.swing.JComponent » javax.swing.JPanel

Building GUI Classes New classes for a GUI often are built using existing classes. Two principal (and compatible) approaches: –use inheritance (for example, using a JFrame to make a derived class) –use a Swing class as a container, placing components in the container (for example, adding a button to a content pane)

The JPanel Class A GUI can be organized hierarchically, with window-like containers inside other window-like containers. Class JPanel is a simple container that does little more than hold components. Components can be placed in a JPanel which can be placed in another JPanel, … which can be placed in a JFrame. To place two components in BorderLayout.SOUTH for example, simply place the two components in a panel and place the panel in the BorderLayout.SOUTH position. The panel has its own layout manager.

The JPanel Class, cont.

The Container Class Class Container is a predefined class. An object of a class which descends from class Container is called a container class and can have components added to it. Class JFrame is a descendent of class Container, permitting any JFrame object to hold labels, buttons, panels, and other components. Class JPanel is a descendent of class Container, permitting any JPanel object to hold labels, buttons, other panels, and other components.

The JComponent Class Class JComponent is similar to class Container, and plays a similar role for components. Any class that descends from JComponent is called a JComponent class. Any JComponent object can be added to any Container object. Since class JComponent descends from class Container, a JComponent object can be added to another JComponent object.

Adding Components To add a component to a JFrame, use method getContentPane to obtain the content pane, and the use method add with the content pane as the calling object. example Container contentPane = getContentPane(); Jlabel label = new Jlabel(“Click Here”); contentPane.add(label); Add a button to a Panel: JPanel buttonPanel = new JPanel(); JButton stopButton = new JButton(“Stop”); buttonPanel.add(stopButton);

Objects in Swing Containers Swing containers use three kinds of objects: –the container class itself (such as a panel) –the components (labels, buttons, panels, etc.) –the layout manager. Typically, a GUI interface, and many subparts of the GUI, will consist of these three kinds of objects.

Text I/O using jTextField Create a text field with some initial text JTextField textfield = new JTextField("Initial Text"); Create a text field with some initial text and a default number of columns. // The number of columns controls the preferred width of the component; // each column is roughly the size of an M in the current font. int cols = 30; textfield = new JTextField("Initial Text", cols);

Text I/O using JTextArea Create a text area with some initial text JTextArea textarea = new JTextArea("Initial Text"); Create a text area with some initial text and a default number of rows and columns. // This number of rows and columns controls the preferred width and height of the component; // each row and column is rougly the size of an M in the current font. int rows = 20; int cols = 30; textarea = new JTextArea(" Initial Text", rows, cols);

Text box / Text area: Methods used Method getText returns the text written in an object of class JTextArea. Method setText of class JTextArea changes the text in the text area into whatever is provided as the argument to method setText. Limit the # of characters entered: JTextField name = new JTextField(10); The number of characters (per line) is not absolute, but represents the space needed for one ‘m’ character. –Note: the lower case "m" is the widest character in most character sets For ReadOnly data: for a textbox named “Name” –Name.setEditable(false); To Retrieve text –Name.getText().trim(); Note: check for NumberFormatException to check for unwanted special characters (comma, -,””) in “Name”

Quiz Create a text field object named “Name” –Set the default value of the text as “put name” –Set the length of this text field to 10