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



Similar documents
CS 335 Lecture 06 Java Programming GUI and Swing

Homework/Program #5 Solutions

5.17 GUI. Xiaoyi Jiang Informatik I Grundlagen der Programmierung

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Programming with Java GUI components

Cours de Java. Sciences-U Lyon. Java - Introduction Java - Fondamentaux Java Avancé.

Using A Frame for Output

GUI Event-Driven Programming

Tutorial Reference Manual. Java WireFusion 4.1

Swing. A Quick Tutorial on Programming Swing Applications

GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012

Advanced Network Programming Lab using Java. Angelos Stavrou

Principles of Software Construction: Objects, Design and Concurrency. GUIs with Swing. toad Spring 2013

Java is commonly used for deploying applications across a network. Compiled Java code

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


public class neurale extends JFrame implements NeuralNetListener {

Extending Desktop Applications to the Web

Essentials of the Java(TM) Programming Language, Part 1

How To Build A Swing Program In Java.Java.Netbeans.Netcode.Com (For Windows) (For Linux) (Java) (Javax) (Windows) (Powerpoint) (Netbeans) (Sun) (

Autoboxing/Autounboxing

core 2 Handling Mouse and Keyboard Events

GUI Components: Part 2

Graphical User Interfaces

Java GUI Programming. Building the GUI for the Microsoft Windows Calculator Lecture 2. Des Traynor 2005

file://c:\dokumente und Einstellungen\Marco Favorito\Desktop\ScanCmds.html

How Scala Improved Our Java

public class Craps extends JFrame implements ActionListener { final int WON = 0,LOST =1, CONTINUE = 2;

How To Write A Program For The Web In Java (Java)

Essentials of the Java Programming Language

Mouse Event Handling (cont.)

CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus

// Correntista. //Conta Corrente. package Banco; public class Correntista { String nome, sobrenome; int cpf;

@ - Internal # - Online TH PR OR TW TOTAL HOURS # @ 175

Syllabus for CS 134 Java Programming

1 Hour, Closed Notes, Browser open to Java API docs is OK

Karsten Lentzsch JGoodies SWING WITH STYLE

public class demo1swing extends JFrame implements ActionListener{

java.applet Reference

11. Applets, normal window applications, packaging and sharing your work

Assignment # 2: Design Patterns and GUIs

JiST Graphical User Interface Event Viewer. Mark Fong

Implementação. Interfaces Pessoa Máquina 2010/ Salvador Abreu baseado em material Alan Dix. Thursday, June 2, 2011

GUJARAT TECHNOLOGICAL UNIVERSITY, AHMEDABAD, GUJARAT COURSE CURRICULUM COURSE TITLE: ADVANCE JAVA PROGRAMMING (COURSE CODE: )

Callbacks. Callbacks Copyright 2007 by Ken Slonneger 1

AODA Mouse Pointer Visibility

Tutorial: Time Of Day Part 2 GUI Design in NetBeans

ipratico POS Quick Start Guide v. 1.0

Introduction to JavaFX. Tecniche di Programmazione A.A. 2012/2013

Developing GUI Applications: Architectural Patterns Revisited

Konzepte objektorientierter Programmierung

Computing Concepts with Java Essentials

The Basic Java Applet and JApplet

Software Design: Figures

Skills and Topics for TeenCoder: Java Programming

ITIL v3 - Overview. Claudio Tancini Marzo 2015 INTERNAL USE ONLY

TATJA: A Test Automation Tool for Java Applets

Nexawebホワイトペーパー. Developing with Nexaweb ~ Nexaweb to Improve Development Productivity and Maintainability

8Q PRQGR GL FRQWHQLWRUL $ ZRUOG RI HQFORVXUHV

JIDE Action Framework Developer Guide

An Overview of Java. overview-1

Creating Fill-able Forms using Acrobat 8.0: Part 1

Fundamentals of Java Programming

How To Use The Command Pattern In Java.Com (Programming) To Create A Program That Is Atomic And Is Not A Command Pattern (Programmer)

How to Develop Accessible Linux Applications

DHBW Karlsruhe, Vorlesung Programmieren, Remote Musterlösungen

Source code security testing

Analysis Of Source Lines Of Code(SLOC) Metric

Here's the code for our first Applet which will display 'I love Java' as a message in a Web page

Lecture VII JAVA SWING GUI TUTORIAL

ICOM 4015: Advanced Programming

Assignment No.3. /*-- Program for addition of two numbers using C++ --*/

Event processing in Java: what happens when you click?

JustClust User Manual

Nuovi domini di primo livello - Registra nuove estensioni con FabsWeb_HOST

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

C.S.E. Nodi Tipici Parametrizzati al /04/2015 Copyright (c) Castalia srl

Word basics. Before you begin. What you'll learn. Requirements. Estimated time to complete:

GRAPHICAL WORKFLOW DESIGN USING WORKFLOW MANAGER - BASICS

How to Convert an Application into an Applet.

Altas, Bajas y Modificaciones de Registros en tabla MYSQL

Using NetBeans IDE for Desktop Development. Geertjan Wielenga

Misurazione performance. Processing time. Performance. Throughput. Francesco Marchioni Mastertheboss.com Javaday IV Roma 30 gennaio 2010

Lab 1A. Create a simple Java application using JBuilder. Part 1: make the simplest Java application Hello World 1. Start Jbuilder. 2.

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

Click on various options: Publications by Wizard Publications by Design Blank Publication

Model-View-Controller (MVC) Design Pattern

ArchiCAD Tutorial Getting started. Dr. Benny Raphael Dept. of Building National University of Singapore (NUS)

TDD da un capo all altro. Matteo Vaccari (cc) Alcuni diritti riservati

CS506 Web Design and Development Solved Online Quiz No. 01

BCA 421- Java. Tilak Maharashtra University. Bachelor of Computer Applications (BCA) 1. The Genesis of Java

Tema: Encriptación por Transposición

method is never called because it is automatically called by the window manager. An example of overriding the paint() method in an Applet follows:

Advanced Presentation Features and Animation

Transcription:

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 Component Graphics posiziona Layout Container

awt component hierarchy Component Button Canvas Checkbox Choice TextComponent List Scrollbar Label TextArea TextField

awt container hierarchy Container Panel Window ScrollPanel Applet Frame Dialog FileDialog

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

Top Level Containers TUTORIAL: http://java.sun.com/docs/books/tutorial/uiswing/

General Purpose Containers

Special Purpose Containers

Basic Controls

Uneditable Information

More complex structures

Prima applicazione JFrame App YellowWindow

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 Event User clicks a button, presses Enter while typing in a text field, or chooses a menu item User closes a frame (main window) User presses a mouse button while the cursor is over a component User moves the mouse over a component Component becomes visible Component gets the keyboard focus Table or list selection changes Any property in a component changes such as the text on a label Listener Type ActionListener WindowListener MouseListener MouseMotionListener ComponentListener FocusListener ListSelectionListener 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 componentdefined 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 String getactioncommand() Returns the command string associated with this action. int getmodifiers() Returns the modifier keys held down during this action event. long getwhen() Returns the timestamp of when this event occurred. String paramstring() Returns a parameter string identifying this action event. Methods Inherited public Object getsource() Returns The object on which the Event initially occurred.

Seconda applicazione JPanel ActionListener JFrame ButtonPanel Painter 3 Button addactionlistener

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, l altro 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 un applicazione 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 1.4.2. "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.