Capítulo 4 Applets e Gráficos.

Slides:



Advertisements
Apresentações semelhantes
IFTO ESTRUTURA DE DADOS AULA 05 Prof. Manoel Campos da Silva Filho
Advertisements

Programação em Java Prof. Maurício Braga
Palestras, oficinas e outras atividades
Material pedagógico Multiplicar x 5 Clica!
Vamos contar D U De 10 até 69 Professor Vaz Nunes 1999 (Ovar-Portugal). Nenhuns direitos reservados, excepto para fins comerciais. Por favor, não coloque.
Engenharia Informática Programação I & Estruturas de Dados e Algoritmos 2001/ Capitulo 7 – Métodos avançados Capitulo 7 Métodos avançados.
Engenharia Informática Programação I & Estruturas de Dados e Algoritmos 2001/ Capítulo 2 Tipos de Dados.
Engenharia Informática Programação I & Estruturas de Dados e Algoritmos 2001/ Capitulo 3 – Introdução às classes Capitulo 3 Introdução às classes.
Capítulo 1 Introdução.
Introdução à Programação usando Processing Programação Gráfica 2D Estrutura de Seleção Exercício Estrutura de Seleção 2º Semestre 2009 > PUCPR > Design.
Introdução à Programação usando Processing Programação Gráfica 2D Animações Exercício Animações 14/10/09 Bruno C. de Paula 2º Semestre 2009 > PUCPR >
14/10/09 Uma animação possui: Início; Passo; Fim; 1.
Exercício do Tangram Tangram é um quebra-cabeças chinês no qual, usando 7 peças deve-se construir formas geométricas.
Windows Forms 2º Semestre 2010 > PUCPR > TPU Bruno C. de Paula.
Nome : Resolve estas operações começando no centro de cada espiral. Nos rectângulos põe o resultado de cada operação. Comprova se no final.
Programação orientada a objetos
Interação entre objetos
Copyright (c) 2003 by Valery Sklyarov and Iouliia Skliarova: DETUA, IEETA, Aveiro University, Portugal.
1 INQUÉRITOS PEDAGÓGICOS 2º Semestre 2003/2004 ANÁLISE GERAL DOS RESULTADOS OBTIDOS 1.Nº de RESPOSTAS ao inquérito 2003/2004 = (42,8%) 2.Comparação.
Sumário, aula 10 Exercícios sobre elasticidade Elasticidade e despesa
Ludwig Krippahl, 2007 Programação para as Ciências Experimentais 2006/7 Teórica 9.
Ludwig Krippahl, 2008 Programação para as Ciências Experimentais 2007/8 Teórica 11.
Orientação a Objetos: Encapsulamento e Classificação
Java: Pacotes e Modificadores de Visibilidade
Java: Pacotes e Modificadores de Visibilidade
Relações Adriano Joaquim de O Cruz ©2002 NCE/UFRJ
Arrays Profa. Isabel Harb Manssour (Material adaptado das aulas dos Profs.: Luciana Nedel, Júlio Machado e Bernardo Copstein) Arrays Exercícios.
Capítulo 15 Swing – Parte 1.
7 Abstração Genérica Unidades genéricas e instanciação.
Auditoria de Segurança da Informação
Capítulo 9 Herança 1.
Aula de reposição Prof. Grace e Ângela
Classes e objetos Arrays e Sobrecarga
Herança P. O. O. Prof. Ângela e Grace.
Classes e objetos P. O. O. Prof. Grace.
Introdução a Programação JAVA
Provas de Concursos Anteriores
1 APLICAÇÃO DA VISUALIZAÇÃO CIENTÍFICA À OCEANOGRAFIA Representação da agitação marítima no porto de Leixões Disciplina de Visualização Científica Mestrado.
© GfK 2012 | Title of presentation | DD. Month
Como aplicar leis da lógica
Criação de objetos da AD 1Luis Rodrigues e Claudia Luz.
Cinemática de uma Partícula Cap. 12
Resultantes de Sistemas de Forças Cap. 4
MECÂNICA - DINÂMICA Cinemática de uma Partícula Cap Exercícios.
Cinética Plana de uma Partícula: Força e Aceleração Cap. 13
Fundamentos de Engenharia de SW
Object Oriented Software Construction (MEYER, Bertrand)
1 António Arnaut Duarte. 2 Sumário: primeiros passos;primeiros passos formatar fundo;formatar fundo configurar apresentação;configurar apresentação animação.
GAPH Integração de Hardware do Usuário ao CoreConnect Leandro Heleno Möller e Leonel Pablo Tedesco Prototipação Rápida e Computação.
Salas de Matemática.
MINISTÉRIO DO PLANEJAMENTO Projeto de Lei Orçamentária 2011 Ministro Paulo Bernardo Silva Brasília, novembro de 2010.
MINISTÉRIO DO PLANEJAMENTO Projeto de Lei Orçamentária 2010 Ministro Paulo Bernardo Silva Brasília, 31 de agosto de 2009.
Coordenação Geral de Ensino da Faculdade
Principais operações em Listas TPA Listas Simples Inserção no Final 1.void insereNofinalDaLista(Lista *l, Elemento e){ 2.Lista paux,p; 3. p.
Programação Funcional
Interface Gráfica (material da Profa. Luciana Nedel - www. inf. pucrs
É u m e l e m e n t o f u n d a m e n t a l
EXERCÍCIOS PARA GUARDA-REDES
Programa Expresso de Capacitação Módulo J2ME Aula 4 – Interface de alto e baixo nível.
Java 2D Marco Antonio. Java2D Conjunto de classes para trabalhar com gráficos e imagens. A principal classe desta API é JComponent. Com esta classe é.
1 2 Observa ilustração. Cria um texto. Observa ilustração.
Grupo A – Azul Claro, Marrom, Laranja
CALENDÁRIO SEXY Ele & Ela. CALENDÁRIO SEXY Ele & Ela.
Rio Verde - Goiás - Brasil
FORMATANDO O TRABALHO NO WORD 2007
Cinemática Plana de um Corpo Rígido Cap. 16
Wagner Santos C. de Jesus
GINÁSTICA LABORAL UM NOVO CAMINHO.
Programação Gráfica em Java Desenho em AWT Aula 04.
Transcrição da apresentação:

Capítulo 4 Applets e Gráficos

Tipos de Programas em Java Aplicações em modo texto: Input do teclado Programação mais simples Aplicações em modo gráfico: Input do teclado ou rato Utiliza componentes gráficas como botões, menus, etc. Consegue mostrar gráficos

Applets Pode-se fazer download de um Servidores Web Executam dentro de um browser Independentes da plataforma (Windows, Mac, Linux, Solaris Necessitam do Java VM Problema de segurança: um applet é executado na máquina local

Esqueleto de um Applet public class MyApplet extends Applet { public void init() { // initializations go here . . . } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; // painting instructions go here . . . } }

Program RectangleApplet.java import java.applet.Applet; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; public class RectangleApplet extends Applet { public void paint(Graphics g) { // recover Graphics2D Graphics2D g2 = (Graphics2D)g; // construct a rectangle and draw it Rectangle cerealBox = new Rectangle(5, 10, 20, 30); g2.draw(cerealBox);

// move rectangle 15 units sideways and 25 units down cerealBox.translate(15, 25); // draw moved rectangle g2.draw(cerealBox); } } // End Class

Formas Gráficas Rectangle2D.Double Ellipse2D.Double Line2D.Double Point2D.Double Exemplo: Ellipse2D.Double egg = new Ellipse2D.Double(5,10,15,20); g2.draw(egg);

Sistema de Coordenadas de uma Elipse

Cores Construtor de cores: Color magenta = new Color(1.0F, 0.0F, 1.0F); Cores pré-definidas, ex. Color.red Definir uma cor no contexto gráfico: g2.setColor(magenta); Desenhar ou preencher: g2.draw(egg); g2.fill(egg);

Fontes (1) Características das fontes: Nome (ex. "Times Roman", "Helvetica") Estilo (plain, bold, italic, bold + italic) Tamanho (ex. 12) Font f = new Font("Serif", Font.BOLD, 36);

Fontes (2) Definir uma fonte no contexto gráfico: g2.setFont(f); Desenhar uma String: g2.drawString("Hello", 50, 100);

Medir o Texto Ascent = tamanho acima do baseline Descent = tamanho abaixo do baseline Exemplo: FontRenderContext context = g2.getFontRenderContext(); TextLayout layout = new TextLayout(“Applet, f, context); float height = layout.getAscent() + layout.getDescent(); float width = layout.getAdvance();

Medição do texto

Input de Texto Exemplo: String input = JOptionPane.showInputDialog (“Insert your age”); Conversão de uma String em número inteiro: int age = Integer.parseInt(input); Por agora, coloque estes comandos no método init de um applet

Exemplo de uma caixa de diálogo

Programas para as teóricas Capítulo 4 Programas para as teóricas

Program FontApplet.java import java.applet.Applet; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Font; import java.awt.font.FontRenderContext; import java.awt.font.TextLayout; public class FontApplet extends Applet { public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; // select the font into the graphics context final int HUGE_SIZE = 48; Font hugeFont = new Font("Serif", Font.BOLD, HUGE_SIZE); g2.setFont(hugeFont); String message ="Applet";

// create a text layout to measure the string FontRenderContext context = g2.getFontRenderContext(); TextLayout layout = new TextLayout(message, hugeFont, context); // measure the message width and height float xMessageWidth = layout.getAdvance(); float yMessageHeight = layout.getAscent() + layout.getDescent(); // center the message in the window float xLeft = 0.5F * (getWidth()- xMessageWidth); float yTop = 0.5F * (getHeight()- yMessageHeight); float yBase = yTop + layout.getAscent(); g2.drawString(message, xLeft, yBase); } } // End Class

Output do Programa FontApplet.java

Program CarDrawer.java import java.applet.Applet; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; public class CarDrawer extends Applet { public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; Rectangle body = new Rectangle(100, 110, 60, 10); Ellipse2D.Double frontTire = new Ellipse2D.Double(110, 120, 10, 10); Ellipse2D.Double rearTire = new Ellipse2D.Double(140, 120, 10, 10);

Point2D.Double r1 = new Point2D.Double(110, 110); // the bottom of the front windshield Point2D.Double r2 = new Point2D.Double(120, 100); // the front of the roof Point2D.Double r3 = new Point2D.Double(140, 100); // the rear of the roof Point2D.Double r4 = new Point2D.Double(150, 110); // the bottom of the rear windshield Line2D.Double frontWindshield = new Line2D.Double(r1, r2); Line2D.Double roofTop = new Line2D.Double(r2, r3); Line2D.Double rearWindshield = new Line2D.Double(r3, r4);

g2.draw(body); g2.draw(frontTire); g2.draw(rearTire); g2.draw(frontWindshield); g2.draw(roofTop); g2.draw(rearWindshield); g2.drawString("JavaMobile 1.2ti", 100, 150); } } // End Class

Output do Programa CarDrower.java

Program ColorSelect.java import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.JOptionPane; public class ColorSelect extends Applet { public void init() { String input; // ask the user for red, green, blue values input = JOptionPane.showInputDialog("red:"); float red = Float.parseFloat(input); input = JOptionPane.showInputDialog("green:"); float green = Float.parseFloat(input); input = JOptionPane.showInputDialog("blue:"); float blue = Float.parseFloat(input); fillColor_ = new Color(red,green,blue); }

public void paint(Graphics g) { final int SQUARE_LENGTH = 100; Graphics2D g2 = (Graphics2D)g; // select color into graphics context g2.setColor(fillColor_); // construct and fill a square whose center is // the center of the window Rectangle square = new Rectangle( (getWidth() - SQUARE_LENGTH) / 2, (getHeight() - SQUARE_LENGTH) / 2, SQUARE_LENGTH, SQUARE_LENGTH); g2.fill(square); } private Color fillColor_; } // End Class

Program Phoenix.java //Class UnitConverter import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.RectangularShape; public class UnitConverter { public UnitConverter(double x1, double x2, double y1, double y2, double w, double h) { xleft_ = x1; xright_ = x2; ybottom_ = y1; ytop_ = y2; width_ = w; height_ = h; }

public Point2D convert(Point2D p) { double x = xToPixel(p.getX()); double y = yToPixel(p.getY()); p.setLocation(x, y); return p; } public Line2D convert(Line2D l) double x1 = xToPixel(l.getX1()); double y1 = yToPixel(l.getY1()); double x2 = xToPixel(l.getX2()); double y2 = yToPixel(l.getY2()); l.setLine(x1, y1, x2, y2); return l;

public RectangularShape convert(RectangularShape r) { double xmin = xToPixel(r.getMinX()); double ymin = yToPixel(r.getMinY()); double xmax = xToPixel(r.getMaxX()); double ymax = yToPixel(r.getMaxY()); r.setFrameFromDiagonal(xmin, ymin, xmax, ymax); return r; } public double xToPixel(double x) return (x – xleft_) * (width_ - 1) / (xright_ - xleft_); public double yToPixel(double y) return (y – ytop_) * (height_ - 1) / (ybottom_ - ytop_);

public double pixelToX(double px) { return xleft_ + px * (xright_ - xleft_) / (width_ - 1); } public double pixelToY(double py) return ytop_ + py * (ybottom_ - ytop_) / (height_ - 1); private double xleft_; private double xright_; private double ytop_; private double ybottom_; private double width_; private double height_;

Program Phoenix.java //Class Phoenix import java.applet.Applet; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; public class Phoenix extends Applet { public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; month_ = 0; units_ = new UnitConverter(0, 12, 0, 40, getWidth(), getHeight()); final int JAN_TEMP = 11; final int FEB_TEMP = 13; final int MAR_TEMP = 16; final int APR_TEMP = 20; final int MAY_TEMP = 25; final int JUN_TEMP = 31; final int JUL_TEMP = 33; final int AUG_TEMP = 32; final int SEP_TEMP = 29;

final int OCT_TEMP = 23; final int NOV_TEMP = 16; final int DEC_TEMP = 12; drawBar(g2, JAN_TEMP); drawBar(g2, FEB_TEMP); drawBar(g2, MAR_TEMP); drawBar(g2, APR_TEMP); drawBar(g2, MAY_TEMP); drawBar(g2, JUN_TEMP); drawBar(g2, JUL_TEMP); drawBar(g2, AUG_TEMP); drawBar(g2, SEP_TEMP); drawBar(g2, OCT_TEMP); drawBar(g2, NOV_TEMP); drawBar(g2, DEC_TEMP); }

public void drawBar(Graphics2D g2, int temperature) { // construct rectangle for this month and temperature Rectangle rect = new Rectangle(month_, 0, 1, temperature); // convert to pixel coordinates and draw units_.convert(rect); g2.draw(rect); month_ ++; } private int month_; private UnitConverter units_; } // End Class

Output do Programa Phoenix.java