Search code examples
javaswinguser-interfacejcombobox

JCombo Box adding Value


I'm Creating GUI program Called KwH Calculator, What it does is calculate the electricity consumption of a certain item, So my problem is in the Combo Box,what i want is that if the user picks an item in the choice the watts will automatically appear on the power consumption (powTF).

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

public class KwH extends JFrame{
    private  JComboBox appCB;
    private  JLabel appL,powL,unitL,wattsL,hrL,hoursL,dayL,monthL,yearL,kwhdayL,kwhmonthL,kwhyearL;
    private  JTextField appTF,powTF,hoursTF,dayTF,monthTF,yearTF;
    private  JButton calculateB,exitB,resetB;
    private  CalculateButtonHandler cbHandler;
    private  ExitButtonHandler exitHandler;
    private  ResetButtonHandler resetHandler;
    private String[] appStrings={" ","Refrigirator","Electric Iron","Fan","Television","Washing Machine"};

public KwH(){


    appCB=new JComboBox(appStrings);
    appL=new JLabel ("Appliances: ",SwingConstants.LEFT);
    powL=new JLabel ("Power Consumption: ",SwingConstants.LEFT);
    hoursL=new JLabel ("Hours of Use: " ,SwingConstants.LEFT);
    unitL=new JLabel (" ",SwingConstants.LEFT);
    wattsL=new JLabel ("Watts",SwingConstants.LEFT);
    hrL=new JLabel("hr/day",SwingConstants.LEFT);
    dayL=new JLabel ("Energy Consumed per Day: ",SwingConstants.LEFT);
    monthL=new JLabel("Energy Consumed per Month: ",SwingConstants.LEFT);
    yearL=new JLabel("Energy Consumed per Year: ",SwingConstants.LEFT);
    kwhdayL=new JLabel("kwh/day" ,SwingConstants.LEFT);
    kwhmonthL=new JLabel("kwh/month",SwingConstants.LEFT);
    kwhyearL=new JLabel("kwh/year", SwingConstants.LEFT);


    appTF=new JTextField(10);
    powTF=new JTextField(10);
    hoursTF=new JTextField(10);
    dayTF=new JTextField(10);;
    monthTF=new JTextField(10);
    yearTF=new JTextField(10);


    calculateB=new JButton("Calculate");
    cbHandler=new CalculateButtonHandler();
    calculateB.addActionListener(cbHandler);

    exitB=new JButton("Exit");
    exitHandler=new ExitButtonHandler();
    exitB.addActionListener(exitHandler);

    resetB=new JButton("Reset");
    resetHandler=new ResetButtonHandler();
    resetB.addActionListener(resetHandler);


    setVisible(true);
    setTitle("KwH Calculator");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(600,600);

    Container p=getContentPane();
    p.setLayout(new GridLayout(7,3));


    p.add(appL);
    p.add(appCB);
    p.add(unitL);
    p.add(powL);
    p.add(powTF);
    p.add(wattsL);
    p.add(hoursL);
    p.add(hoursTF);
    p.add(hrL);
    p.add(calculateB);
    p.add(exitB);
    p.add(resetB);
    p.add(dayL);
    p.add(dayTF);
    p.add(kwhdayL);
    p.add(monthL);
    p.add(monthTF);
    p.add(kwhmonthL);
    p.add(yearL);
    p.add(yearTF);
    p.add(kwhyearL);


}

public class CalculateButtonHandler implements ActionListener{
    public void actionPerformed(ActionEvent e){

        double a,b,c,d,f,g,h;

        a=Double.parseDouble(powTF.getText());
        b=Double.parseDouble(hoursTF.getText());


        c=(a*b)/1000;
        d=c*30;
        f=d*12;

        dayTF.setText(""+c);
        monthTF.setText(""+d);
        yearTF.setText(""+f);


    }
}

public class ResetButtonHandler implements ActionListener{
    public void actionPerformed (ActionEvent e){

    }
}

public class ExitButtonHandler implements ActionListener{
    public void actionPerformed(ActionEvent e){
        System.exit(0);
    }
}

public static void main(String[]args){

    KwH p=new KwH();
}

}

Solution

  • As the example stands right now, the user still needs to enter the power consumption. Keeping with your current design, add an array of your power consumption values:

    private String[] appStrings={" ","Refrigirator","Electric Iron","Fan","Television","Washing Machine"};
    private double[] appPower={0.0, 200.0, 50.0, 20.0, 150.0, 250.0};  // New
    

    Add an ActionChangeListener to your combobox:

    appCB.addActionListener(new ApplianceChangeListener());
    

    Since you have a lookup table, you may not want users to edit the power consumption. If this is the case, you may wish to set the field as not editable:

    powTF.setEditable(false);
    

    In order to keep the Calculate button working and add functionality, I recommend moving all of the code from the CalculateButtonHandler into a new method called calculate and just have the button handler call calculate.

    public class CalculateButtonHandler implements ActionListener{
        public void actionPerformed(ActionEvent e){
            calculate();
        }
    }
    
    private void calculate() {
        double a,b,c,d,f,g,h;
    
        try {
            a=Double.parseDouble(powTF.getText());
            b=Double.parseDouble(hoursTF.getText());
        } catch (NumberFormatException nfe) {
            return;
        }
    
        c=(a*b)/1000;
        d=c*30;
        f=d*12;
    
        dayTF.setText(""+c);
        monthTF.setText(""+d);
        yearTF.setText(""+f);
    
    }
    

    Note that there is a try/catch wrapper around the calls to parseDouble. This will just return from the method (without error) if the user has not entered hours OR if they have selected no appliance.

    And finally, the ApplianceChangeListener:

    public class ApplianceChangeListener implements ActionListener {
    
        @Override
        public void actionPerformed(ActionEvent ae) {
            int item = appCB.getSelectedIndex();
    
            if (item == 0) powTF.setText("");
            else powTF.setText("" + appPower[item]);
    
            calculate();
        }
    }