Jorge Ferreira
1
NOTAS DE AULA – JAVA 5 E NETBEANS 5
Seguindo as configurações iniciais do formulário, devemos definir o comportamento de
apresentação da janela quando executarmos o programa. Para tanto, devemos clicar na
aba Code, a partir da caixa de propriedades (Properties). Devemos ajustar a propriedade
Form Size Police, definindo o valor generate resize code. Dessa forma, estamos
definindo que o formulário será aberto de acordo com as dimensões denifidas na fase de
design.
EXEMPLO 1 – PROGRAMA NOME
Caso deseje que o formulário seja apresentado no centro do desktop, marque a caixa de
seleção da propriedade Generate Center.
private void btapresentanomeActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
txtresposta.setText(txtnome.getText());
}
Jorge Ferreira
private void btsairActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
private void btlimparActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
txtnome.setText("");
txtresposta.setText("");
}
2
Jorge Ferreira
EXEMPLO 2 – PROGRAMA CONCATENAR
private void btokActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String nome, sobrenome;
nome = txtnome.getText();
sobrenome = txtsobrenome.getText();
txtresultado.setText(nome + " " + sobrenome);
private void btsairActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
3
Jorge Ferreira
4
Jorge Ferreira
EXEMPLO 3 – APLICAÇÃO COM INTEIROS – PROGRAMA SOMA
private void btcalcularActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int n1, n2, r;
n1 = Integer.parseInt(txtn1.getText());
n2 = Integer.parseInt(txtn2.getText());
r = n1 + n2;
txtr.setText(""+r);
private void btlimparActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
txtn1.setText("");
txtn2.setText("");
txtr.setText("");
private void btsairActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
5
Jorge Ferreira
EXEMPLO 4 – TRABALHANDO COM REAIS – PROGRAMA MÉDIA
private void brcalcularActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
double n1, n2, media;
n1 = Double.parseDouble(txtnota1.getText());
n2 = Double.parseDouble(txtnota2.getText());
media = (n1+n2)/2;
txtmedia.setText(""+media);
}
6
Jorge Ferreira
private void btlimparActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
txtnota1.setText("");
txtnota2.setText("");
txtmedia.setText("");
}
private void btsairActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
7
Jorge Ferreira
SOMANDO E USANDO INSTÂNCIA DE UMA CLASSE
public class Main {
/** Creates a new instance of Main */
int total;
int calc(int x, int y){
total = x + y;
return total;
}
public Main() {
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
8
Jorge Ferreira
private void btcalcularActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Main m = new Main();
int n1, n2;
n1 = Integer.parseInt(txtn1.getText());
n2 = Integer.parseInt(txtn2.getText());
txtr.setText("" + m.calc(n1,n2));
}
private void btlimparActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
txtn1.setText("");
txtn2.setText("");
txtr.setText("");
}
private void btsairActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
9
Jorge Ferreira
DESVIO TIPO if
Sintaxe:
if (condição) {
instruções
} else {
instruções
}
COMPARADORES
(a = = b) – igualdade
(a != b) – diferentes
(a > b) – maior que
(a < b) – menor que
( a > = b) – maior ou igual a
( a < = ) – menor ou igual a
OPERADORES LÓGICOS
&& - AND – E
| | - OR – OU
^ - OR – OU EXCLUSIVO
10
Jorge Ferreira
EXEMPLO 6 – CALCULANDO MÉDIA E SITUAÇÃO
private void btcalcularActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
double n1, n2, media;
String situacao;
n1 = Integer.parseInt(txtnota1.getText());
n2 = Integer.parseInt(txtnota2.getText());
media = (n1+n2)/2;
if (media >= 7){
situacao = "APROVADO";
}
else{
situacao = "REPROVADO";
}
txtmedia.setText("" + media);
txtsit.setText(situacao);
}
private void btlimparActionPerformed(java.awt.event.ActionEvent evt) {
11
Jorge Ferreira
12
// TODO add your handling code here:
txtnota1.setText("");
txtnota2.setText("");
txtmedia.setText("");
txtsit.setText("");
}
private void btsairActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
EXEMPLO 7
Considere o programa que leia dois valores inteiros, e, independentemente da ordem em
que foram fornecidos, deverão ser impressos na ordem crescente.
Algoritmo
1. Ler um valor para a variável A
2. Ler um valor para a variável B
3. Verificar se o valor A é maior que o valor de B;
a. Se for verdadeiro, efetuar a troca dos valores;
4. Apresentar os valores das variáveis
Jorge Ferreira
Código do Programa:
private void btordenarActionPerformed(java.awt.event.ActionEvent evt) {
int n1,n2,aux;
n1 = Integer.parseInt(txtnum1.getText());
n2 = Integer.parseInt(txtnum2.getText());
if (n1>n2){
aux = n1;
n1 = n2;
n2 = aux;
}
txts1.setText(""+ n1);
txts2.setText(""+ n2);
}
private void btlimparActionPerformed(java.awt.event.ActionEvent evt) {
txtnum1.setText("");
txtnum2.setText("");
}
private void btsairActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
13
Jorge Ferreira
14
Programa Rodando:
EXEMPLO 8
Desenvolva um programa que efetue a leitura de três valores para os lados de um
triângulo, considerando lados como: A, B, C. Este programa deverá verificar se os lados
fornecidos formam realmente um triângulo, e se for esta condição verdadeira, deverá ser
indicado qual o tipo de triângulo foi formado: eqüilátero, isósceles ou escaleno.
Para estabelecer este algoritmo, é necessário, em primeiro lugar, saber o que realmente é
um triângulo. Triângulo é uma forma geométrica (polígono) composta por três lados, e
cada lado é menor que a soma dos outros dois lados. Perceba que isto é uma regra e
deverá ser considerada. É um triângulo quando A<B+C, quando B<A+C e quando
C<A+B.
Um triângulo é eqüilátero quando possui todos os lados iguais; é isósceles quando dois
lados são iguais e um é diferente; é escaleno quando possui todos os lados diferentes.
Algoritmo:
1234-
Ler três valores para os lados de um triângulo; A, B e C.
Verificar se cada lado é menor que a soma dos outros dois lados;
Sendo triângulo, verificar se é eqüilátero, isósceles ou escaleno;
Caso não seja triângulo, imprimir: “Não forma triângulo”.
Jorge Ferreira
Código do programa:
private void btcalcularActionPerformed(java.awt.event.ActionEvent evt) {
double A, B, C;
A = Double.parseDouble(txta.getText());
B = Double.parseDouble(txtb.getText());
C = Double.parseDouble(txtc.getText());
if(A<B+C && B<A+C && C<A+B){
if (A==B && B==C){
txtr.setText("Triângulo Equilátero");
}
else{
if(A==B || A==C || C==B){
txtr.setText("Triângulo Isósceles");
}
else{
txtr.setText("Triângulo Escaleno");
}
}
}
else{
txtr.setText("Não é Triângulo");
}
}
15
Jorge Ferreira
private void btlimparActionPerformed(java.awt.event.ActionEvent evt) {
txta.setText("");
txtb.setText("");
txtc.setText("");
txtr.setText("");
}
private void btsairActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
Programa Rodando:
EXEMPLO 9
DESVIO TIPO IF SEQÜENCIAL
Criar um programa, que fará a leitura de dois valores reais. O usuário escolherá a
operação, e o programa apresentará o resultado da operação escolhida.
Algoritmo:
1- Digitar dois valores do tipo real, um em cada campo.
2- Selecionar a operação desejada.
3- Apresentar o resultado da operação escolhida.
16
Jorge Ferreira
Programa Calculadora Rodando:
Código do Programa: Botão Calcular
private void btcalcularActionPerformed(java.awt.event.ActionEvent evt) {
double total = 0;
double n1 = Double.parseDouble(txtvalor1.getText());
double n2 = Double.parseDouble(txtvalor2.getText());
if (optadicao.isSelected()){
total = n1 + n2;
}
if (optsubtracao.isSelected()){
total = n1 - n2;
}
if (optmultiplicacao.isSelected()){
total = n1 * n2;
}
if (optdivisao.isSelected()){
if(n2==0)
total=0;
else
total = n1 / n2;
}
txtr.setText(""+ total);
}
17
Jorge Ferreira
Botão Sair:
private void btsairActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
18
This document was created with Win2PDF available at http://www.win2pdf.com.
The unregistered version of Win2PDF is for evaluation or non-commercial use only.
This page will not be added after purchasing Win2PDF.