1.
Faça um programa que com a manipulação do JComboBox modifique o texto
de um label. Tome como exemplo a imagem abaixo.
R: /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-
default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to
edit this template
*/
package charevelacao;
/**
*
* @author CGTI
*/
public class jogo extends javax.swing.JFrame {
/**
* Creates new form jogo
*/
public jogo() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jLabel1 = new javax.swing.JLabel();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jRadioButton3 = new javax.swing.JRadioButton();
jLabel2 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Qual sexo você acha que o bebê é?");
jRadioButton1.setText("Menino");
jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton1ActionPerformed(evt);
}
});
jRadioButton2.setText("Menina");
jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton2ActionPerformed(evt);
}
});
jRadioButton3.setText("Não sei");
jRadioButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton3ActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N
jLabel2.setText("CHÁ REVELAÇÃO");
jButton1.setText("Limpar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel3.setText("jLabel3");
javax.swing.GroupLayout layout = new
javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(90, 90, 90)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEA
DING)
.addComponent(jButton1)
.addComponent(jLabel2)
.addComponent(jLabel1)
.addGroup(layout.createSequentialGroup()
.addComponent(jRadioButton2)
.addGap(102, 102, 102)
.addComponent(jLabel3))
.addComponent(jRadioButton3)
.addComponent(jRadioButton1))
.addContainerGap(108, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(17, 17, 17)
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addGap(27, 27, 27)
.addComponent(jRadioButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BAS
ELINE)
.addComponent(jRadioButton2)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jRadioButton3)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(69, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
}
private void jRadioButton3ActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code
(optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default
look and feel.
* For details see
http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(jogo.class.getName()).log(java.util.logging.Le
vel.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(jogo.class.getName()).log(java.util.logging.Le
vel.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(jogo.class.getName()).log(java.util.logging.Le
vel.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(jogo.class.getName()).log(java.util.logging.Le
vel.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new jogo().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JRadioButton jRadioButton3;
// End of variables declaration
2. Escreva um programa em Java para ler: a) o nome de um estudante e b) 4
notas referente às avaliações realizadas no semestre. O programa deve
calcular e escrever a média ponderada (mostrando em um Label),
considerando os seguintes pesos: nota1 com peso 2,0; nota2 com peso 1,0;
nota3 com peso 2,0 e nota4 com peso 5,0. Se a média final for maior que 6,0
mostrar uma janela com a mensagem “APROVADO”. Se a média for menor
que 6,0 e maior que 3,0, mostrar a mensagem “EXAME”, e se a média for
menor que 3,0 mostrar a mensagem “REPROVADO”.
R:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ViceTonio extends JFrame {
private JTextField nomeField;
private JTextField nota1Field;
private JTextField nota2Field;
private JTextField nota3Field;
private JTextField nota4Field;
private JLabel resultadoLabel;
public calcularMedia() {
super("Calculadora da Média");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
nomeField = new JTextField(20);
nota1Field = new JTextField(5);
nota2Field = new JTextField(5);
nota3Field = new JTextField(5);
nota4Field = new JTextField(5);
resultadoLabel = new JLabel();
JButton calcularButton = new JButton("Calcular Média");
calcularButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
calcularMedia();
}
});
JPanel panel = new JPanel(new GridLayout(6, 2));
panel.add(new JLabel("Nome:"));
panel.add(nomeField);
panel.add(new JLabel("Nota 1:"));
panel.add(nota1Field);
panel.add(new JLabel("Nota 2:"));
panel.add(nota2Field);
panel.add(new JLabel("Nota 3:"));
panel.add(nota3Field);
panel.add(new JLabel("Nota 4:"));
panel.add(nota4Field);
panel.add(calcularButton);
panel.add(resultadoLabel);
getContentPane().add(panel);
pack();
setVisible(true);
}
private void calcularMedia() {
String nome = nomeField.getText();
double nota1 = Double.parseDouble(nota1Field.getText());
double nota2 = Double.parseDouble(nota2Field.getText());
double nota3 = Double.parseDouble(nota3Field.getText());
double nota4 = Double.parseDouble(nota4Field.getText());
double media = (nota1 * 2.0 + nota2 * 1.0 + nota3 * 2.0 + nota4 * 5.0) / 10.0;
if (media > 6.0) {
resultadoLabel.setText("APROVADO");
} else if (media > 3.0) {
resultadoLabel.setText("EXAME");
} else {
resultadoLabel.setText("REPROVADO");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new calculadoraMedia();
}
});
}
}
3. Desenvolva um aplicativo em Java que leia o salário e o cargo (ComboBox)
de vários funcionários e calcule o seu salário reajustado de acordo com a
tabela apresentada a seguir. Caso o salário informado seja maior que R$
1.000,00, exibir a mensagem “Salário acima do valor permitido”, caso
contrário, exiba uma mensagem com o nome do funcionário, seu cargo, o
salário anterior e o salário reajustado.
R: import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
public class ReajusteSalarioApp extends JFrame {
private JLabel labelNome = new JLabel("Nome do Funcionário:");
private JTextField fieldNome = new JTextField(20);
private JLabel labelCargo = new JLabel("Cargo:");
private JComboBox<String> comboCargo;
private JLabel labelSalario = new JLabel("Salário:");
private JTextField fieldSalario = new JTextField(10);
private JButton buttonCalcular = new JButton("Calcular");
private JTextArea textAreaResultados = new JTextArea(10, 30);
private Map<String, Double> tabelaReajuste = new HashMap<>();
public ReajusteSalarioApp() {
tabelaReajuste.put("Gerente", 0.06);
tabelaReajuste.put("Analista", 0.02);
tabelaReajuste.put("Assistente", 0.01);
comboCargo = new JComboBox<>(tabelaReajuste.keySet().toArray(new
String[0]));
setLayout(new FlowLayout());
add(labelNome);
add(fieldNome);
add(labelCargo);
add(comboCargo);
add(labelSalario);
add(fieldSalario);
add(buttonCalcular);
add(new JScrollPane(textAreaResultados));
buttonCalcular.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
calcularReajuste();
}
});
setTitle("Reajuste de Salário");
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void calcularReajuste() {
String nome = fieldNome.getText();
String cargo = (String) comboCargo.getSelectedItem();
double salario = Double.parseDouble(fieldSalario.getText());
double reajuste = tabelaReajuste.get(cargo);
double salarioReajustado = salario + (salario * reajuste);
if (salario > 1000) {
textAreaResultados.setText("Salário acima do valor permitido.");
} else {
String resultado = "Nome: " + nome + "\nCargo: " + cargo +
"\nSalário Anterior: R$" + salario +
"\nSalário Reajustado: R$" + salarioReajustado;
textAreaResultados.setText(resultado);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ReajusteSalarioApp();
}
});
}
}
4. Escreva um programa capaz de converter o valor em Reais fornecido numa
caixa de entrada (TextField) em outro valor monetário conforme a seleção de
uma moeda (no mínimo 3 moedas diferentes) numa caixa de seleção (Combo)
indicando o resultado em um rótulo (Label). Se necessário adicione botões.
R: import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
public class ConversorMoedasApp extends JFrame {
private JTextField valorTextField;
private JComboBox<String> moedaComboBox;
private JLabel resultadoLabel;
private static final double DOLAR_RATE = 5.50;
private static final double EURO_RATE = 6.50;
private static final double LIBRA_RATE = 7.50;
public ConversorMoedasApp() {
setTitle("Conversor de Moedas");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
setLayout(new GridLayout(4, 1));
valorTextField = new JTextField();
moedaComboBox = new JComboBox<>(new String[]{"Dólar", "Euro", "Libra"});
resultadoLabel = new JLabel("");
JButton converterButton = new JButton("Converter");
converterButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
double valorEmReais = Double.parseDouble(valorTextField.getText());
String moedaSelecionada = (String) moedaComboBox.getSelectedItem();
double valorConvertido = 0;
switch (moedaSelecionada) {
case "Dólar":
valorConvertido = valorEmReais * DOLAR_RATE;
break;
case "Euro":
valorConvertido = valorEmReais * EURO_RATE;
break;
case "Libra":
valorConvertido = valorEmReais * LIBRA_RATE;
break;
}
DecimalFormat df = new DecimalFormat("#.##");
resultadoLabel.setText("Valor convertido: " + df.format(valorConvertido) + " " +
moedaSelecionada);
} catch (NumberFormatException ex) {
resultadoLabel.setText("Insira um valor válido.");
}
}
});
add(new JLabel("Valor em Reais:"));
add(valorTextField);
add(new JLabel("Moeda de conversão:"));
add(moedaComboBox);
add(converterButton);
add(resultadoLabel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ConversorMoedasApp().setVisible(true);
}
});
}
}