apostila lobianco

73
JAVA - AULA 1 Como Java funciona Primeiro programa em Java (Welcome1.java) public class Welcome1 { // o método principal inicia a execução do aplicativo Java public static void main(String args[]) { System.out.print("Programação "); // não pula linha System.out.println("Java!"); // pula linha ao terminar impressão } // fim do método principal } // fim da classe Welcome1 Utilizando printf (Welcome2.java) public class Welcome2 { public static void main(String args[]) { System.out.printf("%s\n%s\n", "Programação", "Java!"); } }

Upload: luciano-alves-machado

Post on 26-Dec-2014

97 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Apostila Lobianco

JAVA - AULA 1Como Java funciona

Primeiro programa em Java (Welcome1.java)

public class Welcome1{ // o método principal inicia a execução do aplicativo Java public static void main(String args[]) { System.out.print("Programação "); // não pula linha System.out.println("Java!"); // pula linha ao terminar impressão } // fim do método principal} // fim da classe Welcome1

Utilizando printf (Welcome2.java)

public class Welcome2{ public static void main(String args[]) { System.out.printf("%s\n%s\n", "Programação", "Java!"); }}

Page 2: Apostila Lobianco

Adicionando inteiros (Addition.java)

import java.util.Scanner;

public class Addition{ public static void main(String args[]) { Scanner input = new Scanner(System.in);

int number1; // primeiro número a somar int number2; // segundo número a somar int sum; // soma de number1 e number2

System.out.print("Digite o primeiro número: "); number1 = input.nextInt(); System.out.print("Digite o segundo número: "); number2 = input.nextInt();

sum = number1 + number2;

System.out.printf("A soma é %s\n", sum); }}

Operadores relacionais (Comparison.java)

import java.util.Scanner;

public class Comparison{ public static void main( String args[] ) { Scanner input = new Scanner(System.in);

int number1; // primeiro número a comparar int number2; // segundo número a comparar

System.out.print("Digite o primeiro número: "); number1 = input.nextInt(); System.out.print("Digite o segundo número: "); number2 = input.nextInt();

if ( number1 == number2 ) System.out.printf("%s == %s\n", number1, number2); if ( number1 != number2 ) System.out.printf("%s != %s\n", number1, number2); if ( number1 < number2 ) System.out.printf("%s < %s\n", number1, number2); if ( number1 > number2 ) System.out.printf("%s > %s\n", number1, number2); }}

Page 3: Apostila Lobianco

JAVA - AULA 2

Declarando uma classe... (GradeBook1.java)

public class GradeBook1{ public void displayMessage() { System.out.println( "Benvindos ao curso!"); }}

...e chamando seu método (GradeBookTest1. java)

public class GradeBookTest1{ public static void main( String args[] ) { GradeBook1 myGradeBook = new GradeBook1();

myGradeBook.displayMessage(); }}

Declarando um método com parâmetro... (GradeBook2.java)

public class GradeBook2{ public void displayMessage(String CourseName) { System.out.printf( "Benvindos ao curso %s!\n", CourseName); }}

...e chamando seu método (GradeBookTest2. java)

import java.util.Scanner;

public class GradeBookTest2{ public static void main( String args[] ) { Scanner input = new Scanner(System.in);

GradeBook2 myGradeBook = new GradeBook2();

System.out.print("Digite o nome do curso: "); String CourseName = input.nextLine(); System.out.println("");

myGradeBook.displayMessage(CourseName); }}

Page 4: Apostila Lobianco

Variáveis de instância, construtor, métodos set e get (GradeBook3.java)

public class GradeBook3{ private String CourseName;

public GradeBook3(String name) { CourseName = name; }

public void setCourseName(String name) { CourseName = name; }

public String getCourseName() { return CourseName; }

public void displayMessage() { System.out.printf( "Benvindos ao curso %s!\n", getCourseName()); }}

...e chamando seu método (GradeBookTest3. java)

public class GradeBookTest3{ public static void main( String args[] ) { GradeBook3 gradeBook1 = new GradeBook3("Programacao Java Basica"); GradeBook3 gradeBook2 = new GradeBook3("Materia sem nome");

System.out.printf("Curso 1: %s", gradeBook1.getCourseName() ); System.out.println(""); gradeBook2.setCourseName("Programacao Java Avancada"); System.out.printf("Curso 2: %s", gradeBook2.getCourseName() ); System.out.println(""); }}

Page 5: Apostila Lobianco

Classe para tratar números reais (Account.java)

public class Account{ private double balance;

public Account( double initialBalance ) { if ( initialBalance > 0.0 ) balance = initialBalance; }

public void credit( double amount ) { balance = balance + amount; }

public double getBalance() { return balance; }}

Entrada e saída com números reais (AccountTest.java)

import java.util.Scanner;

public class AccountTest{ public static void main( String args[] ) { Account account1 = new Account( 50.00 ); Account account2 = new Account( -7.53 );

System.out.printf( "Saldo da conta 1: $%.2f\n", account1.getBalance() ); System.out.printf( "Saldo da conta 2: $%.2f\n", account2.getBalance() ); Scanner input = new Scanner( System.in ); double depositAmount;

System.out.print( "Digite depósito para conta 1: " ); depositAmount = input.nextDouble(); System.out.printf( "\nAdicionando %.2f ao saldo da conta 1\n\n", depositAmount ); account1.credit( depositAmount );

System.out.printf( "Saldo da conta 1: $%.2f\n", account1.getBalance() ); System.out.printf( "Saldo da conta 2: $%.2f\n", account2.getBalance() ); }}

Page 6: Apostila Lobianco

JAVA - AULA 3

Utilizando if..else...

if (grade >= 60){ System.out.println(" Aprovado ");}else{ System.out.println(" Reprovado ");}

...ou operador condicional

System.out.println( (grade >= 60) ? " Aprovado " : " Reprovado " );

Utilizando while (GradeBook1.java)

import java.util.Scanner;

public class GradeBook1{ private String courseName;

public GradeBook1( String name ) { courseName = name; } public void setCourseName( String name ) { courseName = name; }

public String getCourseName() { return courseName; }

public void displayMessage() { System.out.printf( "Bem-vindo ao curso\n%s!\n\n", getCourseName()); }

public void determineClassAverage() { Scanner input = new Scanner( System.in );

int total; int gradeCounter; int grade; int average;

total = 0; gradeCounter = 1;

Page 7: Apostila Lobianco

while ( gradeCounter <= 10 ) { System.out.print( "Entre com a nota: " ); grade = input.nextInt(); total = total + grade; gradeCounter = gradeCounter + 1; }

average = total / 10; System.out.printf( "\nTotal de 10 notas e %d\n", total ); System.out.printf( "Media da classe e %d\n", average ); } }

...e chamando seu método (GradeBookTest1. java)

public class GradeBookTest1{ public static void main( String args[] ) { GradeBook1 myGradeBook = new GradeBook1( "Programacao Java" );

myGradeBook.displayMessage(); myGradeBook.determineClassAverage(); } }

Utilizando sentinelas (GradeBook2. java)

import java.util.Scanner;

public class GradeBook2{ private String courseName;

public GradeBook2( String name ) { courseName = name; } public void setCourseName( String name ) { courseName = name; } public String getCourseName() { return courseName; } public void displayMessage() { System.out.printf( "Bem-vindo ao curso\n%s!\n\n", getCourseName()); }

Page 8: Apostila Lobianco

public void determineClassAverage() { Scanner input = new Scanner( System.in );

int total; int gradeCounter; int grade; double average; total = 0; gradeCounter = 0;

System.out.print( "Digite a nota ou -1 para terminar: " ); grade = input.nextInt();

while ( grade != -1 ) { total = total + grade; gradeCounter = gradeCounter + 1;

System.out.print( "Digite a nota ou -1 para terminar: " ); grade = input.nextInt(); }

if ( gradeCounter != 0 ) { average = (double) total / gradeCounter;

System.out.printf( "\nTotal de %d notas digitadas e %d\n", gradeCounter, total ); System.out.printf( "Média da classe %.2f\n", average ); } else System.out.println( "Nenhuma nota digitada" ); } }

...e chamando seu método (GradeBookTest2. java)

public class GradeBookTest2{ public static void main( String args[] ) { GradeBook2 myGradeBook = new GradeBook2( "Programacao Java" );

myGradeBook.displayMessage(); myGradeBook.determineClassAverage(); } }

Page 9: Apostila Lobianco

Operadores de atribuição compostos+= a += 2 a = a + 2-= a -= 3 a = a - 3*= a *= 4 a = a * 4/= a /= 5 a = a / 5%= a %= 6 a = a % 6

Operadores de incremento e decrementoOperador Chamado Exemplo Explicação

++ pré-incremento ++a Incrementa antes da operação++ pós-incremento a++ Incrementa após operação-- pré-decremento --b Decrementa antes da operação-- pós-decremento b-- Decrementa após operação

Exemplo de pré e pós-incremento/decremento (Increment.java)

public class Increment { public static void main( String args[] ) { int c; c = 5; // atribui 5 à variável c System.out.println( c ); // imprime 5 System.out.println( c++ ); // imprime 5 então pós-incremente System.out.println( c ); // imprime 6

System.out.println(); // pula uma linha

c = 5; // atribui 5 à variável c System.out.println( c ); // imprime 5 System.out.println( ++c ); // pré-incrementa e então imprime 6 System.out.println( c ); // imprime 6 } }

Page 10: Apostila Lobianco

JAVA - AULA 4

A instrução for (Interest.java)

public class Interest { public static void main( String args[] ) { double amount; // quantia em depósito ao fim de cada ano double principal = 1000.0; // quantidade inicial antes dos juros double rate = 0.05; // taxa de juros

System.out.printf( "%s%20s \n", "Ano", "Quantia em deposito" );

for ( int year = 1; year <= 10; year++ ) { amount = principal * Math.pow( 1.0 + rate, year );

System.out.printf( "%4d%,20.2f\n", year, amount ); } } }

A instrução do..while (DoWhileTest. java)

public class DoWhileTest { public static void main( String args[] ) { int counter = 1;

do { System.out.printf( "%d ", counter ); ++counter; } while ( counter <= 10 );

System.out.println(); }}

Page 11: Apostila Lobianco

A estrutura switch (GradeBook. java)

import java.util.Scanner;

public class GradeBook { private String courseName; private int total; private int gradeCounter; private int aCount; private int bCount; private int cCount; private int dCount; private int fCount; public GradeBook( String name ) { courseName = name; }

public void setCourseName( String name ) { courseName = name; } public String getCourseName() { return courseName; }

public void displayMessage() { System.out.printf( "Bem-vindo ao curso\n%s!\n\n", getCourseName() ); } public void inputGrades() { Scanner input = new Scanner( System.in );

int grade;

System.out.printf( "%s\n%s\n %s\n %s\n", "Digite notas inteiras entre 0-100.", "Digite o fim-de-linha correspondente para terminar:", "No UNIX/Linux/Mac OS X digite <ctrl> d e depois Enter", "No Windows digite <ctrl> z e depois Enter" );

while (input.hasNext()) { grade = input.nextInt(); total += grade; ++gradeCounter; incrementLetterGradeCounter( grade ); }

Page 12: Apostila Lobianco

}

public void incrementLetterGradeCounter( int grade ) { switch ( grade / 10 ) { case 9: // nota estava entre 90 case 10: // e 100 ++aCount; // incrementa aCount break; // necessário para sair de switch case 8: // nota estava entre 80 e 89 ++bCount; // incrementa bCount break; // sai do switch case 7: // nota estava entre 70 e 79 ++cCount; // incrementa cCount break; // sai do switch case 6: // nota estava entre 60 e 69 ++dCount; // incrementa dCount break; // sai de switch default: // nota era menor que 60 ++fCount; // incrementa fCount break; // opcional; sairá de switch de qualquer jeito } // fim do switch }

public void displayGradeReport() { System.out.println( "\nRelatorio de Notas:" );

if ( gradeCounter != 0 ) { double average = (double) total / gradeCounter;

System.out.printf( "Total das %d notas digitadas e %d\n", gradeCounter, total ); System.out.printf( "Media da Classe e %.2f\n", average ); System.out.printf( "%s\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n", "Numero de estudantes que receberam cada nota:", "A: ", aCount, "B: ", bCount, "C: ", cCount, "D: ", dCount, "F: ", fCount ); } // fim do if else // nenhuma nota foi inserida, assim gera a saída da mensagem apropriada System.out.println( "Nenhuma nota foi inserida" ); } }

Page 13: Apostila Lobianco

...e chamando seu método (GradeBookTest. java)

public class GradeBookTest{ public static void main( String args[] ) { GradeBook myGradeBook = new GradeBook( "Programacao Java" );

myGradeBook.displayMessage(); myGradeBook.inputGrades(); myGradeBook.displayGradeReport(); } }

Instrução break (BreakTest.java)

public class BreakTest { public static void main( String args[] ) { int count; for ( count = 1; count <= 10; count++ ) { if ( count == 5 ) break;

System.out.printf( "%d ", count ); }

System.out.printf( "\nO laco termina com count = %d\n", count ); }}

Instrução continue (ContinueTest.java)

public class ContinueTest { public static void main( String args[] ) { for ( int count = 1; count <= 10; count++ ) { if ( count == 5 ) continue;

System.out.printf( "%d ", count ); }

System.out.println( "\nO continue e usado para pular o 5" ); } }

Page 14: Apostila Lobianco

Operadores lógicos (LogicalOperators.java)

public class LogicalOperators { public static void main( String args[] ) { // cria a tabela-verdade para o operador && (E condicional) System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", "Conditional AND (&&)", "false && false", ( false && false ), "false && true", ( false && true ), "true && false", ( true && false ), "true && true", ( true && true ));

// cria a tabela-verdade para o operador || (OU condicional) System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", "Conditional OR (||)", "false || false", ( false || false ), "false || true", ( false || true ), "true || false", ( true || false ), "true || true", ( true || true ));

// cria a tabela-verdade para o operador & (E lógico booleano) System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", "Boolean logical AND (&)", "false & false", ( false & false ), "false & true", ( false & true ), "true & false", ( true & false ), "true & true", ( true & true ));

// cria a tabela-verdade para | (OU inclusivo lógico booleano) System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", "Boolean logical inclusive OR (|)", "false | false", ( false | false ), "false | true", ( false | true ), "true | false", ( true | false ), "true | true", ( true | true ));

// cria a tabela-verdade para ^ (OU exclusivo lógico booleano) System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", "Boolean logical exclusive OR (^)", "false ^ false", ( false ^ false ), "false ^ true", ( false ^ true ), "true ^ false", ( true ^ false ), "true ^ true", ( true ^ true ));

// cria a tabela-verdade para ! (negação lógica) System.out.printf( "%s\n%s: %b\n%s: %b\n", "Logical NOT (!)", "!false", ( !false ), "!true", ( ! true) ); }}

Page 15: Apostila Lobianco

JAVA - AULA 5

Métodos com parâmetros (MaximumFinder.java)

import java.util.Scanner;

public class MaximumFinder { public void determineMaximum() { Scanner input = new Scanner( System.in );

System.out.print( "Digite tres numeros reais separados por espacos: " ); double number1 = input.nextDouble(); double number2 = input.nextDouble(); double number3 = input.nextDouble();

double result = maximum( number1, number2, number3 );

System.out.println("O maior e: " + result); } public double maximum( double x, double y, double z ) { double maximumValue = x;

if ( y > maximumValue ) maximumValue = y;

if ( z > maximumValue ) maximumValue = z;

return maximumValue; }}

...e chamando seu método (MaximumFinderTest.java)

public class MaximumFinderTest{ public static void main( String args[] ) { MaximumFinder maximumFinder = new MaximumFinder(); maximumFinder.determineMaximum(); }}

Page 16: Apostila Lobianco

Geração de números aleatórios (RollDie.java)

import java.util.Random;

public class RollDie { public static void main( String args[] ) { Random randomNumbers = new Random();

int frequency1 = 0; int frequency2 = 0; int frequency3 = 0; int frequency4 = 0; int frequency5 = 0; int frequency6 = 0;

int face; for ( int roll = 1; roll <= 6000; roll++ ) { face = 1 + randomNumbers.nextInt( 6 ); switch (face) { case 1: ++frequency1; break; case 2: ++frequency2; break; case 3: ++frequency3; break; case 4: ++frequency4; break; case 5: ++frequency5; break; case 6: ++frequency6; break; } }

System.out.println( "Face\tFrequencia" ); System.out.printf( "1\t%d\n2\t%d\n3\t%d\n4\t%d\n5\t%d\n6\t%d\n", frequency1, frequency2, frequency3, frequency4, frequency5, frequency6 ); } }

Page 17: Apostila Lobianco

Um jogo de azar com enumerações... (Craps.java)

import java.util.Random;

public class Craps { // cria um gerador de números aleatórios para uso no método rollDice private Random randomNumbers = new Random();

// enumeração com constantes que representam o status do jogo private enum Status { CONTINUE, WON, LOST };

// constantes que representam lançamentos comuns dos dados private final static int SNAKE_EYES = 2; private final static int TREY = 3; private final static int SEVEN = 7; private final static int YO_LEVEN = 11; private final static int BOX_CARS = 12;

// joga uma partida de craps public void play() { int myPoint = 0; // pontos se não ganhar ou perder na 1a. rolagem Status gameStatus; // pode conter CONTINUE, WON ou LOST

int sumOfDice = rollDice(); // primeira rolagem dos dados

// determina status do jogo e pontuação baseado no 1o lançamento switch ( sumOfDice ) { case SEVEN: // ganha com 7 no primeiro lançamento case YO_LEVEN: // ganha com 11 no primeiro lançamento gameStatus = Status.WON; break; case SNAKE_EYES: // perde com 2 no primeiro lançamento case TREY: // perde com 3 no primeiro lançamento case BOX_CARS: // perde com 12 no primeiro lançamento gameStatus = Status.LOST; break; default: // não ganhou nem perdeu, portanto registra a pontuação gameStatus = Status.CONTINUE; // jogo não terminou myPoint = sumOfDice; // informa a pontuação System.out.printf( "O ponto e %d\n", myPoint ); break; // opcional no final do switch } // switch final

// enquanto o jogo não estiver completo while (gameStatus == Status.CONTINUE) // nem WON nem LOST { sumOfDice = rollDice(); // lança os dados novamente

// determina o status do jogo if ( sumOfDice == myPoint ) // vitória por pontuação gameStatus = Status.WON; else if ( sumOfDice == SEVEN ) // perde obtendo 7

Page 18: Apostila Lobianco

gameStatus = Status.LOST; } // fim do while

// exibe uma mensagem ganhou ou perdeu if (gameStatus == Status.WON) System.out.println( "Jogador ganha" ); else System.out.println( "Jogador perde" ); } // fim do método play

// lança os dados, calcula a soma e exibe os resultados public int rollDice() { // seleciona valores aleatórios do dado int die1 = 1 + randomNumbers.nextInt( 6 ); // primeiro lançamento int die2 = 1 + randomNumbers.nextInt( 6 ); // segundo lançamento

int sum = die1 + die2; // soma dos valores dos dados

// exibe os resultados desse lançamento System.out.printf( "Jogador conseguiu %d + %d = %d\n", die1, die2, sum );

return sum; // retorna a soma dos dados } // fim do método rollDice} // fim da classe Craps

...e chamando seu método (CrapsTest.java)

public class CrapsTest { public static void main( String args[] ) { Craps game = new Craps(); game.play(); }}

Page 19: Apostila Lobianco

Escopo das declarações (Scope.java)

public class Scope{ // atributo acessível para todos os métodos dessa classe private int x = 1; // cria e inicializa a variável local x e chama métodos public void begin() { int x = 5; // variável local x do método sombreia o atributo x

System.out.printf( "variavel local x no metodo begin e %d\n", x );

useLocalVariable(); // useLocalVariable tem uma variável local x useField(); // useField utiliza o atributo x da classe Scope useLocalVariable(); // useLocalVariable reinicializa variável local useField(); // atributo x da classe Scope retém seu valor

System.out.printf("\nvariavel local x no metodo begin e %d\n", x ); } // fim do método begin

// cria e inicializa a variável local x durante cada chamada public void useLocalVariable() { int x = 25; // inicializada toda vez que useLocalVariable é chamado

System.out.printf( "\nvariavel local x ao entrar no metodo " ); System.out.printf( "useLocalVariable e %d\n", x ); ++x; // modifica a variável local x desse método System.out.printf( "variavel local x antes de sair do metodo " ); System.out.printf( "useLocalVariable e %d\n", x ); } // fim do método useLocalVariable

// modifica o atributo x da classe Scope durante cada chamada public void useField() { System.out.printf( "\natributo x ao entrar no metodo useField e %d\n", x ); x *= 10; // modifica o atributo x da classe Scope System.out.printf( "atributo x antes de sair do metodo useField e %d\n", x ); } // fim do método useField} // fim da classe Scope

...e chamando seu método (ScopeTest.java)

public class ScopeTest{ public static void main( String args[] ) { Scope testScope = new Scope(); testScope.begin(); }}

Page 20: Apostila Lobianco

Sobrecarga de método (MethodOverload.java)

public class MethodOverload { public void testOverloadedMethods() { System.out.printf( "Quadrado do inteiro 7 e %d\n", square( 7 )); System.out.printf( "Quadrado do real 7.5 e %f\n", square( 7.5 )); } public int square( int intValue ) { System.out.printf( "\nMetodo chamado com argumento inteiro: %d\n", intValue ); return intValue * intValue; }

public double square( double doubleValue ) { System.out.printf( "\nMetodo chamado com argumento real: %f\n", doubleValue ); return doubleValue * doubleValue; } }

...e chamando seu método (MethodOverloadTest.java)

public class MethodOverloadTest{ public static void main( String args[] ) { MethodOverload methodOverload = new MethodOverload(); methodOverload.testOverloadedMethods(); } }

Page 21: Apostila Lobianco

JAVA - AULA 6

Iniciando um vetor (InitArray1.java)

public class InitArray1 { public static void main( String args[] ) { int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };

System.out.printf( "%s%8s\n", "Indice", "Valor" ); for ( int counter = 0; counter < array.length; counter++ ) System.out.printf( "%6d%8d\n", counter, array[ counter ] ); } }

Usando vetores como contadores (RollDie.java)

import java.util.Random;

public class RollDie { public static void main( String args[] ) { Random randomNumbers = new Random(); int frequency[] = new int[ 7 ];

for ( int roll = 1; roll <= 6000; roll++ ) ++frequency[ 1 + randomNumbers.nextInt( 6 ) ];

System.out.printf( "%s%11s\n", "Face", "Frequencia" ); for ( int face = 1; face < frequency.length; face++ ) System.out.printf( "%4d%11d\n", face, frequency[ face ] ); } }

Passando vetores para métodos (PassArray.java)

public class PassArray { public static void main( String args[] ) { int array[] = { 1, 2, 3, 4, 5 }; System.out.println( "Efeito de passar por referencia todo vetor:\n" + "Os valores na ordem original sao:" );

for ( int value : array ) System.out.printf( " %d", value ); modifyArray( array ); System.out.println( "\n\nOs valores do vetor modificado sao:" );

Page 22: Apostila Lobianco

for ( int value : array ) System.out.printf( " %d", value ); System.out.printf( "\n\nEfeito de passar o valor de um elemento do vetor:\n" + "array[3] antes de modifyElement: %d\n", array[ 3 ] ); modifyElement( array[ 3 ] ); System.out.printf( "array[3] depois de modifyElement: %d\n", array[ 3 ] ); } public static void modifyArray( int array2[] ) { for ( int counter = 0; counter < array2.length; counter++ ) array2[ counter ] *= 2; } public static void modifyElement( int element ) { element *= 2; System.out.printf( "Valor do elemento em modifyElement: %d\n", element ); } }

Vetores multidimensionais (GradeBook.java)

public class GradeBook{ private String courseName; private int grades[][]; public GradeBook( String name, int gradesArray[][]) { courseName = name; grades = gradesArray; }

public void setCourseName( String name ) { courseName = name; }

public String getCourseName() { return courseName; }

public void displayMessage() { System.out.printf( "Bemvindo ao curso\n%s!\n\n", getCourseName() ); } public void processGrades() {

Page 23: Apostila Lobianco

outputGrades();

System.out.printf( "\n%s %d\n%s %d\n\n", "Menor nota no curso e", getMinimum(), "Maior nota no curso e", getMaximum() );

outputBarChart(); } public int getMinimum() { int lowGrade = grades[ 0 ][ 0 ];

for ( int studentGrades[] : grades ) { for ( int grade : studentGrades ) { if ( grade < lowGrade ) lowGrade = grade; } }

return lowGrade; } public int getMaximum() { int highGrade = grades[ 0 ][ 0 ];

for ( int studentGrades[] : grades ) { for ( int grade : studentGrades ) { if ( grade > highGrade ) highGrade = grade; } }

return highGrade; } public double getAverage( int setOfGrades[] ) { int total = 0; for ( int grade : setOfGrades ) total += grade;

return (double) total / setOfGrades.length; } public void outputBarChart() { System.out.println( "Distribuicao da notas da turma:" );

int frequency[] = new int[ 11 ];

Page 24: Apostila Lobianco

for ( int studentGrades[] : grades ) { for ( int grade : studentGrades ) ++frequency[ grade / 10 ]; } for ( int count = 0; count < frequency.length; count++ ) { if ( count == 10 ) System.out.printf( "%5d: ", 100 ); else System.out.printf( "%02d-%02d: ", count * 10, count * 10 + 9 ); for ( int stars = 0; stars < frequency[ count ]; stars++ ) System.out.print( "*" );

System.out.println(); } } public void outputGrades() { System.out.println( "As notas sao:\n" ); System.out.print( " " ); for ( int test = 0; test < grades[ 0 ].length; test++ ) System.out.printf( "Prova %d ", test + 1 );

System.out.println( " Media" ); for ( int student = 0; student < grades.length; student++ ) { System.out.printf( "Estudante %2d", student + 1 );

for ( int test : grades[ student ] ) System.out.printf( "%8d", test );

double average = getAverage( grades[ student ] ); System.out.printf( "%9.2f\n", average ); } }}

Page 25: Apostila Lobianco

...e chamando seu método (GradeBookTest.java)

public class GradeBookTest{ public static void main( String args[] ) { int gradesArray[][] = { { 87, 96, 70 }, { 68, 87, 90 }, { 94, 100, 90 }, { 100, 81, 82 }, { 83, 65, 85 }, { 78, 87, 65 }, { 85, 75, 83 }, { 91, 94, 100 }, { 76, 72, 84 }, { 87, 93, 73 } }; GradeBook myGradeBook = new GradeBook( "Programacao Java", gradesArray); myGradeBook.displayMessage(); myGradeBook.processGrades(); }}

Lista de argumentos de comprimento variável (VarargsTest.java)

public class VarargsTest { public static double average(double... numbers) { double total = 0.0;

// calcula total utilizando a instrução for aprimorada for ( double d : numbers ) total += d;

return total / numbers.length; }

public static void main( String args[] ) { double d1 = 10.0; double d2 = 20.0; double d3 = 30.0; double d4 = 40.0;

System.out.printf( "d1 = %.1f\nd2 = %.1f\nd3 = %.1f\nd4 = %.1f\n\n", d1, d2, d3, d4 );

System.out.printf( "Media de d1 e d2 = %.1f\n", average( d1, d2 )); System.out.printf( "Media de d1, d2 e d3 = %.1f\n", average( d1, d2, d3 )); System.out.printf( "Media de d1, d2, d3 e d4 = %.1f\n", average( d1, d2, d3, d4 )); } }

Page 26: Apostila Lobianco

Utilizando argumentos de linha de comando (InitArray2.java)

public class InitArray2 { public static void main(String args[]) { // verifica número de argumentos de linha de comando if (args.length != 3) System.out.println( "Erro: Favor redigitar todo o comando, incluindo\n" + "o tamanho do vetor, valor inicial e incremento." ); else { // obtém o tamanho do array a partir do // primeiro argumento de linha de comando int arrayLength = Integer.parseInt( args[ 0 ] ); int array[] = new int[ arrayLength ]; // cria o array

// obtém o valor inicial e o incremento a partir // do argumento de linha de comando int initialValue = Integer.parseInt( args[ 1 ] ); int increment = Integer.parseInt( args[ 2 ] );

// calcula valor de cada elemento do array for ( int counter = 0; counter < array.length; counter++ ) array[ counter ] = initialValue + increment * counter;

System.out.printf( "%s%8s\n", "Indice", "Valor" ); // exibe o valor e o índice de array for ( int counter = 0; counter < array.length; counter++ ) System.out.printf( "%5d%8d\n", counter, array[ counter ] ); } }}

Page 27: Apostila Lobianco

JAVA - AULA 7

Estudo da classe Time (Time1.java)

public class Time1 { private int hour; private int minute; private int second;

public void setTime( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); // valida horas minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); // valida minutos second = ( ( s >= 0 && s < 60 ) ? s : 0 ); // valida segundos } public String toUniversalString() { return String.format( "%02d:%02d:%02d", hour, minute, second ); } public String toString() { return String.format( "%d:%02d:%02d %s", ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ), minute, second, ( hour < 12 ? "AM" : "PM" ) ); } }

...e chamando seu método (Time1.java)

public class Time1Test { public static void main( String args[] ) { Time1 time = new Time1();

System.out.print( "A hora inicial no formato universal e: " ); System.out.println(time.toUniversalString()); System.out.print( "A hora inicial no formato padrao e: " ); System.out.println(time.toString()); System.out.println();

time.setTime( 13, 27, 6 ); System.out.print( "Hora universal depois de setTime e: " ); System.out.println(time.toUniversalString()); System.out.print( "Hora padrao depois de setTime e: " ); System.out.println(time.toString()); System.out.println(); time.setTime( 99, 99, 99 ); System.out.println( "Depois de tentar horario invalido:" ); System.out.print( "Hora universal: " ); System.out.println(time.toUniversalString()); System.out.print( "Hora padrao: " );

Page 28: Apostila Lobianco

System.out.println(time.toString()); }}

A referência this (ThisTest.java)

public class ThisTest { public static void main( String args[] ) { SimpleTime time = new SimpleTime( 15, 30, 19 ); System.out.println( time.buildString() ); }}

class SimpleTime { private int hour; private int minute; private int second;

// se o construtor utilizar nomes de parametro identicos a // nomes de variaveis de instancia a referencia "this" sera // exigida para distinguir entre nomes public SimpleTime( int hour, int minute, int second ) { this.hour = hour; this.minute = minute; this.second = second; }

// utilizam "this" explicito e implicito para chamar toUniversalString public String buildString() { return String.format( "%24s: %s\n%24s: %s", "this.toUniversalString()", this.toUniversalString(), "toUniversalString()",toUniversalString()); }

// converte em String no formato de data/hora universal (HH:MM:SS) public String toUniversalString() { // "this" nao e requerido aqui para acessar variaveis de instancia, // porque o metodo nao tem variaveis locais com os mesmos // nomes das variaveis de instancia return String.format( "%02d:%02d:%02d", this.hour, this.minute, this.second ); }}

Page 29: Apostila Lobianco

Construtores sobrecarregados (Time2.java)

public class Time2{ private int hour; private int minute; private int second;

public Time2() { this( 0, 0, 0 ); } public Time2( int h ) { this( h, 0, 0 ); } public Time2( int h, int m ) { this( h, m, 0 ); } public Time2( int h, int m, int s ) { setTime( h, m, s ); } public Time2( Time2 time ) { this( time.getHour(), time.getMinute(), time.getSecond() ); }

public void setTime( int h, int m, int s ) { setHour( h ); setMinute( m ); setSecond( s ); }

public void setHour( int h ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); }

public void setMinute( int m ) { minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); }

public void setSecond( int s ) { second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } public int getHour()

Page 30: Apostila Lobianco

{ return hour; } public int getMinute() { return minute; } public int getSecond() { return second; } public String toUniversalString() { return String.format( "%02d:%02d:%02d", getHour(), getMinute(), getSecond() ); } public String toString() { return String.format( "%02d:%02d:%02d %s", ( (getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12 ), getMinute(), getSecond(), ( getHour() < 12 ? "AM" : "PM" ) ); }}

...e chamando seu método (Time2Test.java)

public class Time2Test { public static void main( String args[] ) { Time2 t1 = new Time2(); // 00:00:00 Time2 t2 = new Time2( 2 ); // 02:00:00 Time2 t3 = new Time2( 21, 34 ); // 21:34:00 Time2 t4 = new Time2( 12, 25, 42 ); // 12:25:42 Time2 t5 = new Time2( 27, 74, 99 ); // 00:00:00 Time2 t6 = new Time2( t4 ); // 12:25:42

System.out.println( "Construtor com:" ); System.out.println( "t1: todos argumentos padrao" ); System.out.printf( " %s\n", t1.toUniversalString() ); System.out.printf( " %s\n", t1.toString() );

System.out.println( "t2: hora especificada, minuto e segundo padrao" ); System.out.printf( " %s\n", t2.toUniversalString() ); System.out.printf( " %s\n", t2.toString() );

System.out.println( "t3: hora e minuto especificados, segundo padrao" ); System.out.printf( " %s\n", t3.toUniversalString() ); System.out.printf( " %s\n", t3.toString() );

System.out.println( "t4: hora, minuto e segundo especificados" );

Page 31: Apostila Lobianco

System.out.printf( " %s\n", t4.toUniversalString() ); System.out.printf( " %s\n", t4.toString() );

System.out.println( "t5: especificando valores invalidos" ); System.out.printf( " %s\n", t5.toUniversalString() ); System.out.printf( " %s\n", t5.toString() );

System.out.println( "t6: objeto de Time2 especificado por t4" ); System.out.printf( " %s\n", t6.toUniversalString() ); System.out.printf( " %s\n", t6.toString() ); } }

Composição de classes I (Date.java)

public class Date { private int month; // 1-12 private int day; // 1-31 conforme o mês private int year; // qualquer ano

// construtor: chama checkMonth para confirmar o valor para month; // chama checkDay para confirmar o valor adequado para day public Date( int theMonth, int theDay, int theYear ) { month = checkMonth( theMonth ); // valida month year = theYear; // poderia validar year day = checkDay( theDay ); // valida day

System.out.printf( "Construtor de objeto Date para a data %s\n", this ); }

private int checkMonth( int testMonth ) { if ( testMonth > 0 && testMonth <= 12 ) return testMonth; else // month é inválido { System.out.printf( "Mes invalido (%d) modificado para 1.", testMonth ); return 1; } } private int checkDay( int testDay ) { int daysPerMonth[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // verifica se day está no intervalo para month if ( testDay > 0 && testDay <= daysPerMonth[ month ] ) return testDay; // verifica ano bissexto if ( month == 2 && testDay == 29 && ( year % 400 == 0 || ( year % 4 == 0 && year % 100 != 0 ) ) )

Page 32: Apostila Lobianco

return testDay; System.out.printf("Dia invalido (%d) modificado para 1.",testDay ); return 1; // mantém objeto em estado consistente } public String toString() { return String.format( "%d/%d/%d", month, day, year ); }}

Composição de classes II (Employee1.java)

public class Employee1 { private String firstName; private String lastName; private Date birthDate; private Date hireDate;

public Employee1( String first, String last, Date dateOfBirth, Date dateOfHire ) { firstName = first; lastName = last; birthDate = dateOfBirth; hireDate = dateOfHire; } public String toString() { return String.format( "%s, %s Contratacao: %s Nascimento: %s", lastName, firstName, hireDate, birthDate ); }}

...e chamando seu método (Employee1Test.java)

public class Employee1Test { public static void main( String args[] ) { Date birth = new Date( 7, 24, 1949 ); Date hire = new Date( 3, 12, 1988 ); Employee1 employee = new Employee1( "Bob", "Blue", birth, hire );

System.out.println( employee ); } }

Page 33: Apostila Lobianco

Enumerações (Book.java)

public enum Book { // declara constantes do tipo enum JCP6( "Java Como Programar 6e", "2005" ), CCP4( "C Como Programar 4e", "2004" ), IW3CP3( "Internet & World Wide Web Como Programar 3e", "2004" ), CPPCP4( "C++ Como Programar 4e", "2003" ), VBCP2( "Visual Basic .NET Como Programar 2e", "2002" ), CSHARPCP( "C# Como Programar", "2002" );

private final String title; private final String copyrightYear; // construtor enum Book( String bookTitle, String year ) { title = bookTitle; copyrightYear = year; } public String getTitle() { return title; } public String getCopyrightYear() { return copyrightYear; } }

...e chamando seus métodos (EnumTest.java)

import java.util.EnumSet;

public class EnumTest { public static void main( String args[] ) { System.out.println( "Todos os livros:\n" );

// imprime todos os livros em enum Book for (Book book : Book.values()) System.out.printf( "%-10s%-45s%s\n", book, book.getTitle(),book.getCopyrightYear() );

System.out.println( "\nMostra um intervalo dos constantes:\n" ); // imprime os primeiros quatro livros for ( Book book : EnumSet.range( Book.JCP6, Book.CPPCP4 )) System.out.printf( "%-10s%-45s%s\n", book, book.getTitle(),book.getCopyrightYear() ); } }

Page 34: Apostila Lobianco

Membros da classe static (Employee2.java)

public class Employee2 { private String firstName; private String lastName; private static int count = 0; // número de objetos na memória

public Employee2( String first, String last ) { firstName = first; lastName = last;

count++; // incrementa contagem estática de empregados System.out.printf( "Construtor de Employee: %s %s; count = %d\n", firstName, lastName, count ); }

protected void finalize() { count--; System.out.printf( "Terminador de Employee: %s %s; count = %d\n", firstName, lastName, count ); }

public String getFirstName() { return firstName; } public String getLastName() { return lastName; }

public static int getCount() { return count; } }

...e chamando seus métodos (Employee2Test.java)

public class Employee2Test { public static void main( String args[] ) { // mostra que a contagem é 0 antes de criar Employees System.out.printf( "Empregados antes da instanciacao: %d\n", Employee2.getCount());

// cria dois Employees; a contagem deve ser 2 Employee2 e1 = new Employee2( "Susan", "Baker" ); Employee2 e2 = new Employee2( "Bob", "Blue" );

Page 35: Apostila Lobianco

// mostra que a contagem é 2 depois de criar dois Employees System.out.println( "\nEmpregados depois da instanciacao: " ); System.out.printf( "via e1.getCount(): %d\n", e1.getCount()); System.out.printf( "via e2.getCount(): %d\n", e2.getCount()); System.out.printf( "via Employee2.getCount(): %d\n", Employee2.getCount()); // obtém nomes de Employees System.out.printf( "\nEmpregado 1: %s %s\nEmpregado 2: %s %s\n\n", e1.getFirstName(), e1.getLastName(), e2.getFirstName(), e2.getLastName() );

// nesse exemplo, há somente uma referência a cada Employee, // assim as duas instruções a seguir fazem com que a JVM marque // cada objeto Employee para coleta de lixo e1 = null; e2 = null;

System.gc(); // pede que a coleta de lixo ocorra agora

// mostra contagem de Employee depois de chamar o coletor de lixo; // contagem exibida pode ser 0, 1 ou 2 com base na execução do // coletor de lixo imediata e número de objetos Employees coletados System.out.printf( "\nEmpregados depois de System.gc(): %d\n", Employee2.getCount()); } }

Variáveis de instância final (Increment.java)

public class Increment { private int total = 0; private final int INCREMENT; // variável constante (não-inicializada)

public Increment( int incrementValue ) { INCREMENT = incrementValue; // inicializa constante (uma vez) }

public void addIncrementToTotal() { total += INCREMENT; } public String toString() { return String.format( "total = %d", total ); } }

Page 36: Apostila Lobianco

...e chamando seus métodos (IncrementTest.java)

public class IncrementTest { public static void main( String args[] ) { Increment value = new Increment( 5 );

System.out.printf( "Antes de incrementar: %s\n\n", value );

for ( int i = 1; i <= 3; i++ ) { value.addIncrementToTotal(); System.out.printf( "Depois de incrementar %d: %s\n", i, value ); } }}

Reutilização de código

A reutilização de classes em Java acontece quando os programadores se acostumam a não “reinventar a roda”. Ou seja, quando possuem bom conhecimento: das milhares de classes já implementadas do Java, dos pacotes catalogados pela sua empresa e dos incontáveis recursos oferecidos por outros programadores Java disponíveis (gratuitamente ou pagos).

Abstração de dados e encapsulamento

Normalmente as classes ocultam detalhes de implementação dos seus clientes. Isso se chama ocultamento de informações (ou encapsulamento).

Quando um cliente faz uso de uma classe e seus métodos sem se importar como são implementados ele utiliza uma abstração de dados.

Empacotando classes (Time3.java)

package br.unifieo.Aula_07;

public class Time3 { private int hour; private int minute; private int second;

public void setTime( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } public String toUniversalString() {

Page 37: Apostila Lobianco

return String.format( "%02d:%02d:%02d", hour, minute, second ); } public String toString() { return String.format( "%02d:%02d:%02d %s", ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ), minute, second, ( hour < 12 ? "AM" : "PM" ) ); }}

...e chamando seu método (Time3PackageTest.java)

import br.unifieo.Aula_07.Time3;

public class Time3PackageTest { public static void main( String args[] ) { Time3 time = new Time3();

System.out.print( "A hora inicial no formato universal e: " ); System.out.println(time.toUniversalString()); System.out.print( "A hora inicial no formato padrao e: " ); System.out.println(time.toString()); System.out.println();

time.setTime( 13, 27, 6 ); System.out.print( "Hora universal depois de setTime e: " ); System.out.println(time.toUniversalString()); System.out.print( "Hora padrao depois de setTime e: " ); System.out.println(time.toString()); System.out.println();

time.setTime( 99, 99, 99 ); System.out.println( "Depois de tentar horario invalido:" ); System.out.print( "Hora universal: " ); System.out.println(time.toUniversalString()); System.out.print( "Hora padrao: " ); System.out.println(time.toString()); }}

Page 38: Apostila Lobianco

JAVA - AULA 8

Superclasses e Subclasses

Muitas vezes um objeto de uma classe também o é de outra. Quando isto ocorre, pode acontecer que um, por herança, receba métodos e atributos de uma superclasse. Como exemplo temos a superclasse Forma e subclasses derivadas como: Circulo, Triangulo, Retangulo...

Copiar e colar código de uma classe para a outra pode espalhar erros por múltiplos arquivos de código-fonte. A utilização de herança diminui tal fonte de erro, pois quando precisamos alterar alguns métodos de uma superclasse, não necessitamos alterá-los em suas subclasses.

Membros protected

Os membros protected de uma superclasse podem ser acessados por membros dessa superclasse, por membros de usas subclasses e por membros de outras classes no mesmo pacote.

Hierarquia de herança com variáveis protected I (CommissionEmployee1.java)

public class CommissionEmployee1{ protected String firstName; protected String lastName; protected String socialSecurityNumber; protected double grossSales; // vendas brutas semanais protected double commissionRate; // porcentagem da comissão

public CommissionEmployee1( String first, String last, String ssn, double sales, double rate ) { firstName = first; lastName = last; socialSecurityNumber = ssn; setGrossSales( sales ); setCommissionRate( rate ); } public void setFirstName( String first ) { firstName = first; } public String getFirstName() { return firstName; } public void setLastName( String last ) { lastName = last; }

Page 39: Apostila Lobianco

public String getLastName() { return lastName; } public void setSocialSecurityNumber( String ssn ) { socialSecurityNumber = ssn; } public String getSocialSecurityNumber() { return socialSecurityNumber; } public void setGrossSales( double sales ) { grossSales = ( sales < 0.0 ) ? 0.0 : sales; } public double getGrossSales() { return grossSales; } public void setCommissionRate( double rate ) { commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0; } public double getCommissionRate() { return commissionRate; } public double earnings() { return commissionRate * grossSales; } public String toString() { return String.format( "%s: %s %s\n%s: %s\n%s: %.2f\n%s: %.2f", "empregado comissionado", firstName, lastName, "numero do seguro social", socialSecurityNumber, "vendas brutas", grossSales, "porcentagem da comissao", commissionRate ); } }

Page 40: Apostila Lobianco

Hierarquia de herança com variáveis protected II (BasePlusCommissionEmployee1.java)

public class BasePlusCommissionEmployee1 extends CommissionEmployee1{ private double baseSalary; // salário-base por semana

public BasePlusCommissionEmployee1( String first, String last, String ssn, double sales, double rate, double salary ) { super( first, last, ssn, sales, rate ); setBaseSalary( salary ); }

public void setBaseSalary( double salary ) { baseSalary = ( salary < 0.0 ) ? 0.0 : salary; } public double getBaseSalary() { return baseSalary; } public double earnings() { return baseSalary + ( commissionRate * grossSales ); } public String toString() { return String.format( "%s: %s %s\n%s: %s\n%s: %.2f\n%s: %.2f\n%s: %.2f", "salario base de comissao de empregado", firstName, lastName, "numero de seguro social", socialSecurityNumber, "vendas brutas", grossSales, "taxa de comissao", commissionRate, "salario base", baseSalary ); } }

...e chamando seus métodos (BasePlusCommissionEmployeeTest1.java)

public class BasePlusCommissionEmployeeTest1 { public static void main( String args[] ) { BasePlusCommissionEmployee1 employee = new BasePlusCommissionEmployee1( "Bob", "Lewis", "333-33-3333", 5000, .04, 300 ); System.out.println( "Informacoes do empregado obtidas pelos metodos get: \n" ); System.out.printf( "%s %s\n", "Primeiro nome e", employee.getFirstName() ); System.out.printf( "%s %s\n", "Ultimo nome e", employee.getLastName() );

Page 41: Apostila Lobianco

System.out.printf( "%s %s\n", "Numero do Seguro Social e", employee.getSocialSecurityNumber()); System.out.printf( "%s %.2f\n", "Vendas Brutas e", employee.getGrossSales() ); System.out.printf( "%s %.2f\n", "Taxa de comissao e", employee.getCommissionRate() ); System.out.printf( "%s %.2f\n", "Salario base e", employee.getBaseSalary() );

employee.setBaseSalary( 1000 ); System.out.printf( "\n%s:\n\n%s\n", "Informacoes atualizadas dos empregados obtidas com toString", employee.toString()); } }

Construtores em subclasses I (CommissionEmployee2.java)

public class CommissionEmployee2{ private String firstName; private String lastName; private String socialSecurityNumber; private double grossSales; private double commissionRate;

public CommissionEmployee2( String first, String last, String ssn, double sales, double rate ) { firstName = first; lastName = last; socialSecurityNumber = ssn; setGrossSales( sales ); setCommissionRate( rate );

System.out.printf( "\nConstrutor de CommissionEmployee2:\n%s\n", this ); }

public void setFirstName( String first ) { firstName = first; } public String getFirstName() { return firstName; } public void setLastName( String last ) { lastName = last; } public String getLastName() {

Page 42: Apostila Lobianco

return lastName; } public void setSocialSecurityNumber( String ssn ) { socialSecurityNumber = ssn; } public String getSocialSecurityNumber() { return socialSecurityNumber; } public void setGrossSales( double sales ) { grossSales = ( sales < 0.0 ) ? 0.0 : sales; } public double getGrossSales() { return grossSales; } public void setCommissionRate( double rate ) { commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0; } public double getCommissionRate() { return commissionRate; } public double earnings() { return getCommissionRate() * getGrossSales(); } public String toString() { return String.format( "%s: %s %s\n%s: %s\n%s: %.2f\n%s: %.2f", "empregado comissionado", getFirstName(), getLastName(), "numero de seguro social", getSocialSecurityNumber(), "vendas brutas", getGrossSales(), "taxa de comissao", getCommissionRate() ); } }

Construtores em subclasses II (BasePlusCommissionEmployee2.java)

public class BasePlusCommissionEmployee2 extends CommissionEmployee2{ private double baseSalary; // salário-base por semana

public BasePlusCommissionEmployee2( String first, String last, String ssn, double sales, double rate, double salary ) {

Page 43: Apostila Lobianco

super( first, last, ssn, sales, rate ); setBaseSalary( salary ); // valida e armazena salário-base System.out.printf( "\nConstrutor de BasePlusCommissionEmployee2:\n%s\n", this ); } public void setBaseSalary( double salary ) { baseSalary = ( salary < 0.0 ) ? 0.0 : salary; } public double getBaseSalary() { return baseSalary; } public double earnings() { return getBaseSalary() + super.earnings(); } public String toString() { return String.format( "%s %s\n%s: %.2f", "com salario base", super.toString(), "salario base", getBaseSalary() ); } }

...e chamando seus métodos (ConstructorTest.java)

public class ConstructorTest { public static void main( String args[] ) { CommissionEmployee2 employee1 = new CommissionEmployee2( "Bob", "Lewis", "333-33-3333", 5000, .04 ); System.out.println(); BasePlusCommissionEmployee2 employee2 = new BasePlusCommissionEmployee2( "Lisa", "Jones", "555-55-5555", 2000, .06, 800 ); System.out.println(); BasePlusCommissionEmployee2 employee3 = new BasePlusCommissionEmployee2( "Mark", "Sands", "888-88-8888", 8000, .15, 2000 ); }}

Page 44: Apostila Lobianco

JAVA - AULA 9

Polimorfismo

Imagine três classes de diferentes animais: Cachorro, Peixe e Passarinho. Todas derivam da superclasse Animal e herdam o método mover(). Porém, cada uma delas possui um tipo diferente de movimento (andar, nadar, voar). Logo, apesar de todas as classes possuírem, por herança, o método mover(), cada uma o faz de maneira própria. Daí o termo polimorfismo (muitos modos de fazer).

Criando a superclasse abstrata employee (Employee.java)

public abstract class Employee{ private String firstName; private String lastName; private String socialSecurityNumber;

public Employee( String first, String last, String ssn ) { firstName = first; lastName = last; socialSecurityNumber = ssn; } public void setFirstName( String first ) { firstName = first; } public String getFirstName() { return firstName; } public void setLastName( String last ) { lastName = last; } public String getLastName() { return lastName; } public void setSocialSecurityNumber( String ssn ) { socialSecurityNumber = ssn; } public String getSocialSecurityNumber() { return socialSecurityNumber; }

Page 45: Apostila Lobianco

public String toString() { return String.format( "%s %s\nnumero de seguro social: %s", getFirstName(), getLastName(), getSocialSecurityNumber() ); }

// método abstrato sobrescrito pelas subclasses public abstract double earnings(); }

Criando a subclasse concreta SalariedEmployee (SalariedEmployee.java)

public class SalariedEmployee extends Employee{ private double weeklySalary;

public SalariedEmployee( String first, String last, String ssn, double salary ) { super( first, last, ssn ); setWeeklySalary( salary ); } public void setWeeklySalary( double salary ) { weeklySalary = salary < 0.0 ? 0.0 : salary; } public double getWeeklySalary() { return weeklySalary; } public double earnings() { return getWeeklySalary(); } public String toString() { return String.format( "empregado assalariado : %s\n%s: $%,.2f", super.toString(), "salario semanal", getWeeklySalary() ); } }

Page 46: Apostila Lobianco

Criando a subclasse concreta HourlyEmployee (HourlyEmployee.java)

public class HourlyEmployee extends Employee{ private double wage; // salário por hora private double hours; // horas trabalhadas durante a semana

public HourlyEmployee( String first, String last, String ssn, double hourlyWage, double hoursWorked ) { super( first, last, ssn ); setWage( hourlyWage ); setHours( hoursWorked ); } public void setWage( double hourlyWage ) { wage = ( hourlyWage < 0.0 ) ? 0.0 : hourlyWage; } public double getWage() { return wage; } public void setHours( double hoursWorked ) { hours = ( ( hoursWorked >= 0.0 ) && ( hoursWorked <= 168.0 ) ) ? hoursWorked : 0.0; } public double getHours() { return hours; } public double earnings() { if ( getHours() <= 40 ) // nenhuma hora extra return getWage() * getHours(); else return 40 * getWage() + ( getHours() - 40 ) * getWage() * 1.5; } public String toString() { return String.format( "horista: %s\n%s: $%,.2f; %s: %,.2f", super.toString(), "salario-hora", getWage(), "horas trabalhadas", getHours() ); }}

Page 47: Apostila Lobianco

Criando a subclasse concreta CommissionEmployee (CommissionEmployee.java)

public class CommissionEmployee extends Employee{ private double grossSales; // vendas brutas semanais private double commissionRate; // porcentagem da comissão

public CommissionEmployee( String first, String last, String ssn, double sales, double rate ) { super( first, last, ssn ); setGrossSales( sales ); setCommissionRate( rate ); } public void setCommissionRate( double rate ) { commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0; } public double getCommissionRate() { return commissionRate; } public void setGrossSales( double sales ) { grossSales = ( sales < 0.0 ) ? 0.0 : sales; } public double getGrossSales() { return grossSales; } public double earnings() { return getCommissionRate() * getGrossSales(); } public String toString() { return String.format( "%s: %s\n%s: $%,.2f; %s: %.2f", "comissionado", super.toString(), "vendas brutas", getGrossSales(), "Taxa de comissao", getCommissionRate() ); }}

Page 48: Apostila Lobianco

e a subclasse concreta indireta BasePlusCommissionEmployee (BasePlusCommissionEmployee.java)

public class BasePlusCommissionEmployee extends CommissionEmployee{ private double baseSalary; // salário de base por semana

public BasePlusCommissionEmployee( String first, String last, String ssn, double sales, double rate, double salary ) { super( first, last, ssn, sales, rate ); setBaseSalary( salary ); } public void setBaseSalary( double salary ) { baseSalary = ( salary < 0.0 ) ? 0.0 : salary; } public double getBaseSalary() { return baseSalary; } public double earnings() { return getBaseSalary() + super.earnings(); } public String toString() { return String.format( "%s %s; %s: $%,.2f", "assalariado base", super.toString(), "salario base", getBaseSalary() ); }}

Demostrando processamento polimórfico (PayrollSystemTest.java)

public class PayrollSystemTest { public static void main( String args[] ) { // cria objetos de subclasse SalariedEmployee salariedEmployee = new SalariedEmployee( "John", "Smith", "111-11-1111", 800.00 ); HourlyEmployee hourlyEmployee = new HourlyEmployee( "Karen", "Price", "222-22-2222", 16.75, 40 ); CommissionEmployee commissionEmployee = new CommissionEmployee( "Sue", "Jones", "333-33-3333", 10000, .06 ); BasePlusCommissionEmployee basePlusCommissionEmployee = new BasePlusCommissionEmployee( "Bob", "Lewis", "444-44-4444", 5000, .04, 300 );

Page 49: Apostila Lobianco

System.out.println( "Empregados processados individualmente:\n" );

System.out.printf( "%s\n%s: $%,.2f\n\n", salariedEmployee, "recebeu", salariedEmployee.earnings() ); System.out.printf( "%s\n%s: $%,.2f\n\n", hourlyEmployee, "recebeu", hourlyEmployee.earnings() ); System.out.printf( "%s\n%s: $%,.2f\n\n", commissionEmployee, "recebeu", commissionEmployee.earnings() ); System.out.printf( "%s\n%s: $%,.2f\n\n", basePlusCommissionEmployee, "recebeu", basePlusCommissionEmployee.earnings() );

// cria um array Employee de quatro elementos Employee employees[] = new Employee[ 4 ];

// inicializa o array com Employees employees[ 0 ] = salariedEmployee; employees[ 1 ] = hourlyEmployee; employees[ 2 ] = commissionEmployee; employees[ 3 ] = basePlusCommissionEmployee;

System.out.println( "Empregados processados polimorficamente:\n" );

// processa genericamente cada elemento no employees for ( Employee currentEmployee : employees ) { System.out.println(currentEmployee); // invoca toString

// determina se elemento é um BasePlusCommissionEmployee if (currentEmployee instanceof BasePlusCommissionEmployee) { BasePlusCommissionEmployee employee = ( BasePlusCommissionEmployee ) currentEmployee;

double oldBaseSalary = employee.getBaseSalary(); employee.setBaseSalary( 1.10 * oldBaseSalary ); System.out.printf( "novo salario base com 10%% de aumento e: $%,.2f\n", employee.getBaseSalary() ); }

System.out.printf( "recebeu $%,.2f\n\n", currentEmployee.earnings()); } for ( int j = 0; j < employees.length; j++ ) System.out.printf( "Employee %d is a %s\n", j, employees[ j ].getClass().getName() ); } }

Page 50: Apostila Lobianco

Criando e utilizando interfaces

Se uma empresa deseja realizar seus pagamentos utilizando os mesmos métodos tanto para empregados como faturas, poderá fazer uso de interfaces especialmente preparadas para servirem tanto para folha de pagamentos quanto para pagamento de faturas.

Ou seja, os métodos da interface podem ser implementados por um amplo intervalo de classes não relacionadas.

Criando a interface Payable (Payable.java)

public interface Payable{ // calcula pagamento; nenhuma implementação double getPaymentAmount(); }

Criando a classe Invoice (Invoice.java)

public class Invoice implements Payable{ private String partNumber; private String partDescription; private int quantity; private double pricePerItem;

public Invoice( String part, String description, int count, double price ) { partNumber = part; partDescription = description; setQuantity( count ); setPricePerItem( price ); }

public void setPartNumber( String part ) { partNumber = part; } public String getPartNumber() { return partNumber; } public void setPartDescription( String description ) { partDescription = description; } public String getPartDescription() { return partDescription; }

Page 51: Apostila Lobianco

public void setQuantity( int count ) { quantity = ( count < 0 ) ? 0 : count; } public int getQuantity() { return quantity; } public void setPricePerItem( double price ) { pricePerItem = ( price < 0.0 ) ? 0.0 : price; } public double getPricePerItem() { return pricePerItem; } public String toString() { return String.format( "%s: \n%s: %s (%s) \n%s: %d \n%s: $%,.2f", "fatura", "numero da peca", getPartNumber(), getPartDescription(), "quantidade", getQuantity(), "preco por item", getPricePerItem() ); } public double getPaymentAmount() { return getQuantity() * getPricePerItem(); }}

Modificando Employee para implementar a interface Payable (EmployeeInterface.java)

public abstract class EmployeeInterface implements Payable{ private String firstName; private String lastName; private String socialSecurityNumber;

public EmployeeInterface( String first, String last, String ssn ) { firstName = first; lastName = last; socialSecurityNumber = ssn; } public void setFirstName( String first ) { firstName = first; } public String getFirstName() { return firstName;

Page 52: Apostila Lobianco

} public void setLastName( String last ) { lastName = last; } public String getLastName() { return lastName; } public void setSocialSecurityNumber( String ssn ) { socialSecurityNumber = ssn; } public String getSocialSecurityNumber() { return socialSecurityNumber; } public String toString() { return String.format( "%s %s\nnumero de seguro social: %s", getFirstName(), getLastName(), getSocialSecurityNumber() ); } // Nota: Não implementamos o método getPaymentAmount de Payable aqui, // assim então essa classe deve ser declarada abstrata para evitar um // erro de compilação.}

Modificando SalariedEmployeeInterface para uso com Payable (SalariedEmployeeInterface.java)

public class SalariedEmployeeInterface extends EmployeeInterface { private double weeklySalary;

public SalariedEmployeeInterface( String first, String last, String ssn, double salary ) { super( first, last, ssn ); setWeeklySalary( salary ); } public void setWeeklySalary( double salary ) { weeklySalary = salary < 0.0 ? 0.0 : salary; } public double getWeeklySalary() { return weeklySalary; }

public double getPaymentAmount() {

Page 53: Apostila Lobianco

return getWeeklySalary(); } public String toString() { return String.format( "salario: %s\n%s: $%,.2f", super.toString(), "salario semanal", getWeeklySalary() ); }}

Utilizando interface Payable para processar faturas e folha de pagamento (PayableInterfaceTest.java)

public class PayableInterfaceTest { public static void main( String args[] ) { Payable payableObjects[] = new Payable[ 4 ]; payableObjects[ 0 ] = new Invoice( "01234", "cadeira", 2, 375.00 ); payableObjects[ 1 ] = new Invoice( "56789", "pneu", 4, 79.95 ); payableObjects[ 2 ] = new SalariedEmployeeInterface( "John", "Smith", "111-11-1111", 800.00 ); payableObjects[ 3 ] = new SalariedEmployeeInterface( "Lisa", "Barnes", "888-88-8888", 1200.00 );

System.out.println( "Faturas e Empregados processados polimorficamente:\n" );

// processa genericamente cada elemento no array payableObjects for ( Payable currentPayable : payableObjects ) { System.out.printf( "%s \n%s: $%,.2f\n\n", currentPayable.toString(), "pagamento devido", currentPayable.getPaymentAmount() ); } }}

JAVA - AULA 10

Entrada e saída com JOptionPane (Addition.java)

import javax.swing.JOptionPane;

public class Addition { public static void main( String args[] ) { String firstNumber = JOptionPane.showInputDialog( "Digite primeiro inteiro" ); String secondNumber = JOptionPane.showInputDialog( "Digite segundo inteiro" );

int number1 = Integer.parseInt( firstNumber ); int number2 = Integer.parseInt( secondNumber );

Page 54: Apostila Lobianco

int sum = number1 + number2;

JOptionPane.showMessageDialog( null, "A soma e " + sum, "Soma de dois inteiros", JOptionPane.PLAIN_MESSAGE ); }}

Exibição de texto e imagens em uma janela (LabelFrame.java)

import java.awt.FlowLayout; // especifica organização dos componentesimport javax.swing.JFrame; // fornece recursos básicos de janelaimport javax.swing.JLabel; // exibe texto e imagensimport javax.swing.SwingConstants; // constantes comuns usadas com Swingimport javax.swing.Icon; // interface utilizada para manipular imagensimport javax.swing.ImageIcon; // carrega imagens

public class LabelFrame extends JFrame{ private JLabel label1; private JLabel label2; private JLabel label3; public LabelFrame() { super( "Testando JLabel" ); setLayout( new FlowLayout() ); // configura o layout de frame

// Construtor JLabel com um argumento de string label1 = new JLabel( "Label com texto" ); label1.setToolTipText( "Este e o label1" ); add( label1 ); // adiciona o label1 ao JFrame

// construtor JLabel com string, Icon e argumentos de alinhamento Icon logo = new ImageIcon( getClass().getResource( "logo.gif" ) ); label2 = new JLabel( "Label com texto e icone", logo, SwingConstants.LEFT ); label2.setToolTipText( "Este e o label2" ); add( label2 ); // adiciona label2 ao JFrame

Page 55: Apostila Lobianco

label3 = new JLabel(); // Construtor JLabel sem argumentos label3.setText( "Label com icone e texto embaixo" ); label3.setIcon( logo ); // adiciona o ícone ao JLabel label3.setHorizontalTextPosition( SwingConstants.CENTER ); label3.setVerticalTextPosition( SwingConstants.BOTTOM ); label3.setToolTipText( "Este e o label3" ); add( label3 ); // adiciona label3 ao JFrame }}

...e chamando seu método (LabelTest.java)

import javax.swing.JFrame;

public class LabelTest{ public static void main( String args[] ) { LabelFrame labelFrame = new LabelFrame(); labelFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); labelFrame.setSize( 300, 180 ); // configura o tamanho do frame labelFrame.setVisible( true ); // exibe o frame } }

Campos de texto com tratamento de eventos (TextFieldFrame.java)

import java.awt.FlowLayout;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import javax.swing.JFrame;import javax.swing.JTextField;import javax.swing.JPasswordField;import javax.swing.JOptionPane;

public class TextFieldFrame extends JFrame { private JTextField textField1; private JTextField textField2; private JTextField textField3; private JPasswordField passwordField;

public TextFieldFrame() { super( "Testando JTextField e JPasswordField" ); setLayout( new FlowLayout() );

textField1 = new JTextField( 10 ); add( textField1 );

textField2 = new JTextField( "Digite texto aqui" ); add( textField2 ); textField3 = new JTextField( "Campo de texto nao editavel", 26 ); textField3.setEditable( false ); // desativa a edição add( textField3 );

Page 56: Apostila Lobianco

passwordField = new JPasswordField( "Texto escondido" ); add( passwordField ); // handlers (encarregados) de evento registradores TextFieldHandler handler = new TextFieldHandler(); textField1.addActionListener( handler ); textField2.addActionListener( handler ); textField3.addActionListener( handler ); passwordField.addActionListener( handler ); }

private class TextFieldHandler implements ActionListener { public void actionPerformed( ActionEvent event ) { String string = "";

// usuário pressionou Enter no JTextField textField1 if (event.getSource() == textField1) string = String.format( "textField1: %s", event.getActionCommand());

// usuário pressionou Enter no JTextField textField2 else if (event.getSource() == textField2) string = String.format( "textField2: %s", event.getActionCommand());

// usuário pressionou Enter no JTextField textField3 else if (event.getSource() == textField3) string = String.format( "textField3: %s", event.getActionCommand());

// usuário pressionou Enter no JTextField passwordField else if (event.getSource() == passwordField) string = String.format( "passwordField: %s", new String(passwordField.getPassword()) );

JOptionPane.showMessageDialog( null, string ); } }}

...e chamando seu método (TextFieldTest.java)

import javax.swing.JFrame;

public class TextFieldTest{ public static void main( String args[] ) { TextFieldFrame textFieldFrame = new TextFieldFrame(); textFieldFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); textFieldFrame.setSize( 325, 100 ); textFieldFrame.setVisible( true ); } }

Page 57: Apostila Lobianco

O botão JButton (ButtonFrame.java)

import java.awt.FlowLayout;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import javax.swing.JFrame;import javax.swing.JButton;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JOptionPane;

public class ButtonFrame extends JFrame { private JButton plainJButton; private JButton fancyJButton;

public ButtonFrame() { super( "Testando Buttons" ); setLayout( new FlowLayout() );

plainJButton = new JButton( "Plain Button" ); add( plainJButton ); // adiciona plainJButton ao JFrame

Icon bug1 = new ImageIcon( getClass().getResource( "bug1.gif" ) ); Icon bug2 = new ImageIcon( getClass().getResource( "bug2.gif" ) ); // configura imagem fancyJButton = new JButton( "Fancy Button", bug1 ); // configura imagem de rollover fancyJButton.setRolloverIcon( bug2 ); add( fancyJButton ); // adiciona fancyJButton ao JFrame

// cria novo ButtonHandler para tratamento de evento de botão ButtonHandler handler = new ButtonHandler(); fancyJButton.addActionListener( handler ); plainJButton.addActionListener( handler ); }

private class ButtonHandler implements ActionListener { public void actionPerformed( ActionEvent event ) { JOptionPane.showMessageDialog(ButtonFrame.this, String.format( "Voce pressionou: %s", event.getActionCommand()) ); } } }

...e chamando seu método (ButtonTest.java)

import javax.swing.JFrame;

public class ButtonTest { public static void main( String args[] ) { ButtonFrame buttonFrame = new ButtonFrame();

Page 58: Apostila Lobianco

buttonFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); buttonFrame.setSize( 275, 110 ); buttonFrame.setVisible( true ); } }

O JCheckBox (CheckBoxFrame.java)

import java.awt.FlowLayout;import java.awt.Font;import java.awt.event.ItemListener;import java.awt.event.ItemEvent;import javax.swing.JFrame;import javax.swing.JTextField;import javax.swing.JCheckBox;

public class CheckBoxFrame extends JFrame { private JTextField textField; private JCheckBox boldJCheckBox; private JCheckBox italicJCheckBox; public CheckBoxFrame() { super( "Testando JCheckBox" ); setLayout( new FlowLayout() );

textField = new JTextField( "Veja a mudanca no estilo da fonte", 20 ); textField.setFont( new Font( "Serif", Font.PLAIN, 14 ) ); add( textField );

boldJCheckBox = new JCheckBox( "Bold" ); italicJCheckBox = new JCheckBox( "Italic" ); add( boldJCheckBox ); add( italicJCheckBox );

CheckBoxHandler handler = new CheckBoxHandler(); boldJCheckBox.addItemListener( handler ); italicJCheckBox.addItemListener( handler ); } private class CheckBoxHandler implements ItemListener { private int valBold = Font.PLAIN; private int valItalic = Font.PLAIN;

// responde aos eventos de caixa de seleção public void itemStateChanged( ItemEvent event ) { // processa eventos da caixa de seleção de negrito if (event.getSource() == boldJCheckBox) valBold = boldJCheckBox.isSelected()? Font.BOLD : Font.PLAIN; // processa eventos da caixa de seleção de itálico if (event.getSource() == italicJCheckBox)

Page 59: Apostila Lobianco

valItalic = italicJCheckBox.isSelected()? Font.ITALIC : Font.PLAIN;

// configura a fonte do campo de texto textField.setFont( new Font( "Serif", valBold + valItalic, 14 ) ); } }}

...e chamando seu método (CheckBoxTest.java)

import javax.swing.JFrame;

public class CheckBoxTest{ public static void main( String args[] ) { CheckBoxFrame checkBoxFrame = new CheckBoxFrame(); checkBoxFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); checkBoxFrame.setSize( 275, 100 ); checkBoxFrame.setVisible( true ); } }

O JRadioButton (JRadioButtonFrame.java)

import java.awt.FlowLayout;import java.awt.Font;import java.awt.event.ItemListener;import java.awt.event.ItemEvent;import javax.swing.JFrame;import javax.swing.JTextField;import javax.swing.JRadioButton;import javax.swing.ButtonGroup;

public class RadioButtonFrame extends JFrame { private JTextField textField; private Font plainFont; private Font boldFont; private Font italicFont; private Font boldItalicFont; private JRadioButton plainJRadioButton; private JRadioButton boldJRadioButton; private JRadioButton italicJRadioButton; private JRadioButton boldItalicJRadioButton; private ButtonGroup radioGroup; public RadioButtonFrame() { super( "Testando RadioButton" ); setLayout( new FlowLayout() );

textField = new JTextField( "Veja o estilo da fonte mudar", 25 ); add( textField );

Page 60: Apostila Lobianco

// cria botões de opção plainJRadioButton = new JRadioButton( "Plain", true ); boldJRadioButton = new JRadioButton( "Bold", false ); italicJRadioButton = new JRadioButton( "Italic", false ); boldItalicJRadioButton = new JRadioButton( "Bold/Italic", false ); add( plainJRadioButton ); add( boldJRadioButton ); add( italicJRadioButton ); add( boldItalicJRadioButton );

// cria relacionamento lógico entre JRadioButtons radioGroup = new ButtonGroup(); radioGroup.add( plainJRadioButton ); radioGroup.add( boldJRadioButton ); radioGroup.add( italicJRadioButton ); radioGroup.add( boldItalicJRadioButton );

// cria fonte objetos plainFont = new Font( "Serif", Font.PLAIN, 14 ); boldFont = new Font( "Serif", Font.BOLD, 14 ); italicFont = new Font( "Serif", Font.ITALIC, 14 ); boldItalicFont = new Font( "Serif", Font.BOLD + Font.ITALIC, 14 ); textField.setFont( plainFont ); // registra eventos para JRadioButtons plainJRadioButton.addItemListener( new RadioButtonHandler( plainFont ) ); boldJRadioButton.addItemListener( new RadioButtonHandler( boldFont ) ); italicJRadioButton.addItemListener( new RadioButtonHandler( italicFont ) ); boldItalicJRadioButton.addItemListener( new RadioButtonHandler( boldItalicFont ) ); } // fim do construtor RadioButtonFrame

// classe interna private para tratar eventos de botão de opção private class RadioButtonHandler implements ItemListener { private Font font;

public RadioButtonHandler( Font f ) { font = f; // configura a fonte desse listener } public void itemStateChanged( ItemEvent event ) { textField.setFont( font ); } }}

Page 61: Apostila Lobianco

...e chamando seu método (JRadioButtonTest.java)

import javax.swing.JFrame;

public class RadioButtonTest { public static void main( String args[] ) { RadioButtonFrame radioButtonFrame = new RadioButtonFrame(); radioButtonFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); radioButtonFrame.setSize( 300, 100 ); radioButtonFrame.setVisible( true ); }}

O JComboBox (ComboBoxFrame.java)

import java.awt.FlowLayout;import java.awt.event.ItemListener;import java.awt.event.ItemEvent;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JComboBox;import javax.swing.Icon;import javax.swing.ImageIcon;

public class ComboBoxFrame extends JFrame { private JComboBox imagesJComboBox; private JLabel label; private String names[] = { "bug1.gif", "bug2.gif", "travelbug.gif", "buganim.gif" }; private Icon icons[] = { new ImageIcon( getClass().getResource( names[ 0 ] ) ), new ImageIcon( getClass().getResource( names[ 1 ] ) ), new ImageIcon( getClass().getResource( names[ 2 ] ) ), new ImageIcon( getClass().getResource( names[ 3 ] ) ) };

public ComboBoxFrame() { super( "Testando JComboBox" ); setLayout( new FlowLayout() );

imagesJComboBox = new JComboBox( names ); imagesJComboBox.setMaximumRowCount( 3 ); // exibe três linhas

imagesJComboBox.addItemListener( new ItemListener() { public void itemStateChanged( ItemEvent event ) { // determina se caixa de seleção está marcada ou não if ( event.getStateChange() == ItemEvent.SELECTED ) label.setIcon( icons[

Page 62: Apostila Lobianco

imagesJComboBox.getSelectedIndex() ] ); } } );

add( imagesJComboBox ); label = new JLabel( icons[ 0 ] ); add( label ); }}

...e chamando seu método (ComboBoxTest.java)

import javax.swing.JFrame;

public class ComboBoxTest{ public static void main( String args[] ) { ComboBoxFrame comboBoxFrame = new ComboBoxFrame(); comboBoxFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); comboBoxFrame.setSize( 350, 150 ); comboBoxFrame.setVisible( true ); } }

O JList (ListFrame.java)

import java.awt.FlowLayout;import java.awt.Color;import javax.swing.JFrame;import javax.swing.JList;import javax.swing.JScrollPane;import javax.swing.event.ListSelectionListener;import javax.swing.event.ListSelectionEvent;import javax.swing.ListSelectionModel;

public class ListFrame extends JFrame { private JList colorJList; // lista para exibir cores private final String colorNames[] = { "Black", "Blue", "Cyan", "Dark Gray", "Gray", "Green", "Light Gray", "Magenta", "Orange", "Pink", "Red", "White", "Yellow" }; private final Color colors[] = { Color.BLACK, Color.BLUE, Color.CYAN, Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE, Color.YELLOW };

public ListFrame() { super( "Testando List" ); setLayout( new FlowLayout() ); colorJList = new JList( colorNames ); colorJList.setVisibleRowCount( 5 );

Page 63: Apostila Lobianco

colorJList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );

// adiciona um JScrollPane que contém JList ao frame add( new JScrollPane( colorJList ) );

colorJList.addListSelectionListener( new ListSelectionListener() { public void valueChanged( ListSelectionEvent event ) { getContentPane().setBackground( colors[colorJList.getSelectedIndex()] ); } } ); }}

...e chamando seu método (ListTest.java)

import javax.swing.JFrame;

public class ListTest { public static void main( String args[] ) { ListFrame listFrame = new ListFrame(); listFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); listFrame.setSize( 350, 150 ); listFrame.setVisible( true ); }}

Listas de seleção múltipla (MultipleSelectionFrame.java)

import java.awt.FlowLayout;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import javax.swing.JFrame;import javax.swing.JList;import javax.swing.JButton;import javax.swing.JScrollPane;import javax.swing.ListSelectionModel;

public class MultipleSelectionFrame extends JFrame { private JList colorJList; private JList copyJList; private JButton copyJButton; private final String colorNames[] = { "Black", "Blue", "Cyan", "Dark Gray", "Gray", "Green", "Light Gray", "Magenta", "Orange", "Pink", "Red", "White", "Yellow" };

public MultipleSelectionFrame() { super( "Multiple Selection Lists" );

Page 64: Apostila Lobianco

setLayout( new FlowLayout() );

colorJList = new JList( colorNames ); colorJList.setVisibleRowCount( 5 ); colorJList.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION ); add( new JScrollPane( colorJList ) );

copyJButton = new JButton( "Copy >>>" ); copyJButton.addActionListener(

new ActionListener() { public void actionPerformed( ActionEvent event ) { // coloca valores selecionados na copyJList copyJList.setListData( colorJList.getSelectedValues() ); } } );

add( copyJButton );

copyJList = new JList(); copyJList.setVisibleRowCount( 5 ); copyJList.setFixedCellWidth( 100 ); copyJList.setFixedCellHeight( 15 ); copyJList.setSelectionMode( ListSelectionModel.SINGLE_INTERVAL_SELECTION ); add( new JScrollPane( copyJList ) ); }}

...e chamando seu método (MultipleSelectionTest.java)

import javax.swing.JFrame;

public class MultipleSelectionTest{ public static void main( String args[] ) { MultipleSelectionFrame multipleSelectionFrame = new MultipleSelectionFrame(); multipleSelectionFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); multipleSelectionFrame.setSize( 350, 140 ); multipleSelectionFrame.setVisible( true ); }}

Page 65: Apostila Lobianco

Tratamento de eventos de mouse (MouseTrackerFrame.java)

import java.awt.Color;import java.awt.BorderLayout;import java.awt.event.MouseListener;import java.awt.event.MouseMotionListener;import java.awt.event.MouseEvent;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;

public class MouseTrackerFrame extends JFrame{ private JPanel mousePanel; // painel onde eventos de mouse ocorrerão private JLabel statusBar; // rótulo que exibe informações de evento

public MouseTrackerFrame() { super( "Demonstrando Eventos de Mouse" );

mousePanel = new JPanel(); mousePanel.setBackground( Color.WHITE ); add( mousePanel, BorderLayout.CENTER );

statusBar = new JLabel( "Mouse fora de JPanel" ); add( statusBar, BorderLayout.SOUTH );

MouseHandler handler = new MouseHandler(); mousePanel.addMouseListener( handler ); mousePanel.addMouseMotionListener( handler ); } private class MouseHandler implements MouseListener, MouseMotionListener { public void mouseClicked( MouseEvent event ) { statusBar.setText( String.format( "Clicado em [%d, %d]", event.getX(),event.getY() ) ); }

public void mousePressed( MouseEvent event ) { statusBar.setText( String.format( "Pressionado em [%d, %d]", event.getX(),event.getY() ) ); } public void mouseReleased( MouseEvent event ) { statusBar.setText( String.format( "Solto em [%d, %d]", event.getX(),event.getY() ) ); } public void mouseEntered( MouseEvent event ) { statusBar.setText( String.format( "Mouse entrou em [%d, %d]",

Page 66: Apostila Lobianco

event.getX(),event.getY() ) ); mousePanel.setBackground( Color.GREEN ); } public void mouseExited( MouseEvent event ) { statusBar.setText( "Mouse fora de JPanel" ); mousePanel.setBackground( Color.WHITE ); } public void mouseDragged( MouseEvent event ) { statusBar.setText( String.format( "Arrastado em [%d, %d]", event.getX(),event.getY() ) ); } public void mouseMoved( MouseEvent event ) { statusBar.setText( String.format( "Movido em [%d, %d]", event.getX(),event.getY() ) ); } }}

...e chamando seu método (MouseTracker.java)

import javax.swing.JFrame;

public class MouseTracker { public static void main( String args[] ) { MouseTrackerFrame mouseTrackerFrame = new MouseTrackerFrame(); mouseTrackerFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); mouseTrackerFrame.setSize( 300, 100 ); mouseTrackerFrame.setVisible( true ); }}

Tratamento de eventos de teclado (KeyDemoFrame.java)

import java.awt.Color;import java.awt.event.KeyListener;import java.awt.event.KeyEvent;import javax.swing.JFrame;import javax.swing.JTextArea;

public class KeyDemoFrame extends JFrame implements KeyListener{ private String line1 = ""; private String line2 = ""; private String line3 = ""; private JTextArea textArea; public KeyDemoFrame() {

Page 67: Apostila Lobianco

super( "Demonstrando Eventos de Teclado" );

textArea = new JTextArea( 10, 15 ); textArea.setText( "Pressione qualquer tecla no teclado..." ); textArea.setEnabled( false ); // desativa textarea textArea.setDisabledTextColor( Color.BLACK ); // formata cor texto add( textArea );

addKeyListener( this ); } public void keyPressed( KeyEvent event ) { line1 = String.format( "Tecla pressionada: %s", event.getKeyText( event.getKeyCode() )); setLines2and3( event ); }

public void keyReleased( KeyEvent event ) { line1 = String.format( "Tecla solta: %s", event.getKeyText( event.getKeyCode() )); setLines2and3( event ); } public void keyTyped( KeyEvent event ) { line1 = String.format( "Tecla digitada: %s", event.getKeyChar()); setLines2and3( event ); } private void setLines2and3( KeyEvent event ) { line2 = String.format( "Esta tecla %se uma tecla de acao", (event.isActionKey() ? "" : "nao " ) );

String temp = event.getKeyModifiersText( event.getModifiers() );

line3 = String.format( "Modificador de teclas pressionado: %s", ( temp.equals( "" ) ? "nenhum" : temp ) );

textArea.setText( String.format( "%s\n%s\n%s\n", line1, line2, line3 ) ); } }

...e chamando seu método (KeyDemo.java)

import javax.swing.JFrame;

public class KeyDemo { public static void main( String args[] ) { KeyDemoFrame keyDemoFrame = new KeyDemoFrame(); keyDemoFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); keyDemoFrame.setSize( 350, 100 );

Page 68: Apostila Lobianco

keyDemoFrame.setVisible( true ); }}

Gerenciador de layout mais simples: FlowLayout (FlowLayoutFrame.java)

import java.awt.FlowLayout;import java.awt.Container;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import javax.swing.JFrame;import javax.swing.JButton;

public class FlowLayoutFrame extends JFrame { private JButton leftJButton; private JButton centerJButton; private JButton rightJButton; private FlowLayout layout; private Container container; public FlowLayoutFrame() { super( "FlowLayout Demo" );

layout = new FlowLayout(); container = getContentPane(); setLayout( layout );

leftJButton = new JButton( "Esquerda" ); add( leftJButton ); leftJButton.addActionListener(

new ActionListener() { public void actionPerformed( ActionEvent event ) { layout.setAlignment( FlowLayout.LEFT );

layout.layoutContainer( container ); } } ); centerJButton = new JButton( "Centro" ); add( centerJButton ); centerJButton.addActionListener(

new ActionListener() { public void actionPerformed( ActionEvent event ) { layout.setAlignment( FlowLayout.CENTER );

layout.layoutContainer( container ); } }

Page 69: Apostila Lobianco

); rightJButton = new JButton( "Direita" ); add( rightJButton ); rightJButton.addActionListener(

new ActionListener() { public void actionPerformed( ActionEvent event ) { layout.setAlignment( FlowLayout.RIGHT );

layout.layoutContainer( container ); } } ); }}

...e chamando seu método (FlowLayoutDemo.java)

import javax.swing.JFrame;

public class FlowLayoutDemo{ public static void main( String args[] ) { FlowLayoutFrame flowLayoutFrame = new FlowLayoutFrame(); flowLayoutFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); flowLayoutFrame.setSize( 300, 75 ); flowLayoutFrame.setVisible( true ); }}

Gerenciador de layout II (BorderLayoutFrame.java)

import java.awt.BorderLayout;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import javax.swing.JFrame;import javax.swing.JButton;

public class BorderLayoutFrame extends JFrame implements ActionListener { private JButton buttons[]; private final String names[] = { "Esconder North", "Esconder South", "Esconder East", "Esconder West", "Esconder Center" }; private BorderLayout layout; public BorderLayoutFrame() { super( "BorderLayout Demo" );

layout = new BorderLayout( 5, 5 ); // espaços de 5 pixels setLayout( layout ); buttons = new JButton[ names.length ];

Page 70: Apostila Lobianco

for ( int count = 0; count < names.length; count++ ) { buttons[ count ] = new JButton( names[ count ] ); buttons[ count ].addActionListener( this ); }

add( buttons[ 0 ], BorderLayout.NORTH ); add( buttons[ 1 ], BorderLayout.SOUTH ); add( buttons[ 2 ], BorderLayout.EAST ); add( buttons[ 3 ], BorderLayout.WEST ); add( buttons[ 4 ], BorderLayout.CENTER ); } public void actionPerformed( ActionEvent event ) { for ( JButton button : buttons ) { if ( event.getSource() == button ) button.setVisible( false ); else button.setVisible( true ); }

layout.layoutContainer( getContentPane() ); }}

...e chamando seu método (BorderLayoutDemo.java)

import javax.swing.JFrame;

public class BorderLayoutDemo { public static void main( String args[] ) { BorderLayoutFrame borderLayoutFrame = new BorderLayoutFrame(); borderLayoutFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); borderLayoutFrame.setSize( 300, 200 ); borderLayoutFrame.setVisible( true ); } }

Gerenciador de layout III (GridLayoutFrame.java)

import java.awt.GridLayout;import java.awt.Container;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import javax.swing.JFrame;import javax.swing.JButton;

public class GridLayoutFrame extends JFrame implements ActionListener { private JButton buttons[]; private final String names[] =

Page 71: Apostila Lobianco

{ "Um", "Dois", "Tres", "Quatro", "Cinco", "Seis" }; private boolean toggle = true; // alterna entre dois layouts private Container container; private GridLayout gridLayout1; // primeiro gridlayout private GridLayout gridLayout2; // segundo gridlayout

// construtor sem argumento public GridLayoutFrame() { super( "GridLayout Demo" ); gridLayout1 = new GridLayout( 2, 3, 5, 5 ); // 2 X 3; lacunas de 5 gridLayout2 = new GridLayout( 3, 2 ); // 3 X 2; nenhuma lacuna container = getContentPane(); setLayout( gridLayout1 ); buttons = new JButton[ names.length ]; for ( int count = 0; count < names.length; count++ ) { buttons[ count ] = new JButton( names[ count ] ); buttons[ count ].addActionListener( this ); add( buttons[ count ] ); } } public void actionPerformed( ActionEvent event ) { if ( toggle ) container.setLayout( gridLayout2 ); else container.setLayout( gridLayout1 ); toggle = !toggle; // alterna para valor oposto container.validate(); // refaz o layout do contêiner }}

...e chamando seu método (GridLayoutDemo.java)

import javax.swing.JFrame;

public class GridLayoutDemo { public static void main( String args[] ) { GridLayoutFrame gridLayoutFrame = new GridLayoutFrame(); gridLayoutFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); gridLayoutFrame.setSize( 300, 200 ); gridLayoutFrame.setVisible( true ); }}

O JTextArea (TextAreaFrame.java)

import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import javax.swing.Box;

Page 72: Apostila Lobianco

import javax.swing.JFrame;import javax.swing.JTextArea;import javax.swing.JButton;import javax.swing.JScrollPane;

public class TextAreaFrame extends JFrame { private JTextArea textArea1; private JTextArea textArea2; private JButton copyJButton; public TextAreaFrame() { super( "TextArea Demo" ); Box box = Box.createHorizontalBox(); String demo = "Esta e uma demostracao de texto para\n" + "ilustrar a copia de texto\nde uma textarea para\n" + "outra textarea usando um\nevento externo\n";

textArea1 = new JTextArea( demo, 10, 15 ); box.add( new JScrollPane( textArea1 ) );

copyJButton = new JButton( "Copiar >>>" ); box.add( copyJButton ); copyJButton.addActionListener(

new ActionListener() { public void actionPerformed( ActionEvent event ) { textArea2.setText( textArea1.getSelectedText() ); } } ); textArea2 = new JTextArea( 10, 15 ); textArea2.setEditable( false ); box.add( new JScrollPane( textArea2 ) );

add( box ); } }

...e chamando seu método (TextAreaDemo.java)

import javax.swing.JFrame;

public class TextAreaDemo{ public static void main( String args[] ) { TextAreaFrame textAreaFrame = new TextAreaFrame(); textAreaFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); textAreaFrame.setSize( 425, 200 ); textAreaFrame.setVisible( true ); }}

Page 73: Apostila Lobianco