Conversor Cº > F°

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Conversor extends JFrame implements ActionListener {
    private JLabel celsiusLabel, fahrenheitLabel;
    private JTextField celsiusField, fahrenheitField;
    private JButton converterButton;
    
    public Conversor() {
        super("Conversor de Celsius para Fahrenheit");

        // Configurando o layout
        setLayout(new GridLayout(2, 2));

        // Adicionando o JLabel e o JTextField para Celsius
        celsiusLabel = new JLabel("Celsius:");
        add(celsiusLabel);
        celsiusField = new JTextField(10);
        add(celsiusField);

        // Adicionando o JLabel e o JTextField para Fahrenheit
        fahrenheitLabel = new JLabel("Fahrenheit:");
        add(fahrenheitLabel);
        fahrenheitField = new JTextField(10);
        add(fahrenheitField);

        // Adicionando o botão de conversão
        converterButton = new JButton("Converter");
        add(converterButton);
        converterButton.addActionListener(this);
    }

    // Método para converter graus Celsius em Fahrenheit
    private double converterCelsiusParaFahrenheit(double celsius) {
        return celsius * 1.8 + 32;
    }

    // Evento de clique do botão
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == converterButton) {
            // Obter o valor em Celsius
            String celsiusString = celsiusField.getText();
            double celsius = Double.parseDouble(celsiusString);

            // Converter Celsius para Fahrenheit
            double fahrenheit = converterCelsiusParaFahrenheit(celsius);

            // Mostrar resultado em Fahrenheit
            fahrenheitField.setText(String.format("%.2f", fahrenheit));
        }
    }

    public static void main(String[] args) {
        Conversor conversor = new Conversor();

        // Configurando a janela
        conversor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        conversor.setSize(300, 100);
        conversor.setVisible(true);
    }
}

Neste exemplo, o usuário digita o valor em graus Celsius no campo de texto e, ao clicar no botão "Converter", o programa converte esse valor para graus Fahrenheit e exibe o resultado no segundo campo de texto. O método converterCelsiusParaFahrenheit() realiza a conversão de Celsius para Fahrenheit e o método actionPerformed() é executado quando o botão é clicado, obtendo o valor em Celsius, faz a conversão e exibe o resultado em Fahrenheit no campo de texto correspondente.

Last updated