Escolar Documentos
Profissional Documentos
Cultura Documentos
linguagem.
1 package com.exemplo;
2
3 import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
4 import javax.swing.text.PlainDocument;
5
6 public class TamanhoFixoJTextField extends PlainDocument {
7
8 private int tamMax;
9
1 public TamanhoFixoJTextField(int tamMax) {
0 super();
this.tamMax = tamMax;
1 }
1
1 public void insertString(int offset, String str, AttributeSet
2 attr)
1 throws BadLocationException {
3
1 if (str == null)
return;
4
1 //Define a condição para aceitar qualquer número de
5 caracteres
1 if (tamMax <= 0)
6 {
super.insertString(offset, str, attr);
1
return;
7 }
1
8 int tam = (getLength() + str.length());
1
9 //Se o tamanho final for menor, chama insertString()
2 aceitando a String
if (tam <= tamMax)
0
super.insertString(offset, str, attr);
2 }
1
2 }
2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
3
1
3
2
3
3
3
4
3
5
3
6
1 package com.exemplo;
2
3 import javax.swing.JFrame;
import javax.swing.JTextField;
4
5 public class TestandoJTextField extends JFrame {
6
7 private static final long serialVersionUID = 1L;
8
9 private JTextField txtExemplo;
1
0 public static void main(String[] args)
1 {
TestandoJTextField field = new TestandoJTextField();
1 field.testaJTextField();
1 }
2
1 private void testaJTextField() {
3 this.setTitle("Exemplo");
1 this.setSize(200, 180);
4
//Definimos o tamanho padrão do JTextField
1 txtExemplo = new JTextField(10);
5
1 //Passamos para o construtor o número máximo de caracteres
6 aceitos
1 txtExemplo.setDocument(new TamanhoFixoJTextField(5));
7
1 this.getContentPane().add(txtExemplo, "North");
8
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
1
9 setVisible(true);
2 }
0
2 }
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
3
1
3
2
3
3
3
4
3
5
1 package com.exemplo;
2
3 import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
4 import javax.swing.text.PlainDocument;
5
6 public class TamanhoFixoJTextField extends PlainDocument {
7
8 private int tamMax;
9
1 public TamanhoFixoJTextField(int tamMax) {
0 super();
this.tamMax = tamMax;
1 }
1
1 public void insertString(int offset, String str, AttributeSet
2 attr)
1 throws BadLocationException {
3
1 if (str == null)
return;
4
1 //Define a condição para aceitar qualquer número de
5 caracteres
1 if (tamMax <= 0)
6 {
super.insertString(offset, str, attr);
1 return;
}
7
1
int tam = (getLength() + str.length());
8
1 //Se o tamanho final for menor, chama insertString()
9 aceitando a String
2 if (tam <= tamMax) {
0 super.insertString(offset, str, attr);
} else {
2 //Caso contrário, limita a string e envia para
1 insertString() que aceita a string
2 if (getLength() == tamMax) return;
2 String novaStr = str.substring(0, (tamMax -
2 getLength()));
super.insertString(offset, novaStr, attr);
3 }
2 }
4
2 }
5
2
6
2
7
2
8
2
9
3
0
3
1
3
2
3
3
3
4
3
5
3
6
3
7
3
8
3
9
4
0
4
1
4
2
1 package com.exemplo;
2
3 import java.awt.Container;
4 import java.text.ParseException;
5
6 import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
7 import javax.swing.JLabel;
8 import javax.swing.text.MaskFormatter;
9
1 public class TestandoJFormattedTextField extends JFrame {
0
1 private static final long serialVersionUID = 1L;
1
1 public static void main(String[] args)
{
2 TestandoJFormattedTextField field = new
1 TestandoJFormattedTextField();
3 field.testaJFormattedTextField();
1 }
4
private void testaJFormattedTextField() {
1
Container janela = getContentPane();
5 setLayout(null);
1
6 //Define os rótulos dos botões
1 JLabel labelCep = new JLabel("CEP: ");
7 JLabel labelTel = new JLabel("Telefone: ");
JLabel labelCpf = new JLabel("CPF: ");
1 JLabel labelData = new JLabel("Data: ");
8 labelCep.setBounds(50,40,100,20);
1 labelTel.setBounds(50,80,100,20);
9 labelCpf.setBounds(50,120,100,20);
2 labelData.setBounds(50,160,100,20);
0
//Define as máscaras
2 MaskFormatter mascaraCep = null;
1 MaskFormatter mascaraTel = null;
2 MaskFormatter mascaraCpf = null;
2 MaskFormatter mascaraData = null;
2
3 try{
mascaraCep = new MaskFormatter("#####-###");
2 mascaraTel = new MaskFormatter("(##)####-####");
4 mascaraCpf = new MaskFormatter("#########-##");
2 mascaraData = new MaskFormatter("##/##/####");
5 mascaraCep.setPlaceholderCharacter('_');
mascaraTel.setPlaceholderCharacter('_');
2
mascaraCpf.setPlaceholderCharacter('_');
6 mascaraData.setPlaceholderCharacter('_');
2 }
7 catch(ParseException excp) {
2 System.err.println("Erro na formatação: " +
excp.getMessage());
8 System.exit(-1);
2 }
9
3 //Seta as máscaras nos objetos JFormattedTextField
0 JFormattedTextField jFormattedTextCep = new
3 JFormattedTextField(mascaraCep);
JFormattedTextField jFormattedTextTel = new
1 JFormattedTextField(mascaraTel);
3 JFormattedTextField jFormattedTextCpf = new
JFormattedTextField(mascaraCpf);
2 JFormattedTextField jFormattedTextData = new
3 JFormattedTextField(mascaraData);
3 jFormattedTextCep.setBounds(150,40,100,20);
3 jFormattedTextTel.setBounds(150,80,100,20);
4 jFormattedTextCpf.setBounds(150,120,100,20);
jFormattedTextData.setBounds(150,160,100,20);
3
5 //Adiciona os rótulos e os campos de textos com
3 máscaras na tela
6 janela.add(labelCep);
3 janela.add(labelTel);
7 janela.add(labelCpf);
janela.add(labelData);
3 janela.add(jFormattedTextCep);
8 janela.add(jFormattedTextTel);
3 janela.add(jFormattedTextCpf);
9 janela.add(jFormattedTextData);
setSize(400, 250);
4
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
0 setVisible(true);
4 }
1
4 }
2
4
3
4
4
4
5
4
6
4
7
4
8
4
9
5
0
5
1
5
2
5
3
5
4
5
5
5
6
5
7
5
8
5
9
6
0
6
1
6
2
6
3
6
4
6
5
6
6
6
7
6
8
6
9
7
0
7
1
7
2
7
3
7
4
7
5
7
6
7
7
7
8
7
9
8
0
Se tentarmos entrar com letras onde apenas se aceita número veremos que os
caracteres não serão aceitos no campo.
1. import javax.swing.JOptionPane;
2. public class Media {
3. public static void main(String[] args) {
4.
5. int quantidadeFuncionarios = 0;
6. float salarioFuncionario = 0;
7. float totalSalarios = 0;
8. float mediaSalarial = 0;
9. //variável contadora para laço
10. int contadora = 0;
11.
12. quantidadeFuncionarios = Integer.parseInt(JOptionPane.showInputDialog(nu
ll,"Digite a quantidade de funcionários","Número de funcionários",JOptionPane.QUES
TION_MESSAGE));
13.
14. while (contadora < quantidadeFuncionarios){
15. contadora++;
16. salarioFuncionario = Float.parseFloat(JOptionPane.showInputDialog(nul
l,"Digite o salário do funcionário","Salário",JOptionPane.QUESTION_MESSAGE));
17. totalSalarios = totalSalarios + salarioFuncionario;
18. }
19.
20. mediaSalarial = totalSalarios / quantidadeFuncionarios;
21. System.out.println("Média Salarial = " + mediaSalarial);
22.
23. System.exit(0);
24. }
25.
26. }
Código % aumento
1 10
3 25
4 30
8 50
1. import javax.swing.JOptionPane;
2. public class Porcentagem {
3. public static void main(String[] args) {
4.
5. int codigoTaxaAumento;
6. float valorProduto;
7.
8.
9. valorProduto = Float.parseFloat(JOptionPane.showInputDialog(null,"R$","V
alor do produto",JOptionPane.QUESTION_MESSAGE));
10. codigoTaxaAumento = Integer.parseInt(JOptionPane.showInputDialog(null,"C
ódigo","Código de taxa do aumento",JOptionPane.QUESTION_MESSAGE));
11.
12. switch (codigoTaxaAumento) {
13. case 1: valorProduto = valorProduto + (valorProduto * 10 / 100);
14. JOptionPane.showMessageDialog(null,"R$ " + valorProduto,"Valor do
produto com taxa de aumento",JOptionPane.PLAIN_MESSAGE);
15. break;
16.
17. case 3: valorProduto = valorProduto + (valorProduto * 25 / 100);
18. JOptionPane.showMessageDialog(null,"R$ " + valorProduto,"Valor do produt
o com taxa de aumento",JOptionPane.PLAIN_MESSAGE);
19. break;
20.
21. case 4: valorProduto = valorProduto + (valorProduto * 30 / 100);
22. JOptionPane.showMessageDialog(null,"R$ " + valorProduto,"Valor do produt
o com taxa de aumento",JOptionPane.PLAIN_MESSAGE);
23. break;
24.
25. case 8: valorProduto = valorProduto + (valorProduto * 50 / 100);
26. JOptionPane.showMessageDialog(null,"R$ " + valorProduto,"Valor do produt
o com taxa de aumento",JOptionPane.PLAIN_MESSAGE);
27. break;
28.
29. default: JOptionPane.showMessageDialog(null,"Código" + codigoTaxaAumento
,"Código de taxa de aumento desconhcido",JOptionPane.PLAIN_MESSAGE);
30. break;
31. }
32. System.exit(0);
3) Criar um programa para cálculo do salário líquido em que três valores devem
ser informados pelo usuário em janelas de entrada: a quantidade de horas
trabalhadas, o salário hora e o número de dependentes. O programa deve
mostrar em janela de saída as informações contidas no lado esquerdo da tabela
seguinte:
Informação Cálculos
Salário bruto Horas trabalhadas * salário hora + (50 * número de
dependentes)
1. import javax.swing.JOptionPane;
2.
3. public class Rh {
4.
5. public static void main( String args[] )
6. {
7.
8. String ND, SH, HT;
9. int nd;
10. float sh, ht, dIR, sb;
11. double dINSS, sl;
12.
13. ND=
14. JOptionPane.showInputDialog
15. (null,"Digite número de dependentes","Número de Dependentes",
16. JOptionPane.QUESTION_MESSAGE);
17.
18. nd = Integer.parseInt(ND);
19.
20. SH=
21. JOptionPane.showInputDialog
22. (null,"Digite salário hora","Salário Hora",
23. JOptionPane.QUESTION_MESSAGE);
24.
25. sh = Float.parseFloat(SH);
26.
27. HT=
28. JOptionPane.showInputDialog
29. (null,"Digite número de horas trabalhadas","Número de Horas Trabalhadas",
30. JOptionPane.QUESTION_MESSAGE);
31.
32. ht = Float.parseFloat(HT);
33.
34. sb = ht*sh+(50*nd);
35.
36. {JOptionPane.showMessageDialog (
37. null, "Salário Bruto" +sb , "Salário Bruto",
38. JOptionPane.INFORMATION_MESSAGE );}
39.
40. if (sb<=1000)
41.
42. dINSS = sb*8.5/100;
43.
44. else
45.
46. dINSS = sb*9/100;
47.
48. {JOptionPane.showMessageDialog (
49. null, "Desconto do INSS" +dINSS , "Desconto do INSS",
50. JOptionPane.INFORMATION_MESSAGE );}
51.
52. if (sb<=500)
53.
54. dIR = 0;
55.
56. if (sb>500 && sb<=1000)
57.
58. dIR = sb*5/100;
59.
60. else
61.
62. dIR = sb*7/100;
63.
64. {JOptionPane.showMessageDialog (
65. null, "Desconto do IR" +dIR , "Desconto do IR",
66. JOptionPane.INFORMATION_MESSAGE );}
67.
68. sl = sb-dINSS-dIR;
69.
70. {JOptionPane.showMessageDialog (
71. null, "Salário Líquido" +sl , "Salário Líquido",
72. JOptionPane.INFORMATION_MESSAGE );
73. System.exit( 0 );}
74.
75. }
76. }
1. import javax.swing.*;
2. public class Senha4 {
3. public static void main(String[] args) {
4. String cadastroSenha;
5. String confirmaSenha;
6. double a;
7. double b;
8.
9. cadastroSenha = JOptionPane.showInputDialog(null,"Senha","",JOptionPane.
QUESTION_MESSAGE);
10.
11. a = Double.parseDouble(JOptionPane.showInputDialog(null,"Primeiro número
","",JOptionPane.QUESTION_MESSAGE));
12. b = Double.parseDouble(JOptionPane.showInputDialog(null,"Segundo número
","",JOptionPane.QUESTION_MESSAGE));
13.
14. confirmaSenha = JOptionPane.showInputDialog(null,"Digite sua senha","",J
OptionPane.QUESTION_MESSAGE);
15.
16. if (confirmaSenha.equals(cadastroSenha)){
17. System.out.println(a/b);
18. }else{
19. System.out.println("Senha incorreta");
20. }
21.
22. System.exit(0);
23. }
24.
25. }
5) Implementar programa que realize uma das 4 operaçoes (+), (-), (/) e (*)
entre duas variáveis, através da escolha do usuário.
1. import javax.swing.JOptionPane;
2.
3. public class Operacoes{
4.
5. public static void main( String args[] )
6. {
7. //APRESENTAÇÃO DAS VARIAVEIS
8.
9. String a, b, escolha;
10. int es;
11. float c, d, e;
12.
13.
14. //DEFINIÇÃO DAS VARIAVEIS
15.
16. escolha = JOptionPane.showInputDialog ("Digite 0 para soma, \n Digite 1 par
a subtraçao, \n Digite 2 para divisao, \n Digite 3 para multiplicacao");
17. es = Integer.parseInt(escolha);
18. a = JOptionPane.showInputDialog ("Digite o primeiro numero");
19. c = Float.parseFloat(a);
20. b = JOptionPane.showInputDialog ("Digite o segundo numero");
21. d = Float.parseFloat(b);
22.
23.
24.
25. //SWITCH CASE
26.
27. switch (es)
28. {
29. case 0:
30. e = c + d;
31. JOptionPane.showMessageDialog(null, "Resultado da soma: " + e, "Feito", JO
ptionPane.PLAIN_MESSAGE );break;
32.
33. case 1:
34. e = c - d;
35. JOptionPane.showMessageDialog(null, "Resultado da subtracao: " + e, "Feit
o", JOptionPane.PLAIN_MESSAGE );break;
36.
37. case 2:
38. e = c / d;
39. JOptionPane.showMessageDialog(null, "Resultado da divisao: " + e, "Feito",
JOptionPane.PLAIN_MESSAGE );break;
40.
41. case 3:
42. e = c * d;
43. JOptionPane.showMessageDialog(null, "Resultado da multiplicacao: " + e, "F
eito", JOptionPane.PLAIN_MESSAGE );break;
44.
45. }
46. System.exit(0);
47. }
48. }