How to change a Jbutton's function on clicking another Jbutton? - java

I am writing a program which will convert weight in pounds to kilograms and also weight in Kilograms to pounds. The output window is as follows:
When I want to convert Kilograms to Pounds I click switch button and the output changes as follows:
But the problem is when I click "Convert" it still converts weight to Kilogram instead of Pounds.
I want the "Convert" button's function to change when I click the "Switch" button so it will convert the weight in Kilograms to pounds. Please help.
My source code is as follows:
public class convertApp extends JFrame implements ActionListener {
private JLabel poundlbl = new JLabel("Weight in Pounds");
private JLabel kglbl = new JLabel("Weight in Kilograms");
private JTextField poundbx= new JTextField(12);
private JTextField kgbx= new JTextField(12);
private JButton conbtn=new JButton("Convert");
private JButton switchbtn=new JButton("Switch");
private JButton newconbtn=new JButton("Convert");
private JPanel bxPanel = new JPanel();
public convertApp(){
super("Weight Converter");
bxPanel.setLayout(new GridLayout(5,29,5,5));
bxPanel.add(poundlbl);
bxPanel.add(poundbx);
bxPanel.add(kglbl);
bxPanel.add(kgbx);
bxPanel.add(conbtn);
bxPanel.add(switchbtn);
//bxPanel.setBackground(Color.gray);
this.setLayout(new GridLayout(1,1,0,0));
this.add(bxPanel);
this.setVisible(true);
//what to do if i close
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//put window in the center
this.setLocationRelativeTo(null);
//disable resize
this.setResizable(false);
//pack all the components within the window
this.pack();
conbtn.addActionListener(this);
switchbtn.addActionListener(this);
}
public void actionPerformed(ActionEvent evnt){
if(evnt.getSource()==conbtn){
String poundtext = poundbx.getText();
int pound = Integer.parseInt(poundtext);
double kilo = pound * 0.453592;
kgbx.setText(""+kilo);
}
else if(evnt.getSource()==switchbtn)
{
poundlbl.setText("Weight in Kilograms:");
kglbl.setText("Weight in Pounds:");
if(evnt.getSource()==conbtn){
String kilotext = poundbx.getText();
int kilo = Integer.parseInt(kilotext);
double pound = kilo * 2.20462;
kgbx.setText(""+pound);
}
}
}
}

Create boolean Variable
boolean switch=true;
void kiloGramToPound{
//Convert Codes Here
}
void PoundToKiloGram{
//Convert Codes Here
}
Convert Button actionPerformed
if(switch==true){
kiloGramToPound();
}else{
PoundToKiloGram();
}
Switch Button actionPerformed
if(switch==true){
switch=false;
}else{
switch=true;
}

You cannot change the function itself. You can create a flag that sets true or false (your choice) when you click the 'switch' button. Then check the value of that flag when you click 'convert' and perform the appropriate conversion according to your flag convention.
i.e.
Boolean isPtoK = true;
// [...]
if(isPtoK){
// convert pounds to kilos
} else{
// kilos to pounds
}
I would create a separate function that switches the value of your flag when 'switch' is clicked.

Apologies for not answering your question, but may I suggest you to try KeyListener/KeyAdapter instead of the combination of ActionListeners and buttons.
Example:
textField1.addKeyListener(new ConverterListener(textField2, "2.20462"));
textField2.addKeyListener(new ConverterListener(textField1, "0.453592"));
class ConverterListener extends KeyAdapter {
JTextField destination;
String multiplier;
public ConverterListener(JTextField destination, String multiplier) {
this.destination = destination;
this.multiplier = multiplier;
}
#Override
public void keyReleased(KeyEvent e) {
JTextField source = (JTextField) e.getSource();
String result = convert(source.getText(), multiplier);
destination.setText(result);
}
private String convert(String value, String multiplier) {
String result = "0";
try {
double dblValue = value.isEmpty() ? 0d : Double.parseDouble(value);
double dblMultiplier = value.isEmpty() ? 0d : Double.parseDouble(multiplier);
result = Double.toString(dblValue * dblMultiplier);
} catch (Exception e) {
System.out.println(e);
}
return result;
}
}

Related

How to calculate number from two Jtextfield?

I'm designing a food ordering system which I need to get the input of cash that customer paid, then minus with the total price they need to pay to calculate the change. My JTextField can't show the correct answer for the change, it only show 0.0. I'm not sure what's the problem with my code. Hope that you all can help me. Appreciate your helps, thank you!
public Cash() {
init();
btnPay.addActionListener(this);
setVisible(true);
}
public String returnChange1() {
double change = 0.00 ;
double custPay;
String total = lblDisplayTotal.getText();
double a=Double.parseDouble(total);
if (!(txtCustPay.getText().isEmpty())){
custPay = Double.parseDouble(txtCustPay.getText());
change = custPay - a;
}
return String.valueOf(change);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(btnPay)) {
returnChange1();
}
}
public void init() {
txtChange = new JTextField(returnChange1());
txtChange.setSize(150, 30);
txtChange.setLocation(150, 250);
add(txtChange);
}
You are not assigning the function to the text field. In the button action, don't simply call the function, in this case what you should do is assign the function to the text field: txtChange.setText(returnChange1()), Also try to put a try and catch where you convert the text to double:
try{
double a = Double.parseDouble(total);
}catch(NumberFormatException e){
e.printStackTrace;
}
The above code is useful when the user mistakenly enters a character that is not a number.
public Cash() {
init();
btnPay.addActionListener(this);
setVisible(true);
}
public String returnChange1() {
double change = 0.00;
double custPay;
String total = lblDisplayTotal.getText();
double a = Double.parseDouble(total);
if (!(txtCustPay.getText().isEmpty())) {
custPay = Double.parseDouble(txtCustPay.getText());
change = custPay - a;
}
return String.valueOf(change);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(btnPay)) {
txtChange.setText(returnChange1());
}
}
public void init() {
txtChange = new JTextField(returnChange1());
txtChange.setSize(150, 30);
txtChange.setLocation(150, 250);
add(txtChange);
}

Enter button error in java swing

I'm doing a programming exercise.
Miles and kilometer converter.(both case)
However, If I input number and press "Enter", nothing happened.
I don't know what part I need to modify... :(
Help me please..
public class Grid1 extends JFrame{
private JLabel label1,label2;
private JTextField textField1,textField2;
private Container container;
private GridLayout grid1;
// set up GUI
public Grid1(){
super( "Miles to Km / Km to Mile" );
grid1 = new GridLayout( 2, 2 );
container = getContentPane();
container.setLayout( grid1 );
label1 = new JLabel("Mile");
container.add(label1);
textField1 = new JTextField("");
container.add( textField1 );
label2 = new JLabel("Kilometer");
container.add(label2);
textField2 = new JTextField( "" );
container.add( textField2 );
TextFieldHandler handler = new TextFieldHandler();
textField1.addActionListener(handler);
JButton submit = new JButton("Submit");
submit.addActionListener(handler);
setSize(300, 100);
setVisible(true);
}
private class TextFieldHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
float miles = 0, km = 0;
String string = "";
if(event.getSource() == textField1){
string = "textField1: " + event.getActionCommand();
km = miles * 1.609344f;
}else if(event.getSource() == textField2){
string = "textField2: " + event.getActionCommand();
miles = km / 1.609344f;
}
}
}
public static void main( String args[]){
Grid1 application = new Grid1();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
} // end class GridLayoutDemo
You should remove handler from variable textField1 if you need to update data from button click. And in handler class you shold store data into result field/label.
In your case it looks like:
private class TextFieldHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
// In both cases you should get value from textField,
// parse it and store computed values in another field
float miles = 0, km = 0;
try {
if(event.getSource() == textField1){
// Value form field stored in String, you should parse Integer from it
miles = Integer.parseInt(textField1.getText());
km = miles * 1.609344f;
textField2.setText(String.format("%f", km));
}else if(event.getSource() == textField2){
// Value form field stored in String, you should parse Integer from it
km = Integer.parseInt(textField2.getText());
miles = km / 1.609344f;
textField1.setText(String.format("%f", km));
}
} catch(NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Wrong value", "Input error");
}
}
}
Since you are working with a single frame and a single button, I would suggest to set the following line:
frame.getRootPane().setDefaultButton(submitButton);
You can set a default button on each frame you control, the button you set in this method, will automatically listen to enter and invoke your actionPerformed.
You can also use a KeyListener and extend the functionality for your button in this case or in future exercises or projects.
Hope it helps.
All the best... and happy coding :)

Calculating the total price

How do you calculate the total price of of groceries purchased? At the moment, I can only calculate only one of the grocery with its quantity.
Below are the classes that I have used:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.text.DecimalFormat;
/**
Long Distance Calls
*/
public class GroceryMain extends JFrame
{
private RatePanel ratePanel; // A panel for rates
private QuantityPanel quantityPanel; // A panel for minutes
private JPanel buttonPanel; // A panel for the buttons
private JButton calcButton; // Calculates everything
private JButton exitButton; // Exits the application
/**
Constructor
*/
public GroceryMain()
{
// Display a title.
setTitle("Grocery Shop");
// Specify what happens when the close button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a RatePanel object.
ratePanel = new RatePanel();
// Create a MinutesPanel object.
quantityPanel = new QuantityPanel();
// Build the panel that contains the buttons.
buildButtonPanel();
// Add the panels to the content pane.
add(ratePanel, BorderLayout.WEST);
add(quantityPanel, BorderLayout.EAST);
add(buttonPanel, BorderLayout.SOUTH);
// Pack and display the window.
pack();
setVisible(true);
}
/**
The buildButtonPanel method creates a panel containing
buttons.
*/
private void buildButtonPanel()
{
// Create a button to calculate the charges.
calcButton = new JButton("Calculate Charges");
// Add an action listener to the button.
calcButton.addActionListener(new CalcButtonListener());
// Create a button to exit the application.
exitButton = new JButton("Exit");
// Add an action listener to the button.
exitButton.addActionListener(new ExitButtonListener());
// Put the buttons in their own panel.
buttonPanel = new JPanel();
buttonPanel.add(calcButton);
buttonPanel.add(exitButton);
}
/**
CalcButtonListener is an action listener class for the
calcButton component.
*/
private class CalcButtonListener implements ActionListener
{
/**
actionPerformed method
#param e An ActionEvent object.
*/
public void actionPerformed(ActionEvent e)
{
double rate; // Applicable rate
double totalCharges; // Total charges
// Create a DecimalFormat object to format output.
DecimalFormat dollar = new DecimalFormat("#,##0.00");
// Get the applicable rate.
rate = ratePanel.getRate();
// Get the total charges
totalCharges = quantityPanel.getCharges(rate);
// Display the message.
JOptionPane.showMessageDialog(null, "Total Charges: £" +
dollar.format(totalCharges));
}
} // End of inner class
/**
ExitButtonListener is an action listener class for the
exitButton component.
*/
private class ExitButtonListener implements ActionListener
{
/**
actionPerformed method
#param e An ActionEvent object.
*/
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
} // End of inner class
/**
The main method creates an instance of the LongDistance
class, causing it to display its window.
*/
public static void main(String[] args)
{
GroceryMain ld = new GroceryMain();
}
}
import java.awt.*;
import javax.swing.*;
/**
MinutesPanel class
Long Distance Calls
*/
public class QuantityPanel extends JPanel
{
private JTextField quantity; // To get minutes
private JTextField quantity2; // To get minutes
private JTextField baked_beans_JT; // JTextField box for baked_beans
private JTextField Cornflakes_JT; // JTextField box for cornflakes
private JTextField Sugar_JT; // JTextField box for sugar box
private JTextField Tea_Bags_JT; // JTextField box for tea bag
private JTextField Instant_Coffee_JT; // JTextField box for Instant_Coffee_Box
private JTextField Bread_JT; // JTextField box for bread box
private JTextField Sausage_JT; // JTextField box for sausage box
private JTextField egg_JT; // JTextField box for egg box
private JTextField milk_JT; // JTextField box for milk
private JTextField potatoes_JT; // JTextField box for potatoes
/**
Constructor
*/
public QuantityPanel()
{
// Create a label prompting the user and a text field.
//JLabel minutesMsg = new JLabel("Quantity:");
quantity = new JTextField(5);
quantity2 = new JTextField(5);
baked_beans_JT = new JTextField(5);
Cornflakes_JT = new JTextField(5);
Sugar_JT = new JTextField(5);
Tea_Bags_JT = new JTextField(5);
Instant_Coffee_JT = new JTextField(5);
Bread_JT = new JTextField(5);
Sausage_JT = new JTextField(5);
egg_JT = new JTextField(5);
milk_JT = new JTextField(5);
potatoes_JT = new JTextField(5);
//initialize text field to 0
baked_beans_JT.setText("0");
Cornflakes_JT.setText("0");
Sugar_JT.setText("0");
Tea_Bags_JT.setText("0");
Instant_Coffee_JT.setText("0");
Bread_JT.setText("0");
Sausage_JT.setText("0");
egg_JT.setText("0");
milk_JT.setText("0");
potatoes_JT.setText("0");
// Create a GridLayout manager.
setLayout(new GridLayout(15, 1));
// Create a border.
setBorder(BorderFactory.createTitledBorder("QTY"));
// Add the labels and text fields to this panel.
//add(minutesMsg);
//add(quantity);
// add(quantity2);
add(baked_beans_JT);
add(Cornflakes_JT);
add(Sugar_JT);
add(Tea_Bags_JT);
add(Instant_Coffee_JT);
add(Bread_JT);
add(Sausage_JT);
add(egg_JT);
add(milk_JT);
add(potatoes_JT);
}
/**
The getCharges method uses the specified rate to calculate
the charges for the number of minutes entered.
#param rate The per-minute rate.
#return The charges for the number of minutes used.
*/
public double getCharges(double rate)
{
double charges = Double.parseDouble(baked_beans_JT.getText()) * rate;
return charges;
}
}
import java.awt.*;
import javax.swing.*;
import java.text.DecimalFormat;
/**
RatePanel class
Long Distance Calls
*/
public class RatePanel extends JPanel
{
// Named constants for rates
private final double BAKED_BEANS= 0.35;
private final double CORNFLAKES = 1.75;
private final double SUGAR = 0.75;
private final double TEA_BAGS = 1.15;
private final double INSTANT_COFFEE = 2.50;
private final double BREAD = 1.25;
private final double SAUSAGES = 1.30;
private final double EGGS = 0.75;
private final double MILK = 0.65;
private final double POTATOES = 2.00;
private JCheckBox bakedbeans; // Radio button for daytime rate
private JCheckBox cornflakes; // Radio button for evening rate
private JCheckBox sugar; // Radio button for off peak rate
private JCheckBox teabags; // Radio button for off peak rate
private JCheckBox instantcoffee; // Radio button for off peak rate
private JCheckBox bread; // Radio button for off peak rate
private JCheckBox sausages; // Radio button for off peak rate
private JCheckBox eggs; // Radio button for off peak rate
private JCheckBox milk; // Radio button for off peak rate
private JCheckBox potatoes; // Radio button for off peak rate
//private ButtonGroup bg; // Radio button group
/**
Constructor
*/
public RatePanel()
{
// Create a DecimalFormat object.
DecimalFormat dollar = new DecimalFormat("#,##0.00");
// Create the check boxes.
bakedbeans = new JCheckBox("Bakedbeans (£" +
dollar.format(BAKED_BEANS) + " per packet)");
cornflakes = new JCheckBox("Cornflakes (£" +
dollar.format(CORNFLAKES) + " per packet)");
sugar = new JCheckBox("Sugar (£" +
dollar.format(SUGAR) + " per packet)");
teabags = new JCheckBox("Teabags (£" +
dollar.format(TEA_BAGS) + " per item)");
instantcoffee = new JCheckBox("Instantcoffee (£" +
dollar.format(INSTANT_COFFEE) + " per packet)");
bread = new JCheckBox("Bread (£" +
dollar.format(BREAD) + " per packet)");
sausages = new JCheckBox("Sausages (£" +
dollar.format(SAUSAGES) + " per packet)");
eggs = new JCheckBox("Eggs (£" +
dollar.format(EGGS) + " per packet)");
milk = new JCheckBox("Milk (£" +
dollar.format(MILK) + " per packet)");
potatoes = new JCheckBox("Potatoes (£" +
dollar.format(POTATOES) + " per packet)");
// Create a GridLayout manager.
setLayout(new GridLayout(15, 12));
// Create a border.
setBorder(BorderFactory.createTitledBorder("Select a Category"));
// Add the check boxes to this panel.
add(bakedbeans);
add(cornflakes);
add(sugar);
add(teabags);
add(instantcoffee);
add(bread);
add(sausages);
add(eggs);
add(milk);
add(potatoes);
}
/**
The getRate method returns the rate for the selected
rate category.
#return One of the constants DAYTIME_RATE, EVENING_RATE, or
OFF_PEAK_RATE.
*/
public double getRate()
{
double rate = 0.0;
if (bakedbeans.isSelected())
rate += BAKED_BEANS;
if (cornflakes.isSelected())
rate = CORNFLAKES;
else if (sugar.isSelected())
rate += SUGAR;
else if (teabags.isSelected())
rate += TEA_BAGS;
else if (instantcoffee.isSelected())
rate += INSTANT_COFFEE;
else if (bread.isSelected())
rate += BREAD;
else if (sausages.isSelected())
rate += SAUSAGES;
else if (eggs.isSelected())
rate += EGGS;
else if (milk.isSelected())
rate += MILK;
else if (potatoes.isSelected())
rate += POTATOES;
return rate;
}
}
I want to be able to calculate the total price of groceries when the user select a multiple of check-boxes with its quantities..
Try if - if instead of if-else if.
if - else if condition is satisfied, the appropriate statements are executed and the remaining conditions are not evaluated.
if -if will evaluate each condition.
public double getRate()
{
double rate = 0.0;
if (bakedbeans.isSelected())
rate += BAKED_BEANS;
if (cornflakes.isSelected())
rate += CORNFLAKES;
if (sugar.isSelected())
rate += SUGAR;
if (teabags.isSelected())
rate += TEA_BAGS;
if (instantcoffee.isSelected())
rate += INSTANT_COFFEE;
if (bread.isSelected())
rate += BREAD;
if (sausages.isSelected())
rate += SAUSAGES;
if (eggs.isSelected())
rate += EGGS;
if (milk.isSelected())
rate += MILK;
if (potatoes.isSelected())
rate += POTATOES;
return rate;
}
As I understand it, getCharges is intended to return the total cost of the selected items. The current implementation is:
public double getCharges(double rate)
{
double charges = Double.parseDouble(baked_beans_JT.getText()) * rate;
return charges;
}
Unfortunately, you cannot use the number of baked beans selected to predict what else the customer is buying :)
There are several ways this could be fixed, and I'm afraid all of them will need modifications elsewhere in the code. I would recommend looking into the use of arrays. If you'd rather avoid that, you'll have to do something similar to this:
double charges = 0;
charges += Integer.parseInt(baked_beans_JT.getText()) * BAKED_BEANS;
charges += Integer.parseInt(cornflakes_JT.getText()) * CORNFLAKES;
...
Since the getRate method wouldn't be needed anymore, you could adapt that and save some copy-pasting.
But really, look into arrays or collections. Without them, you're in for a frustrating future.

how to assign value to a checked JChechbox?

I am making a simple currency convertor which takes the initial value in a JTextField then the user clicks the JCheckBox corresponding to their desired currency, the converted value will then be displayed in another JTextField. Basically i would like to know is there any way of assigning a value to a checked JCheckBoxi have looked around and cannot find a clear answer to this, any help would be appreciated.
For example if the current conversion rate from Sterling to euro is 1.12244 this value would be assigned when the JCheckBox is checked, so the the original value would be multiplied by the conversion rate.
Think it'd be easier if you assign an action-listener to your JCheckBox and make the conversion on trigger of this event. To check is a JCheckBox is checked or not you can use the isSelected() method
EDIT
Actually i think you need to use JRadioButton's in a ButtonGroup for this, as if you are using a checkbox then there is a chance that more than one is selected. Here is an example of how to do use ButtonGroup and trigger action on the radio button
This would give you the value of the check box.
JCheckBox cb = ...;
// Determine status
boolean isSel = cb.isSelected();
if (isSel) {
// The checkbox is now selected
} else {
// The checkbox is now deselected
}
You can change the value on the action-listener of the JCheckBox
// Create an action
Action action = new AbstractAction("CheckBox Label") {
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
// Perform action
JCheckBox cb = (JCheckBox)evt.getSource();
// Determine status
boolean isSel = cb.isSelected();
if (isSel) {
// The checkbox is now selected
} else {
// The checkbox is now deselected
}
}
};
// Create the checkbox
JCheckBox checkBox = new JCheckBox(action);
// this is whole working code i hope this this will help
public class CConvertor extends JFrame {
private JLabel result;
private JCheckBox pk;
private JCheckBox ch;
public CConvertor(){
result = new JLabel();
ch = new JCheckBox();
pk = new JCheckBox();
init();
}
public void init(){
setTitle("JCheckBox Test");
getContentPane().setLayout(new FlowLayout());
add(result);
add(new JLabel(" "));
add(new JLabel(" China "));
add(ch);
add(new JLabel(" Pakistan "));
add(pk);
setSize(400,80);
pk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ch.setSelected(false);
result.setText("Pakistan selected");
}
});
ch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pk.setSelected(false);
result.setText("China is Selected");
}
});
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new CConvertor();
}
}
This could not be the best solution but you can try this.
Take an array of JCheckBox.
Make sure only one checkbox gets selected at a time.
Take an array of currency conversion value.
Now based on the index of the selected checkbox get the currency conversion value from array.
Instead of using JCheckBox you can use JRadioButton as suggested by #Balanivash. More simpler and proper solution will be using JComboBox.[I'm with #Riduidel in this.]
I also think that JCheckBox isn't the best option to do what you want, however...
Why don't you extend the JCheckBox class to a CurrencyConverterCheckBox where you can
pass as arguments the currencies and the current value of the conversion.
e.g.:
public class CurrencyConverterCheckBox extends JCheckBox {
private String from;
private String to;
private double value;
public CurrencyConverterCheckBox(String from, String to, double value) {
super();
this.from = from;
this.to = to;
this.value = value;
}
}
Then you will be able to do the conversion when the user clicks the checkbox. You can also provide labels next to the checkboxes (USD to EUR). And you can also provide a method in your new checkbox to flip the currencies and calculate the multiplication factor in the other direction.
kind regards
What it's easiest to do is something like this:
String[] ccys = {"USD", "EUR", "CHF", "JPY"};
public void initUI(){
...
ButtonGroup grp = new ButtonGroup();
for(String ccy : ccys){
JCheckBox cb = new JCheckBox(ccy);
cb.setActionCommand(ccy);
cb.addActionListener(this);
grp.add(cb);
...(add CheckBox to ui)
}
}
private double getRate(String ccy){
...(retrieve the current conversion rate, f.ex from a map)
}
public void actionPerformed(ActionEvent evt){
Double rate = getRate(evt.getActionCommand());
...(calculation, display)
}

JAVA: how to use listeners on JMenuItem and Jbutton to calculate rates

I'm writing a currency converter but I'm having a bit of trouble caculating the exchange rate for each currency. basically I want the user to select a currecy first then enter an amount and press "go" button to calculate the rate. but i'm having trouble with the listeners on JMenuItem and JButton. I've declared two listeners for menuItem and JButton. how do i use the listener on the button to look out for the selection made on the menuIten so that it makes the right currecy calculation?
thanks.
CODE:
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
The usual approach is that the menu listener changes the state of the application (i.e. calls a method that will save the exchange rate in a field).
Then the calculation code can read this value and use it.
Try this out with the Euros. Should give you a place to get started.
/*
*
* 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);
}
}
I would also suggest you use a JComboBox to store the currencies. You would create an object to store both the currency name and the conversion rate. Then when you need to calculate the converted amount you get the selected item from the combo and use its conversion rate in your calculation. With this approach you can easily expand the number of currencies you support.
Check out: How to use Map element as text of a JComboBox for an example to get you start on using an object in the combo box.
I would personally add in an Enumeration to denote the currency conversion type. eg:
public enum ConversionType {
DOLLARS,
EUROS,
RUBLES
//ETC...
}
Using this, you can keep a state variable in the class:
private ConversionType fromType;
This is what you set in your selection listener.
From there it's a matter of doing the different conversions in your action listener based on the state variable (fromType). Something like this:
if( fromType== EUROS ) {
convertEurosToSterling( value1, value2 );
}
This is sort of a general approach - I hope this helps.

Categories