Inner Classes Ancora eventi. 2 Design considerations The most important rule to keep in mind about event listeners that they should execute very quickly.

Slides:



Advertisements
Similar presentations
Chapter 14 Advanced GUI ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Advertisements

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.
G5BUID - Java Swing Laying out components Manage realized components Determine size and position Each container has a layout manager (usually)
Custom Painting Gestione della Grafica customizzata Vedi anche:
Fondamenti di Java Introduzione alla costruzione di GUI (graphic user interface)
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.
Sezione: Upcast - downcast Upcast & downcast. Coercion Una funzione può essere polimorfa senza essere stata disegnata tale intenzionalmente. Sia f una.
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.
User Interfaces II GUI – Awt, Swing, Web
Rectangles moving and responding to the mouse. We want a window with a pile of rectangles in it When we click a rectangle it changes from filled to unfilled.
Java GUI building with the AWT. AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
GUI. Swing Programs Four basic types of Top Level Window – JFrame, a top level window decorated like a native window – JWindow, an undecorated stand-alone.
Graphical User Interfaces
Made with love, by Zachary Langley Applets The Graphics Presentation.
Web Design & Development Lecture 19. Java Graphics 2.
Programming in Java; Instructor:John Punin Graphics and Graphical User Interfaces1 Programming in Java Graphics and Graphical User Interfaces.
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.
Graphical User Interfaces Java’s AWT and Swing APIs.
Graphical User Interfaces (Part IV)
Java Software Development Paradigm Lecture # 12. Basics of GUI.
Examples. // A simple Frame with Rectangle Inside import java.awt.*; import javax.swing.*; import java.awt.geom.*; // For Shapes class rectComponent extends.
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Mouse Listeners We continue our examination of GUIs by looking at how to interact with the mouse –Just as Java creates Events when the user interacts with.
CS18000: Problem Solving and Object-Oriented Programming.
Graphic User Interfaces Layout Managers Event Handling.
F27SB2 Programming Languages
Graphical User Interfaces, 2D Graphics & Game Programming.
Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
Bar Graph Design. Left-side/Right-side mechanical processing creative, abstract reasoning.
TCU CoSc Programming with Java Handling Events.
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.
Event Handling Events and Listeners Timers and Animation.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
GUI Event Handling Nithya Raman. What is an Event? GUI components communicate with the rest of the applications through events. The source of an event.
Events in Java Swing Chris North cs3724: HCI. Typical command line program Non-interactive Linear execution program: main() { code; }
Applets, AWTS CompSci 230 Software Construction.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Chapter 11 Java AWT Part I: Mouse Events (Optional) Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin,
Java GUIs and Graphics CNS Outline  Introduction  Events  Components  Layout managers  Drawing  Introduction  Events  Components  Layout.
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
Session 11 Border Layout, using Panels, Introduction to PinBallGame.
(c) University of Washington07b-1 CSC 143 Java Events, Event Handlers, and Threads Reading: Ch. 17.
7/3/00SEM107- © Kamin & ReddyClass 11 - Events - 1 Class 11 - Events r A couple of odds & ends m Component sizes  switch statement r Event types r Catching.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
MSc Workshop - © S. Kamin, U.Reddy Lect 4 - Events - 1 Lecture 4 – Event Handling r Painting r Event types r Catching different event types.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
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.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
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.
UID – Event Handling and Listeners Boriana Koleva
Week 6: Basic GUI Programming Concepts in Java Example: JFrameDemo.java container : a screen window/applet window/panel that groups and arranges components.
Object Oriented Programming.  Interface  Event Handling.
1 Layout Managers Layout managers –Provided for arranging GUI components –Provide basic layout capabilities –Processes layout details –Programmer can concentrate.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7-3 ( Book Chapter 14) GUI and Event-Driven Programming.
Event Handling and Listeners in SWING The practice of event handling.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Event Driven (Asynchronous) Programming. Event handling in Unity Subclass a class that contains event handling methods, and then override those methods.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
Events and Event Handling
GUI Event Handling Nithya Raman.
Fondamenti di Java Introduzione alla costruzione di GUI
Chapter 7-3 (Book Chapter 14)
Events, Event Handlers, and Threads
Border Layout, using Panels, Introduction to PinBallGame
Presentation transcript:

Inner Classes Ancora eventi

2 Design considerations The most important rule to keep in mind about event listeners that they should execute very quickly. Because all drawing and event- listening methods are executed in the same thread, a slow event- listener method can make the program seem unresponsive and slow to repaint itself. You might choose to implement separate classes for different kinds of event listeners. This can be an easy architecture to maintain, but many classes can also mean reduced performance. When designing your program, you might want to implement your event listeners in a class that is not public, but somewhere more hidden. A private implementation is a more secure implementation.

3 Low-Level Events and Semantic Events Events can be divided into two groups: low-level events and semantic events. Low-level events represent window-system occurrences or low-level input. Everything else is a semantic event. Examples of low-level events include mouse and key events both of which result directly from user input. Examples of semantic events include action and item events. Whenever possible, you should listen for semantic events rather than low-level events. That way, you can make your code as robust and portable as possible. For example, listening for action events on buttons, rather than mouse events, means that the button will react appropriately when the user tries to activate the button using a keyboard alternative or a look-and-feel-specific gesture.

4 Listeners/Adapters public class MyClass implements MouseListener {... someObject.addMouseListener(this);... /* Empty method definition. */ public void mousePressed(MouseEvent e) { } /* Empty method definition. */ public void mouseReleased(MouseEvent e) { } /* Empty method definition. */ public void mouseEntered(MouseEvent e) { } /* Empty method definition. */ public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) {...//Event listener implementation goes here... } }

5 Listeners/Adapters /* * An example of extending an adapter class instead of * directly implementing a listener interface. */ public class MyClass extends MouseAdapter {... someObject.addMouseListener(this);... public void mouseClicked(MouseEvent e) { //Event listener implementation goes here... } }

6 Inner classes //An example of using an inner class. public class MyClass extends JFrame {... someObject.addMouseListener( new MyAdapter());... class MyAdapter extends MouseAdapter { public void mouseClicked(MouseEvent e){...//Event listener implementation goes here... } }

7 Anonymous Inner classes //An example of using an inner class. public class MyClass extends JFrame {... someObject.addMouseListener( new MouseAdapter () { public void mouseClicked(MouseEvent e){...//Event listener implementation goes here... } ); … }

8 Inner classes An instance of InnerClass can exist only within an instance of EnclosingClass and it has direct access to the instance variables and methods of its enclosing instance.

9 Anonymous Inner classes //An example of using an inner class. public class MyClass extends JFrame {... someObject.addMouseListener( new MouseAdapter() { public void mouseClicked(MouseEvent e){...//Event listener implementation goes here... } } });... }

10 Listeners supported by all Swing components component listener Listens for changes in the component's size, position, or visibility. focus listener Listens for whether the component gained or lost the ability to receive keyboard input. key listener Listens for key presses; key events are fired only by the component that has the current keyboard focus. mouse listener Listens for mouse clicks and mouse movement into or out of the component's drawing area. mouse-motion listener Listens for changes in the cursor's position over the component. mouse-wheel listenermouse-wheel listener (introduced in 1.4) Listens for mouse wheel movement over the component.

11 Altri listeners action caret change document undoable edit item list selection window + Listeners speciali per componenti specifiche (treeNodeExpansion, ecc)

Layouts and Graphics

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

Layouts Gestione del Layout Vedi anche:

Layouts

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 MyWindow // 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); }

BorderLayout In YellowWindow cambio il metodo jbInit: private void jbInit() throws Exception { JPanel f=(JPanel)this.getContentPane(); JButton north, south, east, west, center; north = new JButton("North"); east = new JButton("East"); west = new JButton("West"); center = new JButton("Center"); south = new JButton("South"); f.setLayout(new BorderLayout(2, 2)); f.add(north, BorderLayout.NORTH); f.add(south, BorderLayout.SOUTH); f.add(east, BorderLayout.EAST); f.add(west, BorderLayout.WEST); f.add(center, BorderLayout.CENTER); this.setSize(300,300); }

FlowLayout In YellowWindow cambio il metodo jbInit: private void jbInit() throws Exception { JPanel f=(JPanel)this.getContentPane(); JButton one, two, three, four, five, six; one = new JButton("one"); two = new JButton("two"); three = new JButton("three"); four = new JButton("four"); five = new JButton("five"); six = new JButton("six"); f.setLayout(new FlowLayout()); f.add(one); f.add(six); f.add(five); // attenzione allordine! f.add(two); f.add(three); f.add(four); // aggiungo five per la seconda volta: - la prima viene eliminata ! f.add(five); this.setSize(300,300); }

BorderLayout In YellowWindow cambio il metodo jbInit: private void jbInit() throws Exception { JPanel f=(JPanel)this.getContentPane(); f.setLayout(new GridLayout(3,4)); JButton b[]=new JButton[10]; // VETTORE DI 10 BOTTON for (int k=0; k<10; k++){ b[k]=new JButton(); // Integer.toString(int a) traduce lintero a in una String b[k].setLabel(Integer.toString(k)); f.add(b[k]); } this.setSize(300,300); }

BorderLayout In YellowWindow cambio il metodo jbInit: private void jbInit() throws Exception{ JPanel f=(JPanel)this.getContentPane(); CardLayout cl=new CardLayout(); f.setLayout(cl); JPanel p[ ]=new JPanel[5]; Color c[ ]={Color.red,Color.orange,Color.green,Color.blue,Color.pink}; for (int k=0;k<5; k++){ p[k]=new JPanel(); p[k].setBackground(c[k]); f.add(Integer.toString(k),p[k]); // il primo parametro è una stringa con la quale riferirsi al componente aggiunto } this.setSize(300,300); this.setVisible(true); while (true) { // ciclo infinito try { Thread.sleep(800); // dormi per 500 millisecondi } catch (Exception e) { } cl.next(f); // richiama il prossimo componente }

Posizionamento assoluto: Null Layout It's possible to set the layout manager to null: no layout control. You might do this to position an object on the display at some absolute coordinates. This is almost never the right approach. Components might have different minimum sizes on different platforms, and your interface would not be very portable. import java.awt.*; public class Applicazione { public static void main(String s[]) {Applicazione a=new Applicazione()} Applicazione() { JFrame g= new JFrame ("Finestra controllata da BORDER Layout"); JPanel f=(JPanel)(g.getContentFrame(); f.setSize(200,200); // Dimensione della finestra f.setLocation(50,100); // Posizione della finestra JButton b=new JButton(("Push me"); f.setLayout(null); f.add(b); b.setSize(25,75); // Dimensiono il Bottone b.setLocation(10,100); // Posiziono il bottone nella finestra g.setVisible(true); }

Custom Painting Gestione della Grafica customizzata Vedi anche:

Metodi grafici di Graphics drawLine()Draws a line drawRect()Draws a rectangle fillRect()Draws a filled rectangle drawRoundRect()Draws a rounded-corner rectangle fillRoundRect()Draws a filled, rounded-corner rectangle draw3DRect()Draws a highlighted, 3D rectangle fill3DRect()Draws a filled, highlighted, 3D rectangle drawArc()Draws an arc fillArc()Draws a filled arc drawOval()Draws an oval fillOval()Draws a filled oval drawPolygon()Draws a polygon, connecting endpoints fillPolygon()Draws a filled polygon drawPolyline()Draws a line connecting a polygon's points

Il sistema di coordinate

import java.awt.*; import javax.swing.*; import java.awt.event.*; public class TestPattern { public static void main(String[] args) { new TestPattern(); } public TestPattern() { startGraphics(); } public void startGraphics();{ JFrame f = new JFrame("TestPattern"); f.setSize(300,300); f.setContentPane(new MyPanel()); f.setVisible(true); } Disegno Grafico

class MyPanel extends JPanel { int theta = 45; int delta = 90; public void paintComponent(Graphics g) { super.paintComponent(g); int width = getSize().width; int height = getSize().height; int hWidth = width / 2; int hHeight = height / 2; int x = (width - hWidth)/2; int y = (height - hHeight)/2; g.setColor(Color.black); g.fillRect(0, 0, size().width, size().height); int[] polyx = {0, width / 2, width, width / 2}; int[] polyy = {height / 2, 0, height / 2, height}; Polygon poly = new Polygon(polyx, polyy, 4); g.setColor(Color.yellow) g.fillPolygon(poly); g.setColor(Color.red); g.fillRect(x, y, hWidth, hHeight); g.setColor(Color.green); g.fillOval(x, y, hWidth, hHeight); g.setColor(Color.blue); g.fillArc(x, y, hWidth, hHeight, theta, delta); g.setColor(Color.white); g.drawLine(x, y, x + hWidth, x + hHeight); } Disegno Grafico

Animazione Click!

class MyPanel extends JPanel implements MouseListener{ int theta = 45; int delta = 90; public void paintComponent(Graphics g) {... } public void mouseClicked(MouseEvent e) { theta=theta-90; this.repaint(); } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} } MyPanel() {this.addMouseListener(this);} } Animazione Double buffering dietro le quinte!

Repainting NON SI CHIAMA MAI ESPLICITAMENTE LA paintComponent(Graphics g)! [ nè la paint(Graphics g) ] Si chiama sempre, solo la repaint() NON SI IMPLEMENTA MAI LA REPAINT! La repaint viene chiamata anche dal sistema quando lo ritiene opportuno (resize, unhide...)

class MyPanel extends JPanel implements MouseListener{ public void paintComponent(Graphics g) { super.paintComponent(g); int rval, gval, bval; for (int j = 30; j < (this.size().height -25); j += 30) for (int i = 5; i < (this.size().width -25); i+= 30) { rval = (int)Math.floor(Math.random() * 256); gval = (int)Math.floor(Math.random() * 256); bval = (int)Math.floor(Math.random() * 256); g.setColor(new Color(rval,gval,bval)); g.fillRect(i,j,25,25); g.setColor(Color.black); g.drawRect(i-1,j-1,25,25); }... } Colore Double buffering dietro le quinte!

Animazione Click! Resize!

Insets protected void paintComponent(Graphics g) {... Insets insets = getInsets(); int currentWidth = getWidth() - insets.left - insets.right; int currentHeight = getHeight() - insets.top - insets.bottom;... /* First painting occurs at (x,y), where x is at least insets.left, and y is at least insets.top. */... }

Come avviene il painting 1. background (if opaque) 2. custom painting (if any) 3. border (if any) 4. children (if any) paintComponent The main method for painting. By default, it first paints the background if the component is opaque. Then it performs any custom painting. paintBorder Tells the component's border (if any) to paint. Do not invoke or override this method. paintChildren Tells any components contained by this component to paint themselves. Do not invoke or override this method.

Regole When implementing custom painting code for a component, keep these rules in mind: Your custom painting code should be in a method with the signature protected void paintComponent(Graphics). To gain access to the power of the 2D graphics API, you can cast the Graphics parameter into a Graphics2D object.2D graphics API You can use a border to paint the outside edges of your component. Except when painting the background of the component, you should avoid painting over the border area of the component. You can determine this area using the getInsets method. Your component must honor the opaque property. If your component is opaque, it must paint its complete area using an opaque color or colors. If its opaque property is false, then you have the option of not painting over the entire component.

class MyPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); Font f = new Font("TimesRoman", Font.PLAIN, 18); FontMetrics fm = getFontMetrics(f); g.setFont(f); String s = "This is a plain font"; int xstart = (getSize().width – fm.stringWidth(s))/2; g.drawString(s, xstart, 25); Font fb = new Font("TimesRoman", Font.BOLD, 18); Font fi = new Font("TimesRoman", Font.ITALIC, 18); Font fbi=new Font("TimesRoman",Font.BOLD +Font.ITALIC, 18); g.setFont(fb); g.drawString("This is a bold font", 10, 50); g.setFont(fi); g.drawString("This is an italic font", 10, 75); g.setFont(fbi); g.drawString("This is a bold italic font", 10, 100); }... } Fonts