Fondamenti di Java Introduzione alla costruzione di GUI (graphic user interface)

Slides:



Advertisements
Similar presentations
Event handling and listeners What is an event? user actions and context event sources and listeners Why should my programs be event- driven? User interaction.
Advertisements

Chapter 18 Building the user interface. This chapter discusses n Javas graphical user interface. n Swing: an enhancement of a library called the Abstract.
Layouts and Graphics. component - container - layout Un Container contiene [0 o +] Components Il Layout specifica come i Components sono disposti nel.
1 Event Listeners Some Events and Their Associated Event Listeners Act that Results in the EventListener Type User clicks a button, presses Enter while.
Inner Classes Ancora eventi. 2 Design considerations The most important rule to keep in mind about event listeners that they should execute very quickly.
Handling Mouse Events Event-Driven Programming Approccio standard per programmare GUI In contrapposizione al polling offre: - Maggiore flessibilità - Minor.
1 Graphical User Interface (GUI) Applications Abstract Windowing Toolkit (AWT) Events Handling Applets.
Introduction to Java 2 Programming
Chapter 16 GUI Programming Basics GUI Overview Event-Driven Programming Basics GUI Classes and Packages A Simple Window Program JFrame Class Java Components.
15 Copyright © 2005, Oracle. All rights reserved. Adding User Interface Components and Event Handling.
OLD BUSINESS : Lets talk about the next exam Project proposals – Functional Definitions Go over homework – NEW BUSINESS: Chapter 4 today GUIs Assignment.
1 Graphical User Interfaces AWT and Swing packages Frames and Panels Components Nested Panels Images Reading for this Lecture: L&L, 3.9 – 3.11.
1 cs205: engineering software university of virginia fall 2006 Wimpy Interfaces.
Web Design & Development Lecture 19. Java Graphics 2.
CSE 1341 Honors Professor Mark Fontenot Southern Methodist University Note Set 21.
Graphics and event-driven programs Learning objectives By the end of this lecture you should be able to: identify and use some of the common components.
Basic Java – Interface design. Understand: How to use TextPad for Java How to define classes and objects How to create a GUI interface How event-driven.
Graphical User Interfaces Java’s AWT and Swing APIs.
Graphical User Interfaces (Part IV)
Examples. // A simple Frame with Rectangle Inside import java.awt.*; import javax.swing.*; import java.awt.geom.*; // For Shapes class rectComponent extends.
CS18000: Problem Solving and Object-Oriented Programming.
Unit 3 Graphical User Interface (GUI) Dr. Magdi AMER.
Graphic User Interfaces Layout Managers Event Handling.
F27SB2 Programming Languages
Problem Solving 6 GUIs and Event Handling ICS-201 Introduction to Computing II Semester 071.
Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
Chapter 5 Programming Graphics. Chapter Goals To be able to write applications with simple graphical user interfaces To display graphical shapes such.
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.
Java Applets- Using SwingWorker Dave Price and Chris Loftus Computer Science Department University of Wales, Aberystwyth.
Things to mention public static void main(String [] args) –The starting point for a free-standing Java application (i.e. one not run from the DrJava interactions.
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Event Handling Events and Listeners Timers and Animation.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
Chapter 8: Graphical User Interfaces Objectives - by the end of this chapter, you should be able to do the following: –write a simple graphical user interface.
ACM/JETT Workshop - August 4-5, ExceptionHandling and User Interfaces (Event Delegation, Inner classes) using Swing.
Intro to Java 2 By Geb Thomas Based on the Java TutorialJava Tutorial.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
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.
Java GUI CSCE 190 – Java Instructor: Joel Gompert Mon, July 26, 2004.
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,
Dale Roberts GUI Programming using Java - Event Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
Graphical User Interface Components: Part 1 Chapter 11.
– 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.
GUI Clients 1 Enterprise Applications CE00465-M Clients with Graphical User Interfaces.
Chapter 12 1 TOPIC 13B l Buttons and Action Listeners Window Interfaces Using Swing Objects.
UID – Event Handling and Listeners Boriana Koleva
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Anonymous Classes An anonymous class is a local class that does not have a name. An anonymous class allows an object to be created using an expression.
Object Oriented Programming.  Interface  Event Handling.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event.
Mouse Events GUI. Types of Events  Below, are some of the many kinds of events, swing components generate. Act causing EventListener Type User clicks.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Lesson 28: More on the GUI button, frame and actions.
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.
Event Driven (Asynchronous) Programming. Event handling in Unity Subclass a class that contains event handling methods, and then override those methods.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
GUI Programming using Java - Event Handling
CSC 205 Programming II Lecture 5 AWT - I.
A First Look at GUI Applications
Advanced User Interfaces
Graphical User Interface (pronounced "gooey")
CSE 114 – Computer Science I Event Programming
Event-driven programming for GUI
Fondamenti di Java Introduzione alla costruzione di GUI
Presentation transcript:

Fondamenti di Java Introduzione alla costruzione di GUI (graphic user interface)

component - container - layout Un Container contiene [0 o +] Components Il Layout specifica come i Components sono disposti nel Container Un Container è un Component (quindi il contenimento è ricorsivo) Un Component ha una Graphics associata

awt component hierarchy

awt container hierarchy

javax.swing java.awt Swing component hierarchy Container JComponent Swing containers JPanel Swing components JButton Component

Top Level Containers TUTORIAL:

General Purpose Containers

Special Purpose Containers

Basic Controls

Uneditable Information

More complex structures

Prima applicazione AppYellowWindow JFrame

class YellowWindow package it.unitn.science.prog2.guiApp; import java.awt.*; import javax.swing.*; public class YellowWindow extends JFrame { private JPanel contentPane; public YellowWindow() { try { jbInit(); } catch(Exception e) { e.printStackTrace(); } } private void jbInit() throws Exception { contentPane=(JPanel)this.getContentPane(); this.setSize(new Dimension(400, 300)); contentPane.setBackground(Color.YELLOW); }

class App package it.unitn.science.prog2.guiApp; import javax.swing.*; import java.awt.*; public class App { JFrame finestra=null; public static void main(String[ ] a){ new App(); } public App() { // aggiungere qui: set look&feel (vedi oltre) this.setupGraphicEnvironment(); }

class App private void setupGraphicEnvironment() { finestra = new YellowWindow(); //new CalculatorWindow // trova le dimensioni dello schermo e della finestra Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = finestra.getSize(); // assicurati che la finestra non sia più grande dello schermo if (frameSize.height > screenSize.height) frameSize.height = screenSize.height; if (frameSize.width > screenSize.width) frameSize.width = screenSize.width;

class App // centra la finestra nello schermo finestra.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2); // fai in modo che la chiusura della finestra // termini l'applicazione finestra.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE ); // rendi la finestra visibile finestra.setVisible(true); }

18 Event Listeners Some Events and Their Associated Event Listeners Act that Results in the EventListener Type User clicks a button, presses Enter while typing in a text field, or chooses a menu item ActionListener User closes a frame (main window) WindowListener User presses a mouse button while the cursor is over a component MouseListener User moves the mouse over a component MouseMotionListener Component becomes visible ComponentListener Component gets the keyboard focus FocusListener Table or list selection changes ListSelectionListener Any property in a component changes such as the text on a label PropertyChangeListener

19 ActionListener public interface ActionListener extends EventListener The listener interface for receiving action events. The class that is interested in processing an action event implements this interface, and the object created with that class is registered with a component, using the component's addActionListener method. void actionPerformed(ActionEvent e) Invoked when an action occurs

20 ActionEvent ActionEvent extends AWTEvent A semantic event which indicates that a component- defined action occured. This high-level event is generated by a component (such as a Button) when the component-specific action occurs (such as being pressed). The event is passed to every every ActionListener object that registered to receive such events using the component's addActionListener method.

21 ActionEvent Method Summary StringString getActionCommand() Returns the command string associated with this action. getActionCommand int getModifiers() Returns the modifier keys held down during this action event. getModifiers long getWhen() Returns the timestamp of when this event occurred. getWhen StringString paramString() Returns a parameter string identifying this action event. paramString Methods Inherited … public Object getSource()Object Returns The object on which the Event initially occurred.

Seconda applicazione ButtonPanel Painter JFrame ActionListenerJPanel Button addActionListener 3

23 Esempio package actionlistener; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.JFrame; public class ButtonPanel extends JPanel { public ButtonPanel() { super(); JButton button1 = new JButton("Giallo"); JButton button2 = new JButton("Verde"); JButton button3 = new JButton("Rosso"); this.add(button1); this.add(button2); this.add(button3); Painter azioneGiallo = new Painter(Color.YELLOW,this); Painter azioneVerde = new Painter( Color.GREEN,this); Painter azioneRosso = new Painter(Color.RED,this); button1.addActionListener(azioneGiallo); button2.addActionListener(azioneVerde); button3.addActionListener(azioneRosso); }

24 Esempio - continua public static void main(String a[]) { JFrame f=new JFrame(); f.setContentPane(new ButtonPanel()); f.setSize(300,300); f.setVisible(true); } } class Painter implements ActionListener { private Color colore; private JPanel contenitore; public Painter(Color colore, JPanel contenitore) { this.colore = colore; this.contenitore=contenitore; } public void actionPerformed(ActionEvent actionEvent) { contenitore.setBackground(colore); }

25 Esempio 2 public class ButtonPanel extends JPanel { public ButtonPanel() { super(); Painter p=new Painter(this); String c[]={"Giallo","Verde","Rosso"}; for (int i=0;i<c.length;i++) { JButton b=new JButton(c[i]); this.add(b); b.addActionListener(p); // b.setActionCommand(c[i]); } public static void main(String a[]) { JFrame f=new JFrame(); f.setContentPane(new ButtonPanel()); f.setSize(300,300); f.setVisible(true); }

26 Esempio 2 - continua class Painter implements ActionListener { private JPanel contenitore; private Color colore; public Painter(JPanel contenitore) { this.contenitore=contenitore; } public void actionPerformed(ActionEvent actionEvent) { String s=((JButton)actionEvent.getSource()).getText(); //String s=actionEvent.getActionCommand(); if (s.equals("Giallo")) colore=Color.YELLOW; else if (s.equals("Rosso")) colore=Color.RED; else if (s.equals("Verde")) colore=Color.GREEN; contenitore.setBackground(colore); }

27 Esempio 3 public class ButtonPanel extends JPanel { public ButtonPanel() { super(); Painter p=new Painter(this); this.setLayout(null); String c[]={"Giallo","Verde","Rosso"}; for (int i=0;i<c.length;i++) { JButton b=new JButton(c[i]); b.setSize(100,50); b.setLocation(i*100,i*50); this.add(b); b.addActionListener(p); b.setActionCommand(c[i]); } NON CONSIGLIATO – LAYOUT NON LIQUIDO!

28 Compito Scrivere un applicazione contenente un bottone che quando viene premuto si sposta altrove nella finestra. Scrivere una applicazione contenente due bottoni: uno ingrandisce la dimensione della finestra, laltro la rimpicciolisce

29 Mouse events This low-level event is generated by a component object for: Mouse Events a mouse button is pressed a mouse button is released a mouse button is clicked (pressed and released) the mouse cursor enters the unobscured part of component's geometry the mouse cursor exits the unobscured part of component's geometry Mouse Motion Events the mouse is moved the mouse is dragged

30 Compito Scrivere un applicazione contenente un TextField il cui valore inizialmente è zero, e che viene incrementato di uno ogni volta che il bottone del mouse viene cliccato. Scrivere unapplicazione contenente un bottone che si posiziona dove viene cliccato il bottone del mouse. Se invece viene cliccato il bottone grafico, questo si riposiziona nella sua sede iniziale.

Pluggable Look&Feel

Scelta del Look&Feel public static void main(String[] args) { try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { } new SwingApplication(); //Create and show the GUI. } UIManager.getCrossPlatformLookAndFeelClassName() Returns the Java look and feel. UIManager.getSystemLookAndFeelClassName() Specifies the look and feel for the current platform.

Scelta del Look&Feel public static void main(String[] args) { try { UIManager.setLookAndFeel( "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); } catch (Exception e) { } new SwingApplication(); //Create and show the GUI. } UIManager.getSystemLookAndFeelClassName(String s) Specifies the look and feel for the platform described by s.

Available Look&Feel "com.sun.java.swing.plaf.gtk.GTKLookAndFeel" Specifies the GTK+ look and feel. Introduced in release "javax.swing.plaf.metal.MetalLookAndFeel" Specifies the Java look and feel. "com.sun.java.swing.plaf.windows.WindowsLookAndFeel" Specifies the Windows look and feel. Currently, you can use this look and feel only on Microsoft Windows systems. "com.sun.java.swing.plaf.motif.MotifLookAndFeel" Specifies the CDE/Motif look and feel. This look and feel can be used on any platform.