0

I'm trying to create a simple tip calculator program, however, I'm somewhat new to action listeners in general so I'm not sure what I'm doing wrong. I want the button to update the value of num, format it into a string, then change the text of the label (displaying what the user entered(which is the bill amount)).

Here is my code:

package calculatorCW;

import java.awt.Color;
import java.awt.event.*;
import java.text.DecimalFormat;
import java.text.ParseException;
import javax.swing.*;

public class calGui {
    double tip = 0;
    String num = "000.00", output1 = "00.00", output2 = "00.00";
    JFrame frame = new JFrame();
    JPanel myPanel = new JPanel();
    JLabel label1, label2, label3, label4;
    JTextField myText1, myText2;
    JButton buttons, tBtn1, tBtn2, tBtn3, calc, btn0;
    DecimalFormat formatter = new DecimalFormat();
    private int i = 1;

    public calGui() {
        initializeLabels();
        initializeTextFields();
        initializeButtons();
        setPanels();
        setBounds();
        guiExtras();
        setActionListeners();
    }

    public static void main(String[] args) {
        new calGui();
    }

    public void initializeLabels() {

        label1 = new JLabel("<html> <p style='font-size: 15px; color: red;'> TIP CALCULATOR </p></html>");
        label2 = new JLabel("<html> <p style='color: white;'> Bill Amount:</p></html> ");
        label3 = new JLabel("<html> <p style='color: white;'>Tip Percentage: </p></html>");
        label4 = new JLabel("<html> <p style='color: white;'>Total Cost: </p></html>");
    }

    public void initializeTextFields() {
        myText1 = new JTextField(output1);
        myText2 = new JTextField(output2);
    }

    public void initializeButtons() {
        tBtn1 = new JButton("<html> <p style='color: blue;'>15 %</p></html>");
        tBtn2 = new JButton("<html> <p style='color: blue;'>18 %</p></html>");
        tBtn3 = new JButton("<html> <p style='color: blue;'>20 %</p></html>");
        calc = new JButton("<html> <p style='color: black;'>CALC</p></html>");
        btn0 = new JButton("0");
        //Buttons Loop
        for (int col = 50; col <= 190; col = col + 70) {
            for (int row = 253; row <= 393; row = row + 70) {
                buttons = new JButton("" + i);
                myPanel.add(buttons);
                buttons.setBounds(row, col, 60, 50);
                buttons.setActionCommand(String.valueOf(i));
                i++;
            }
        }
    }

    public void setPanels() {
        myPanel.add(tBtn1);
        myPanel.add(tBtn2);
        myPanel.add(tBtn3);
        myPanel.add(calc);
        myPanel.add(btn0);
        myPanel.add(label1);
        myPanel.add(label2);
        myPanel.add(label3);
        myPanel.add(label4);
        myPanel.add(myText1);
        myPanel.add(myText2);
    }

    public void setBounds() {
        tBtn1.setBounds(23, 90, 60, 50);
        tBtn2.setBounds(93, 90, 60, 50);
        tBtn3.setBounds(163, 90, 60, 50);
        calc.setBounds(13, 190, 100, 50);
        btn0.setBounds(323, 260, 60, 50);
        label1.setBounds(155, -5, 200, 50);
        label2.setBounds(13, 50, 100, 20);
        label3.setBounds(13, 70, 200, 20);
        label4.setBounds(13, 160, 100, 20);
        myText1.setBounds(96, 50, 100, 20);
        myText2.setBounds(96, 160, 100, 20);
    }

    public void guiExtras() {
        myPanel.setLayout(null);
        myPanel.setSize(500, 400);
        frame.add(myPanel);
        frame.setBounds(600, 50, 500, 400);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myText1.setEditable(false);
        myText2.setEditable(false);
        //myPanel.setOpaque(true);
        myPanel.setBackground(Color.black);
    }

    public void setActionListeners() {
        //bill amounts
        buttons.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                num = num + (e.getActionCommand());
            }
        });

        buttons.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    output1 = formatter.format(formatter.parse(num));
                    myText1.setText(output1);
                } catch (ParseException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });

        //tips
        tBtn1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                tip = .15;
            }
        });
        tBtn2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                tip = .18;
            }
        });
        tBtn3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                tip = .20;
            }
        });
    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Tommy Rivera
  • 75
  • 1
  • 4
  • 1
    At least tell what is wrong with the code you've posted and ask a much more specific question rather than a bunch of requirements. – Hovercraft Full Of Eels Sep 09 '17 at 22:22
  • 1
    Welcome to Stack Overflow! You have posted way to much code in your question, which makes it unclear to us (and to future readers) exactly where the problem is. Please reduce your problem code to 10 lines or less. See: [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) and [How to Debug Small Programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Joe C Sep 09 '17 at 22:23
  • when I click a number on the gui its not updating the Bill amount Jlabel from "00.00" to what ever number the user enters – Tommy Rivera Sep 09 '17 at 23:41
  • 1) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 2) Please learn common Java nomenclature (naming conventions - e.g. `EachWordUpperCaseClass`, `firstWordLowerCaseMethod()`, `firstWordLowerCaseAttribute` unless it is an `UPPER_CASE_CONSTANT`) & use it consistently... – Andrew Thompson Sep 10 '17 at 02:31
  • .. 3) See also this [calculator example](http://stackoverflow.com/a/7441804/418556). It uses `ScriptEngine` to evaluate the expression in the text field. – Andrew Thompson Sep 10 '17 at 02:31

3 Answers3

3

You currently add the ActionListener to 'buttons' which is just a temporare reference to a button created in 'initializeButtons()'. Calling 'setActionListeners' afterwards than adds the ActionListener to the very last button that was created while initializing the buttons.

I would recommand not using a class variable for buttons, use a local variable button instead.

You can fix this by adding the ActionListener while initializing the buttons:

public void initializeButtons() {
    ...
    //Buttons Loop
    for (int col = 50; col <= 190; col = col + 70) {
        for (int row = 253; row <= 393; row = row + 70) {
            JButton button = new JButton("" + i);
            // bill amounts
            button.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    num = num + (e.getActionCommand());
                    try {
                        output1 = formatter.format(formatter.parse(num));
                        myText1.setText(output1);
                    } catch (ParseException e1) {
                        e1.printStackTrace();
                    }
                }
            });
            ...
        }
    }
}
1

you can do both on the same listener

button.addActionListener(new Actionlistener{
public void actionPerformed(ActionEvent ae){
 //add code to update value of num
//change text of Jlabel
}
});
chrisgeeq
  • 149
  • 1
  • 16
0

My new question is this: I have two issues now with my code. The first issue is that when I press any of the number buttons to add a bill amount It doesn't display in the bill amount textFeild the way I want it too. If a user enters 9. I want it to display "000.09". If now the user enters 5 I want the bill amount to now display "000.95". I understand that my math if wrong the way I set it up in the Button action listener. The second issue im having is that I added a reset button and want it to reset the values in the textFields back to the original. In the setResetListener() method I created a action listener to the reset button so that it converts the values of the doubles back to its original values. I want it to then display back on the textField. However, it doesn't do this. I also want it to recolor the background of the myPanel back to its original which is black.Im guessing this is due to something about threads? Here is my code I have thus far.

package calculatorCW;
import java.awt.Color;
import java.awt.event.*;
import java.text.DecimalFormat;
import java.text.ParseException;
import javax.swing.*;
public class calGui 
{
    private int i=1;
    double tip=0,finalAmount=0,amountTaxed=0;
    String num="000.00",output1="000.00",output2="000.00";
    JFrame frame = new JFrame();
    JPanel myPanel = new JPanel();
    JLabel label1, label2, label3, label4;
    JTextField myText1, myText2;
    JButton buttons,tBtn1,tBtn2, tBtn3,calc,btn0,reset;
    DecimalFormat formatter = new DecimalFormat();

    public calGui() 
    {
        initializeLabels();
        initializeTextFields();
        initializeButtons();
        setPanels();
        setBounds();
        guiExtras();
        setTipListeners();
        setCalcListener();
    }
    public void initializeLabels()
    {

         label1 = new JLabel("<html> <p style='font-size: 15px; color: red;'> TIP CALCULATOR </p></html>");
         label2 = new JLabel("<html> <p style='color: white;'> Bill Amount:</p></html> ");
         label3 = new JLabel("<html> <p style='color: white;'>Tip Percentage: </p></html>");
         label4 = new JLabel("<html> <p style='color: white;'>Total Cost: </p></html>");
    }
    public void initializeTextFields()
    {
         myText1 = new JTextField(output1);
         myText2 = new JTextField(output2);
    }
    public void initializeButtons()
    {
        tBtn1 = new JButton("<html> <p style='color: blue;'>15 %</p></html>");
        tBtn2 = new JButton("<html> <p style='color: blue;'>18 %</p></html>");
        tBtn3 = new JButton("<html> <p style='color: blue;'>20 %</p></html>");
        calc = new JButton("<html> <p style='color: black;'>CALC</p></html>");
        reset = new JButton("<html> <p style='color: black;'>Reset</p></html>");
        btn0 = new JButton("0");
        //Buttons Loop
                for (int col = 50; col<=190; col=col+70)
                    {
                        for(int row =253; row<=393; row=row+70)
                        {
                            buttons = new JButton(""+i);
                            myPanel.add(buttons);
                            buttons.setBounds(row, col, 60, 50);
                            buttons.setActionCommand(String.valueOf(i));
                            setButtonsListeners();
                            i++;
                        }
                    }

    }

    public void setPanels()
    {
        myPanel.add(tBtn1);
        myPanel.add(tBtn2);
        myPanel.add(tBtn3);
        myPanel.add(calc);
        myPanel.add(reset);
        myPanel.add(btn0);
        myPanel.add(label1);
        myPanel.add(label2);
        myPanel.add(label3);
        myPanel.add(label4);
        myPanel.add(myText1);
        myPanel.add(myText2);
    }
    public void setBounds()
    {
        tBtn1.setBounds(23, 90, 60, 50);
        tBtn2.setBounds(93, 90, 60, 50);
        tBtn3.setBounds(163, 90, 60, 50);
        calc.setBounds(13, 190, 100, 50);
        reset.setBounds(13, 260, 100, 50);
        btn0.setBounds(323, 260, 60, 50);
        label1.setBounds(155,-5,200, 50);
        label2.setBounds(13, 50, 100, 20);
        label3.setBounds(13, 70, 200, 20);
        label4.setBounds(13, 160, 100, 20);
        myText1.setBounds(96, 50, 100, 20);
        myText2.setBounds(96, 160, 100, 20);
    }
    public void guiExtras()
    {
        myPanel.setLayout(null);
        myPanel.setSize(500,400);
        frame.add(myPanel);
        frame.setBounds(600,50,500,400);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myText1.setEditable(false);
        myText2.setEditable(false);
        //myPanel.setOpaque(true);
        myPanel.setBackground(Color.black);
    }

    public void setButtonsListeners()
    {
        //bill amounts
        buttons.addActionListener(new ActionListener() 
        {@Override public void actionPerformed(ActionEvent e)
        {
            num=num+(e.getActionCommand());
            //buttons.setEnabled(true);
            try {
                output1=formatter.format(formatter.parse(num));
            } catch (ParseException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            myText1.setText(output1);
        }});
    }

    public void setTipListeners()
    {
        //tips
        tBtn1.addActionListener(new ActionListener() {@Override public void actionPerformed(ActionEvent e) {tip=.15;}});
        tBtn2.addActionListener(new ActionListener() {@Override public void actionPerformed(ActionEvent e) {tip=.18;}});
        tBtn3.addActionListener(new ActionListener() {@Override public void actionPerformed(ActionEvent e) {tip=.20;}});
    }

    public void setCalcListener()
    {
        calc.addActionListener(new ActionListener() {@Override public void actionPerformed(ActionEvent e) 
        {
            amountTaxed=(Double.parseDouble(output1)*tip)+Double.parseDouble(output1);
            finalAmount=(amountTaxed*8.25)+amountTaxed;
            try {
                output2=formatter.format(formatter.parse(Double.toString(finalAmount)));
            } catch (ParseException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            myText2.setText(output2);
            myPanel.setBackground(Color.gray);
            label1.setText(("<html> <p style='font-size: 15px; color: white;'> TIP CALCULATOR </p></html>"));
        }});
    }
    public void setResetListerner()
    {
        reset.addActionListener(new ActionListener() {@Override public void actionPerformed(ActionEvent e) 
        {
             tip=0;
             finalAmount=0;
             amountTaxed=0;
             num="000.00";
             output1="000.00";
             output2="000.00";
             myText2.setText(output2);
             myText1.setText(output1);
             myPanel.setBackground(Color.BLACK);
             //myPanel.repaint();

        }});
    }

    public static void main(String[] args) 
    {
        new calGui();
    }
}
Tommy Rivera
  • 75
  • 1
  • 4