CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

Similar documents
Window Interfaces Using Swing Objects

Window Interfaces Using Swing Objects

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

Systems Programming Graphical User Interfaces

Programming Language Concepts: Lecture 8

Graphical User Interfaces. Swing. Jose Jesus García Rueda

Graphical User Interface (Part-1) Supplementary Material for CPSC 233

Programming Languages and Techniques (CIS120e)

Introduction to the JAVA UI classes Advanced HCI IAT351

Graphic User Interfaces. - GUI concepts - Swing - AWT

Window Interfaces Using Swing. Chapter 12

Graphical Interfaces

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

Graphical Interfaces

Chapter 1 GUI Applications

Graphical User Interfaces 2

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

CS 2113 Software Engineering

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Calculator Class. /** * Create a new calculator and show it. */ public Calculator() { engine = new CalcEngine(); gui = new UserInterface(engine); }

Introduction. Introduction

Swing I CHAPTER EVENT-DRIVEN PROGRAMMING 921 Events and Listeners 921

Swing I Event-Driven Programming Buttons, Events, and Other Swing Basics Containers and Layout Managers 946

GUI in Java TalentHome Solutions

BM214E Object Oriented Programming Lecture 13

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

Programming Mobile Devices J2SE GUI

Graphical User Interfaces 2

KF5008 Program Design & Development. Lecture 1 Usability GUI Design and Implementation

Method Of Key Event Key Listener must implement three methods, keypressed(), keyreleased() & keytyped(). 1) keypressed() : will run whenever a key is

Graphical User Interfaces 2

Graphical User Interfaces (GUIs)

DM503 Programming B. Peter Schneider-Kamp.

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

User interfaces and Swing

PIC 20A GUI with swing

Class 16: The Swing Event Model

The AWT Event Model 9

Agenda. Container and Component

JAVA NOTES GRAPHICAL USER INTERFACES

MIT AITI Swing Event Model Lecture 17

Swing from A to Z Some Simple Components. Preface

Chapter 14. More Swing

CS 251 Intermediate Programming GUIs: Components and Layout

CS 251 Intermediate Programming GUIs: Event Listeners

Java Programming Lecture 6

(Incomplete) History of GUIs

Computer Science 210: Data Structures. Intro to Java Graphics

12/22/11. Copyright by Pearson Education, Inc. All Rights Reserved.

COSC 123 Computer Creativity. Graphics and Events. Dr. Ramon Lawrence University of British Columbia Okanagan

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

Parts of a Contract. Contract Example. Interface as a Contract. Wednesday, January 30, 13. Postcondition. Preconditions.

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

Part 3: Graphical User Interface (GUI) & Java Applets

Unit 7: Event driven programming

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC).

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events

Graphical User Interfaces. Comp 152

กล ม API ท ใช. Programming Graphical User Interface (GUI) Containers and Components 22/05/60

Lecture 5: Java Graphics

Packages: Putting Classes Together

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in

Java. GUI building with the AWT

Class 14: Introduction to the Swing Toolkit

Swing from A to Z Using Focus in Swing, Part 2. Preface

Course: CMPT 101/104 E.100 Thursday, November 23, 2000

GUI Programming: Swing and Event Handling

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

JRadioButton account_type_radio_button2 = new JRadioButton("Current"); ButtonGroup account_type_button_group = new ButtonGroup();

Java - Applications. The following code sets up an application with a drop down menu, as yet the menu does not do anything.

CSE 8B Intro to CS: Java

H212 Introduction to Software Systems Honors

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

China Jiliang University Java. Programming in Java. Java Swing Programming. Java Web Applications, Helmut Dispert

1.00 Lecture 14. Lecture Preview

Chapter 13 Lab Advanced GUI Applications Lab Objectives. Introduction. Task #1 Creating a Menu with Submenus

GUI Forms and Events, Part II

GUI Event Handlers (Part I)

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Java Swing. Lists Trees Tables Styled Text Components Progress Indicators Component Organizers

Graphical User Interface (GUI)

Graphical User Interface (GUI)

encompass a group of features for building Graphical User Interfaces (GUI).

SINGLE EVENT HANDLING

Chapter 8. Java continued. CS Hugh Anderson s notes. Page number: 264 ALERT. MCQ test next week. This time. This place.

Java continued. Chapter 8 ALERT ALERT. Last week. MCQ test next week. This time. This place. Closed book. Assignment #2 is for groups of 3

Chapter 12 Advanced GUIs and Graphics

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Graphics User Defined Forms, Part I

Building Graphical User Interfaces. GUI Principles

Transcription:

CSEN401 Computer Programming Lab Topics: Graphical User Interface Window Interfaces using Swing Prof. Dr. Slim Abdennadher 22.3.2015 c S. Abdennadher 1

Swing c S. Abdennadher 2

AWT versus Swing Two basic sets of components to implement a graphical user Interface (GUI): Abstract Window Toolkit (AWT) Swing Swing can be viewed as an improved version of AWT. Swing implements a set of GUI components that build on AWT technology. We will use classes from both Swing and AWT. c S. Abdennadher 3

Event-Driven Programming A widget (component of a window) can get an event and can call the corresponding processing program. Main implementation issues: How to pass an event to widget? How to specify the event-processing program that will be called? How the event processing program can get details about the event that called it? GUIs are event driven: Generate events when user interacts with GUI, e.g. mouse click, mouse movement, typing in a text field,... Event information stored in object that extends AWTEvent. c S. Abdennadher 4

Creating a Simple Window import javax.swing.*; public class FirstWindow { public static void main(string[] args) { JFrame mywindow = new JFrame(); mywindow.setsize(400,100); mywindow.setvisible(true); } } import says that the program uses the Swing library. The object mywindow is an object of the class JFrame. A JFrame swing is a very simple window but with a set of features, e.g. close-window button,... setsize is a method of the class JFrame and sets the size of the window. setvisible makes the window visible on the scree. c S. Abdennadher 5

Adding Text to the Window import javax.swing.*; public class FirstWindow { public static void main(string[] args) { JFrame mywindow = new JFrame(); mywindow.setsize(400,100); JLabel mylabel = new JLabel("My first window"); mywindow.getcontentpane().add(mylabel); mywindow.setvisible(true); } } The object mylabel is an object of the class JLabel. Jlabel is a special kind of text that can be added to a JFrame or to any of a number of other kinds of objects. getcontent is a method of the class JFrame that add produces the content pane of the JFrame. Every JFrame has its content pane, e.g. inside of the JFrame. Using the add method, the label mylabel is added to the content pane of mywindow. c S. Abdennadher 6

Event Firing and Event Listener What should happen when the user clicks the close-window button? The window should fire an event and send it to a listener object. A listener object should have methods that should specify what should happen when events of various kinds are sent to the listener. These methods are called event handlers. The programmer has to define or redefine these event-handler methods. c S. Abdennadher 7

Adding Events to the Window import javax.swing.*; public class FirstWindow { public static void main(string[] args) { JFrame mywindow = new JFrame(); mywindow.setsize(400,100); JLabel mylabel = new JLabel("My first window"); mywindow.getcontentpane().add(mylabel); WindowDestroyer mylistener = new WindowDestroyer(); mywindow.addwindowlistener(mylistener); mywindow.setvisible(true); } } The listener object is WindowDestroyer. The object mylistener should be associated with the object (the window) mywindow, so that mylistener will receive any event fired by the object mywindow: mywindow.addwindowlistener(mylistener); A listener class should be defined. c S. Abdennadher 8

A Listener Class for Window Events import javax.swing.*; import java.awt.event.*; public class WindowDestroyer extends WindowAdapter { public void windowclosing(windowevent e) { System.exit(0); } } A window listener class for a GUI is often a derived class of the class WindowAdapter. The methods inherited from WindowAdapter class responds automatically to a different kind of event. Normally no new methods are added. Methods are redefined. The method that handles events that a window should be closed is windowclosing. The method windowclosing is redefined. The command ends the program and thus closes the window. The second import statement tells the compiler where the definitions for the WindowAdapter and for event handling are located. c S. Abdennadher 9

Methods in the Class WindowAdapter public void windowopened(windowevent e) Invoked when a window has been opened public void windowclosed(windowevent e) Invoked when a window has been closed public void windowclosing(windowevent e) Invoked when a window is in the process of being closed. public void windowiconified(windowevent e) Invoked when a window is iconified. public void windowdeinconified(windowevent e) public void windowdeactivated(windowevent e) public void windowactivated(windowevent e) Invoked when a window is activated, e.g. when you click in a window... c S. Abdennadher 10

Better Version of Our First Swing Program import javax.swing.*; public class FirstWindow extends JFrame { public FirstWindow() { super(); setsize(400,100); JLabel mylabel = new JLabel("My first window"); getcontentpane().add(mylabel); WindowDestroyer mylistener = new WindowDestroyer(); addwindowlistener(mylistener); } } This is the style you should follow in writing your own GUIs. You define a subclass of JFrame to define a window interface. The base class gives some basic window facilities. The derived class adds whatever additional features you want in your window interface. c S. Abdennadher 11

Program that uses the Class FirstWindow import javax.swing.*; public class FirstWindowDemo { public static void main(string[] args) { FirstWindow window1 = new FirstWindow(); window1.setvisible(true); } } FirstWindow window2 = new FirstWindow(); window2.setvisible(true); c S. Abdennadher 12

A Window with Title and Color Inherited Methods from the class JFrame: To give title to a window: settitle("second Window"); To give the window a background color: getcontentpane().setbackground(color.blue); The class Color contains constants for many of the common colors, e.g. YELLOW, MAGENTA, BLACK,... The class Color is in the AWT package. c S. Abdennadher 13

Layout Manager We can add more than one label to the content pane. How are the labels arranged? The arranging is done by a special kind of object known as a layout manager. Different layout managers follow different rules. FlowLayout is the simplest layout manager that arranges the components one after the other, going from the left to the right. BorderLayout is a layout manager that places labels into the five regions NORTH, SOUTH, EAST, WEST and CENTER. GridLayout is a layout manager that arranges components in rows and columns. The add method has only one argument, items are placed from left to right. getcontentpane().setlayout(new GridLayout(2,3)); c S. Abdennadher 14

Layout Manager Example import javax.swing.*; import java.awt.*; public class ThirdWindow extends JFrame { public ThirdWindow() { super(); setsize(400,100); getcontentpane().setlayout(new BorderLayout()); JLabel label1 = new JLabel("My name is"); getcontentpane().add(label1, BorderLayout.NORTH); JLabel label2 = new JLabel("Slim"); getcontentpane().add(label2, BorderLayout.SOUTH); settitle("second Window"); getcontentpane().setbackground(color.blue); WindowDestroyer mylistener = new WindowDestroyer(); addwindowlistener(mylistener); } } c S. Abdennadher 15

Adding Buttons import javax.swing.*; import java.awt.*; public class ButtonD extends JFrame { public static void main(string[] args) { ButtonD buttongui = new ButtonD(); buttongui.setvisible(true); } public ButtonD() { super(); setsize(400,100); JButton button = new JButton("Red"); getcontentpane().add(button); settitle("second Window"); getcontentpane().setbackground(color.blue); WindowDestroyer mylistener = new WindowDestroyer(); addwindowlistener(mylistener); } } c S. Abdennadher 16

Adding Action Listeners import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ButtonDemo extends JFrame implements ActionListener {... public ButtonDemo() {... getcontentpane().setlayout(new FlowLayout()); JButton button1 = new JButton("Red"); button1.addactionlistener(this); getcontentpane().add(button1); JButton button2 = new JButton("Black"); button2.addactionlistener(this); getcontentpane().add(button2);... } c S. Abdennadher 17

Action Listeners and Action Events button1.addactionlistener(this); registers this (ButtonDemo) as listener to receive events from the button called button1. An action listener is an object of type ActionListener. It is not A class but it is a property (interface). To make a class into an ActionListener, we need add the statement implements ActionListener to the beginning of the class definition. define a method named actionperformed. c S. Abdennadher 18

actionperfomed Method In order to be an action listener a class must have a method named actionperformed. The actionperformed method is the only method required by the interface ActionListener. The code is typically a branching statement. Often the branching depends on getactioncommand(). public void actionperformed(actionevent e) { if (e.getactioncommand().equals("red")) getcontentpane().setbackground(color.red); else if (e.getactioncommand().equals("black")) getcontentpane().setbackground(color.black); } c S. Abdennadher 19

Mouse Events The mouse listeners allow you to receive events to process: Button clicks, presses, or releases by the left, middle, or right buttons. Moves and drags. Which Modifier keys (shift, control, alt) were down when the event occurred. Notification when the mouse enters or exits the component. Scroll wheel movements. Normally handled for you. Sometimes used with graphics. If you are are drawing your own graphics (eg, on a JComponent or JPanel) and need to know where the user clicks, then you need to know about mouse events. You can easily add a mouse listener to a JComponent or JPanel. c S. Abdennadher 20

MouseListener The actions that a MouseListener catches: press: one of the mouse buttons is pressed. release: one of the mouse buttons is released. click: a mouse button was pressed and released without moving the mouse. This is perhaps the most commonly used. enter: mouse cursor enters the component. Often used to change cursor. exit: mouse cursor exits the component. Often used to restore cursor. To listen for these events you will use addmouselistener. c S. Abdennadher 21

MouseListener Interface and Mouse Events To implement a MouseListener interface, you must define the following methods. You can copy these definitions into your program and only make a meaningful body for those methods that are of interest. public void mousepressed(mouseevent e) {} public void mousereleased(mouseevent e) {} public void mouseclicked(mouseevent e) {} public void mouseentered(mouseevent e) {} public void mouseexited(mouseevent e) {} To get the mouse coordinates: All coordinates are relative to the upper left corner of the component with the mouse listener. int getx() // returns the x coordinate of the event. int gety() // returns the y coordinate of the event. To check for double clicks: Use the following MouseEvent method int getclickcount() // number of mouse clicks c S. Abdennadher 22

JPanel Class A GUI is often organized in a hierarchical fashion, with windowlike containers inside of other windowlike containers. JPanel is used to define subparts of a window. It is a very simple container class that does little more than grouping objects. A JPanel object is analogous to the braces used to combine a number of simpler Java statements into a single larger Java statement. A JPanel objects groups smaller objects, such as buttons and labels into a larger component. c S. Abdennadher 23

Putting Buttons in a Panel import javax.swing.*; import java.awt.*; import java.awt.event.*; public class PanelDemo extends JFrame implements ActionListener { public static void main(string[] args) { PanelDemo buttongui = new PanelDemo(); buttongui.setvisible(true); } public PanelDemo() { super(); setsize(400,100); WindowDestroyer mylistener = new WindowDestroyer(); addwindowlistener(mylistener); Container contentpane = getcontentpane(); c S. Abdennadher 24

Putting Buttons in a Panel contentpane.setbackground(color.blue); contentpane.setlayout(new BorderLayout()); JPanel buttonpanel = new JPanel(); buttonpanel.setbackground(color.white); buttonpanel.setlayout(new FlowLayout()); JButton button1 = new JButton("Red"); button1.setbackground(color.red); button1.addactionlistener(this); buttonpanel.add(button1); JButton button2 = new JButton("MAGENTA"); button2.setbackground(color.magenta); button2.addactionlistener(this); buttonpanel.add(button2); contentpane.add(buttonpanel, BorderLayout.SOUTH); } c S. Abdennadher 25

Putting Buttons in a Panel public void actionperformed(actionevent e) { if (e.getactioncommand().equals("red")) getcontentpane().setbackground(color.red); else if (e.getactioncommand().equals("magenta")) getcontentpane().setbackground(color.magenta); } } c S. Abdennadher 26