Pregunta

Estoy escribiendo un convertidor de divisas pero estoy teniendo un poco de problemas caculating la tasa de cambio de cada moneda. Básicamente quiero que el usuario seleccione un Currecy primero y luego entrar en una cantidad y pulse el botón "ir" para calcular la tarifa. pero estoy teniendo problemas con los oyentes en JMenuItem y JButton. He declarado dos oyentes para menuItem y JButton. ¿Cómo uso el oyente en el botón para mirar hacia fuera para la selección realizada en el menuIten para que haga el cálculo Currecy derecho?

gracias.

CÓDIGO:

    private class selectionListener implements ActionListener
    {
        double EuroToSterling(double euro)
        {
            double total = Double.parseDouble(amountField.getText());
            return total;
        }
        public void actionPerformed(ActionEvent e)
        {
            if (e.getActionCommand().equals("Euros"))
               // result = EuroToSterling(10*euro);
                currencyMenu.setLabel("Euros");
               // answerLabel.setText("this" + EuroToSterling(1.22*2));

            if (e.getActionCommand().equals("Japanese Yen"))
                currencyMenu.setLabel("Japanese Yen");

        }
    }



    private class GoButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent evt)
        {

//please help with this section
¿Fue útil?

Solución

Trate de hacer esto con los euros. Debe darle un lugar para empezar.


/*
 *
 * Currency converting
 *
 */

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;

import javax.swing.UIManager;

public class CurrencyConverterWin extends JFrame {

    private JLabel promptLabel;
    private JTextField amountField;
    private JButton goButton;
    private JPanel inputPanel;
    private JPanel answerPanel;
    private JLabel answerLabel;
    private JLabel selectLabel;
    private JComboBox currencyMenuBar;
    private JPanel menuPanel;
    private double result = 0.0;
    private double euro = 1.22257;
    private double japYen = 152.073;
    private double rusRuble = 42.5389;
    private double usd = 1.5577;

    public CurrencyConverterWin() {
        super();
        this.setSize(500, 200);
        this.setTitle("Currency Converter Window");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.setLayout(new GridLayout(3, 1));

        this.selectLabel = new JLabel("Select a currency to convert to: ", JLabel.RIGHT);
        this.answerLabel = new JLabel(" ", JLabel.CENTER);

        currencyMenuBar = new JComboBox(new String[]{"Euros","Japanese Yen","Russian Rubles","US Dollars"});

        this.menuPanel = new JPanel();
        this.menuPanel.add(this.selectLabel);
        this.menuPanel.add(this.currencyMenuBar);
        this.add(this.menuPanel);

        this.promptLabel = new JLabel("(select a currency first) ", JLabel.RIGHT);
        this.answerLabel = new JLabel(" ", JLabel.CENTER);

        this.amountField = new JTextField("", 8);
        this.goButton = new JButton("GO");
        goButton.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonClicked(evt);
            }
        });

        this.inputPanel = new JPanel();
        this.inputPanel.add(this.promptLabel);
        this.inputPanel.add(this.amountField);
        this.inputPanel.add(this.goButton);

        this.add(this.inputPanel);

        this.answerPanel = new JPanel();
        this.answerPanel.add(this.answerLabel);
        this.add(this.answerPanel);
    }

    double EuroToSterling() {
        double total = Double.parseDouble(amountField.getText()) * euro;
        return total;
    }

    double JapYenToSterling()
    {
        double japToSterlingTotal = Double.parseDouble(amountField.getText()) * japYen;
        return japToSterlingTotal;
    }


//String currencyEntered = yearField.getText();
    public void buttonClicked(ActionEvent evt) {
        if(currencyMenuBar.getSelectedItem().equals("Euros"))
        {
            answerLabel.setText(EuroToSterling() + " Euros");
        }
        if(currencyMenuBar.getSelectedItem().equals("Japanese Yen"))
        {
            answerLabel.setText(JapYenToSterling() + " Japanese Yen");
        }
    }

    public static void main(String[] args) {        
        try{UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");}
        catch (Exception e){e.printStackTrace();}
        CurrencyConverterWin win = new CurrencyConverterWin();
        win.setVisible(true);
    }
}

Otros consejos

El método usual es que el oyente menú cambia el estado de la aplicación (es decir, llama a un método que salvará el tipo de cambio en un campo).

A continuación, el código de cálculo puede leer este valor y utilizarlo.

También sugeriría que utilice un JComboBox para almacenar las monedas. Para ello se crea un objeto para almacenar tanto el nombre de la moneda y la tasa de conversión. Luego, cuando es necesario calcular la cantidad convertida a sacar el elemento seleccionado en el combo y utiliza su tasa de conversión de la operación. Con este enfoque se puede ampliar fácilmente el número de monedas que usted apoya.

Salida: Cómo Mapa utilización como elemento de texto de una JComboBox para un ejemplo para conseguir que inicie en el uso de un objeto en el cuadro combinado.

Yo añadiría personalmente en una enumeración para indicar el tipo de conversión de moneda. por ejemplo:

public enum ConversionType {
   DOLLARS,
   EUROS,
   RUBLES
   //ETC...
}

El uso de este, puede mantener una variable de estado en la clase:

private ConversionType fromType;

Esto es lo que se propuso en su oyente selección.

A partir de ahí es una cuestión de hacer las conversiones diferentes en su oyente de acción basado en la variable de estado (fromType). Algo como esto:

if( fromType== EUROS ) {
 convertEurosToSterling( value1, value2 );
} 

Esta es una especie de un enfoque general -. Espero que esto ayude

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top