Graphical User Interfaces in Java - SWING

Similar documents
Dr. Hikmat A. M. AbdelJaber

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

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

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

17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau

Graphical User Interfaces. Comp 152

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords

Graphic User Interfaces. - GUI concepts - Swing - AWT

Dr. Hikmat A. M. AbdelJaber

Systems Programming Graphical User Interfaces

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class.

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

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

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

Part I: Learn Common Graphics Components

Basicsof. JavaGUI and SWING

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

Window Interfaces Using Swing Objects

Containers and Components

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!

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

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

Introduction to the JAVA UI classes Advanced HCI IAT351

Chapter 6: Graphical User Interfaces

Java. GUI building with the AWT

Chapter 12 Advanced GUIs and Graphics

Introduction. Introduction

Window Interfaces Using Swing Objects

GUI in Java TalentHome Solutions

COMP16121 Sample Code Lecture 1

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

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski

Agenda. Container and Component

Swing/GUI Cheat Sheet

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

Java: Graphical User Interfaces (GUI)

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

Building Java Programs Bonus Slides

Swing UI. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

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

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

PIC 20A GUI with swing

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

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

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

Graphical User Interfaces (GUIs)

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

Top-Level Containers

Building Graphical User Interfaces. Overview

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Graphical User Interface (GUI) components in Java Applets. With Abstract Window Toolkit (AWT) we can build an applet that has the basic GUI

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

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

Building Graphical User Interfaces. GUI Principles

SampleApp.java. Page 1

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how to paint graphics on GUI components

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

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1

To gain experience using GUI components and listeners.

More Swing. CS180 Recitation 12/(04,05)/08

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

CSE 1325 Project Description

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

CS 251 Intermediate Programming GUIs: Components and Layout

Overview. Building Graphical User Interfaces. GUI Principles. AWT and Swing. Constructing GUIs Interface components GUI layout Event handling

Example: Building a Java GUI

Graphical User Interfaces in Java

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

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN

Chapter 7: A First Look at GUI Applications

CHAPTER 2. Java Overview

Layout. Dynamic layout, Swing and general layout strategies

Packages: Putting Classes Together

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN

User interfaces and Swing

2110: GUIS: Graphical User Interfaces

Example: Building a Java GUI

Systems Programming. Bachelor in Telecommunication Technology Engineering Bachelor in Communication System Engineering Carlos III University of Madrid

Using Several Components

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

Chapter 9 Designing Graphical User Interfaces (GUIs)

Together, the appearance and how user interacts with the program are known as the program look and feel.

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

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

CS11 Java. Fall Lecture 4

No SVN checkout today. Object-Oriented Design

Chapter 13 GUI Basics. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved.

CompSci 125 Lecture 17. GUI: Graphics, Check Boxes, Radio Buttons

Unit 6: Graphical User Interface

Sri Vidya College of Engineering & Technology

Java Programming Lecture 6

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

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

Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS

Object-Oriented Programming Design. Topic : User Interface Components with Swing GUI Part III

Transcription:

Graphical User Interfaces in Java - SWING

Graphical User Interfaces (GUI) Each graphical component that the user can see on the screen corresponds to an object of a class Component: Window Button Menu... Class: JFrame JButton JMenu... import javax.swing.componente;

Example JMenu JFrame JLabel JTextField JButton

Graphical User Interfaces in Java (I) There are more than 250 classes for graphical user interface components and logic The goal is to create intuitive and usable GUIs. Programming these interfaces may not always be intuitive and the code can sometimes be difficult to read. For that reason, some IDEs include tools for graphically designing GUIs and automatic code generation (we will not use those in the course).

Graphical User Interfaces in Java (II) The AWT library The first library for implementing GUIs in Java. For performance reasons, the AWT components used the underlying components on the execution platform (Solaris, Windows, Linux, ): Version J2SE 1.2 and onwards include the Swing framework.

Swing s Architecture Swing is a framework for implementation of GUIs that allows for separation of interface and data. Swing uses one thread (eventdispatch thread). Swing allows for the implementation of platform independent GUIs.

A Visual Index to the Swing Components (I) http://java.sun.com/docs/books/tutorial/uiswing/components/components.ht ml

A Visual Index to the Swing Components (II) http://java.sun.com/docs/books/tutorial/uiswing/components/components.ht ml

A Visual Index to the Swing Components (III) http://java.sun.com/docs/books/tutorial/uiswing/components/components.ht ml

Window based GUIs Creating and displaying a window: import javax.swing.jframe; public class MáquinaDeCalcular { public static void main(string[] argumentos) { JFrame janela = new JFrame("Calculadora"); janela.setvisible(true); The application does not terminate

JFrame: import javax.swing.jframe; public class MáquinaDeCalcular { public static void main(string[] argumentos) { Jframe janela = new JFrame("Calculadora"); // Estabelece o tamanho da janela em pixeis (largura, altura) janela.setsize(300, 200); // Estabelece a localizaçãodajanela: distância do canto superior // esquerdodajanelaao canto superior esquerdo do ecrã janela.setlocation(200, 100); // A janelanão é redimensionável janela.setresizable(false); // Quando a janela é fechada a aplicaçãotermina janela.setdefaultcloseoperation(jframe.exit_on_close); janela.setvisible(true); Very important!

A JFrame on the desktop 100 200 200 300

Adding components to the window Add a button: import javax.swing.jframe; import javax.swing.jbutton; public class MáquinaDeCalcular { public static void main(string[] argumentos) { JFrame janela = new JFrame("Calculadora"); janela.getcontentpane().add(new JButton("=")); janela.setsize(300, 200); janela.setlocation(200, 100); janela.setresizable(false); janela.setdefaultcloseoperation(jframe.exit_on_close); janela.setvisible(true);

A window with a button ( = ) The button occupies the entire window

Container: Access content in the window The content of a window: JFrame janela = new JFrame("Calculadora"); Container contentor = janela.getcontentpane(); contentor.setbackground(color.white) contentor.add(new JButton("=")); Set the background color of the window To use Containerand Color: import java.awt.container; import java.awt.color;

Layout of components There are different layout managers implemented in Swing: FlowLayout GridLayout BorderLayout... The components added to another component (such as a container) will be laid out according to the layout manager set on that component. import java.awt.layoutespecífico;

Layout Managers LayoutManagers do the following: Compute the minimum, preferred and maximum size of a container. Layouts the components added to the container (its children) The layout is done using the characteristics of the manager and the minimum, preferred, and maximum size of its children.

FlowLayout import java.awt.container; import java.awt.flowlayout; import javax.swing.jframe; import javax.swing.jbutton; public class MáquinaDeCalcular { public static void main(string[] argumentos) { JFrame janela = new JFrame("Calculadora"); Container contentor = janela.getcontentpane(); contentor.setlayout(new FlowLayout()); contentor.add(new JButton("1")); contentor.add(new JButton("2")); contentor.add(new JButton("3")); janela.setsize(300, 200); janela.setlocation(200, 100); janela.setresizable(false); janela.setdefaultcloseoperation(jframe.exit_on_close); janela.setvisible(true);

FlowLayout

GridLayout import java.awt.container; import java.awt.gridlayout; import javax.swing.jframe; import javax.swing.jbutton; public class MáquinaDeCalcular { public static void main(string[] argumentos) { JFrame janela = new JFrame("Calculadora"); Container contentor = janela.getcontentpane(); contentor.setlayout(new GridLayout(3,1)); contentor.add(new JButton("1")); contentor.add(new JButton("2")); contentor.add(new JButton("3")); janela.setsize(300, 200); janela.setlocation(200, 100); janela.setresizable(false); janela.setdefaultcloseoperation(jframe.exit_on_close); janela.setvisible(true); 3 rows and 1 column

GridLayout

BorderLayout import java.awt.container; import java.awt.borderlayout; import javax.swing.jframe; import javax.swing.jbutton; public class MáquinaDeCalcular { public static void main(string[] argumentos) { JFrame janela = new JFrame("Calculadora"); Container contentor = janela.getcontentpane(); contentor.setlayout(new BorderLayout()); contentor.add(new JButton("1"), BorderLayout.NORTH); contentor.add(new JButton("2"), BorderLayout.WEST); contentor.add(new JButton("3"), BorderLayout.EAST); janela.setsize(300, 200); janela.setlocation(200, 100); janela.setresizable(false); janela.setdefaultcloseoperation(jframe.exit_on_close); janela.setvisible(true);

BorderLayout NORTH WEST EAST CENTER SOUTH

Other Layout Managers There are other LayoutManagers: BoxLayout like FlowLayout, but with more options. CardLayout allows for several components to occupy the same space. Allows for creation of taps and tabbed panes. GridBagLayout is very flexible (and complex). Defines a grid, but allows fine control over how components are placed in the grid. GroupLayout was developed for IDE frameworks for GUI builders but can be used by hand as well. Uses two independent layouts (vertical and horizontal). SpringLayout is very flexible and very low-level. Only for GUI builders. You can even create your own

Combining different layouts using JPanel Container contentor = janela.getcontentpane(); contentor.setlayout(new BorderLayout()); JPanel painel = new JPanel(); final String caracteresdosbotões= "789+456-123*0.^/"; JPanel paineldosbotões= new JPanel(); paineldosbotões.setlayout(new GridLayout(4, 4)); for(inti = 0; i!= caracteresdosbotões.length(); ++i) paineldosbotões.add(new JButton("" + caracteresdosbotões.charat(i))); painel.add(paineldosbotões); JPanel paineldasacções= new JPanel(); paineldasacções.setlayout(new GridLayout(2, 1)); paineldasacções.add(new JButton("C")); paineldasacções.add(new JButton("=")); If no layout is given, FlowLayout is used in JPanels painel.add(paineldasacções); contentor.add(painel, BorderLayout.CENTER);

JPanels painel paineldasacções paineldosbotões

JTextField Create and add to a Containeror to a JPanel: JTextField mostrador = new JTextField(); contentor.add(mostrador, BorderLayout.NORTH); Some operations: In order to use Font, do import java.awt.font; // Make the background white mostrador.setbackground(color.white); // Use a specific font Arial, regular, tamanho 14 mostrador.setfont(new Font("Arial", Font.PLAIN, 14)); // Right-align text mostrador.sethorizontalalignment(jtextfield.right); // Disable editing mostrador.seteditable(false);

JTextField mostrador

JTextField Getting the text in a text field: String texto = mostrador.gettext(); Setting the text in a text field mostrador.settext( 1 + 3 * 4 );

How do we make an application react when a button is pressed? Event-based programming Whenever an event occurs, a specific piece of code is execute Events: Mouse button pressed Mouse is moved Key is pressed Timers Fonte: Programação Concorrente e Distribuída DCTI

Fonte: Programação Concorrente e Distribuída D Events A signal sent to a program A program can choose to react or ignore All events inherit from EventObject Events have a source the object that generated the event. The source of an event can be determined by calling the following method on the event: Object getsource()

Actions, objects and events Edit text Action Press a button Press ENTER in a text field Select an item Select an item Select an item Manipulate a window Object JButton JTextComponent JTextField JComboBox JList JMenuItem Window TextEvent Event ActionEvent ActionEvent ItemEvent, ActionEvent ListSelectionEvent ActionEvent WindowEvent Fonte: Programação Concorrente e Distribuída DCTI

Fonte: Programação Concorrente e Distribuída DCTI Subscription, listening and handling An external action causes an event to be generated Example: a button is pressed Objects that have subscribed to the event receive the event We say that objects are listening for events Objects that can generate events maintain a list of event subscribers Whenever an event occurs, the event generating object goes through the list of subscribers and calls a method on each subscriber that allows the subscriber to handle the event.

Fonte: Programação Concorrente e Distribuída DCTI Events and Listener: an object that can subscribe to events. listeners Event Listener Method called ActionEvent ItemEvent WindowEvent TextEvent ListSelectionEvent ActionListener ItemListener WindowListener TextListener ListSelectionListener actionperformed() itemstatechanged() windowclosing() windowopened() windowiconified() windowdeiconified() windowclosed() textvaluechanged() valuechanged()

Fonte: Programação Concorrente e Distribuída DCTI Libraries Events and Listeners are defined in the AWT library in the event package: import java.awt.event.actionevent; import java.awt.event.actionlistener; Except: javax.swing.event.listselectionevent javax.swing.event.listselectionlistener

Fonte: Programação Concorrente e Distribuída D Defining a listener Listener: possibly an internal class. The listener is an interface! private class SentinelaParaAcções implements ActionListener { public void actionperformed(actionevent e) { if(e.getsource() == botãook) { System.out.println( Carregou no botão OK. ); else if(e.getsource() == botãocancel) { System.out.println( Carregou no botão Cancel. ); getsource() returns a reference to the object that sent the event. Handler: method that handles an event.

Fonte: Programação Concorrente e Distribuída D Subscribing to events public class Botões { public Botões() { Container contentor = janela.getcontentpane(); contentor.setlayout(new FlowLayout()); contentor.add(botãook); contentor.add(botãocancel); // Regista sentinelas: botãook.addactionlistener(sentinela); botãocancel.addactionlistener(sentinela); janela.setsize(100, 100); janela.setlocation(200, 100); janela.setdefaultcloseoperation(jframe.exit_on_close); (continues)

Fonte: Programação Concorrente e Distribuída D The listener (continuação) public void executa() { janela.setvisible(true); Should be private in most cases private JFrame janela = new JFrame("Eventos"); private JButton botãook = new JButton("OK"); private JButton botãocancel = new JButton("Cancel"); private SentinelaParaAcções sentinela = new SentinelaParaAcções(); private class SentinelaParaAcções implements ActionListener { public void actionperformed(actionevent e) { JButton botão=(jbutton)e.getsource(); if (botão==botãook ) {... else {... public static void main(string[] argumentos) { Botões b = new Botões(); b.executa();

Example Fonte: Programação Concorrente e Distribuída D

Fonte: Programação Concorrente e Distribuída D Example The method actionperformed() was called on the listener Carregou no botão OK.

Fonte: Programação Concorrente e Distribuída D Example The method actionperformed() was called on the listener Carregou no botão OK. Carregou no botão Cancel.

Fonte: Programação Concorrente e Distribuída D An example with lists javax.swing.jlist javax.swing.jscrollpane javax.swing.listselectionmodel javax.swing.event.listselectionevent javax.swing.event.listselectionlistener

Fonte: Programação Concorrente e Distribuída D Adding the list and setting up the window public class Listador { public Listador() { janela.getcontentpane().add(new JScrollPane(lista)); lista.setselectionmode(listselectionmodel.single_selection); lista.setselectedindex(0); lista.addlistselectionlistener(sentinela); janela.setsize(100, 200); janela.setlocation(200, 100); janela.setdefaultcloseoperation(jframe.exit_on_close); (continues) public void executa() { janela.setvisible(true);

Fonte: Programação Concorrente e Distribuída D List, items and the listener (continuation) private static final String[] nomesdoitens = { "zero", "um", "dois", "três", "quatro" ; (continues) private int índicedoitemseleccionado = 0; private JFrame janela = new JFrame("Listas"); private JList lista = new JList(nomesDoItens); private SentilenaParaALista sentinela = new SentilenaParaALista();

Fonte: Programação Concorrente e Distribuída D Handling events (continued) private class SentilenaParaALista implements ListSelectionListener { public void valuechanged(listselectionevent e) { if(índicedoitemseleccionado!= lista.getselectedindex()) { System.out.println(lista.getSelectedIndex() + " --> " + lista.getselectedvalue()); índicedoitemseleccionado = lista.getselectedindex(); (continues)

Fonte: Programação Concorrente e Distribuída D The main (continuation) public static void main(string[] argumentos) { Listador l = new Listador(); l.executa();

Fonte: Programação Concorrente e Distribuída D Example 1 --> um

Fonte: Programação Concorrente e Distribuída D Example 1 --> um 2 --> dois

1 --> um 2 --> dois 4 --> quatro Example

Notes For more on creating user interfaces with Swing, see: http://java.sun.com/docs/books/tutorial/uiswing/index.html There are more than 250 classes : It is impossible to remember all of them, so it is essential that you understand the basic principles and then learn to find the specific information you need in order to create the GUI.

Summary GUIs Event-based programming Events Actions Source objects Different types of events Subscription, listening and handling events Listeners Methods for handing events Examples