Expenses calculator

Java swing library is a library that is used for creation of java application with Graphical User Interface (GUI). The whole project will consist of two classes: The first class will be the application class that will hold the GUI of the application:
  1. public class Expenses extends JFrame implements ActionListener
The second class will be a class, that will represent an expense panel with the information:
  1. class ExpensesPanel extends JPanel implements ActionListener
An expense record is represented by the following data:
  1. //data
  2. String name;
  3. String data;
  4. float cost;
  5. int number;
These fields will be represented in this panel by the Labels:
  1. JLabel nameLabel,
  2. dataLabel,
  3. costLabel,
  4. numberLabel;
Also, there is an option to delete an expense record by pressing a button:
  1. //delete
  2. JButton delete;
An array of colors is used to fill every expense panel with different color:
  1. //array of colors for background
  2. Color[] colors;
The constructor of this class initializes fields and sets data to the labels and adds labels to the panel:
  1. ExpensesPanel(String _name, String _data, float _cost,int _number){
  2. initColors();//initializing colors for expenses
  3. //save data
  4. name = _name;
  5. data = _data;
  6. cost = _cost;
  7. number = _number;
  8. //creating labels
  9. nameLabel = new JLabel(name);
  10. dataLabel = new JLabel(data);
  11. costLabel = new JLabel(new Double(cost).toString());//converting double to string
  12. numberLabel = new JLabel(new Integer(number).toString());//converting int to string
  13. delete = new JButton("Delete");//a button to delete expense
  14. delete.addActionListener(this);//action listener for delete
  15. //horizontal box layout for panel
  16. this.setLayout(new BoxLayout(this,BoxLayout.X_AXIS));
  17. add(numberLabel);
  18. //adding glue
  19. add(Box.createHorizontalGlue());
  20. add(nameLabel);
  21. //adding glue
  22. add(Box.createHorizontalGlue());
  23. add(dataLabel);
  24. //adding glue
  25. add(Box.createHorizontalGlue());
  26. add(costLabel);
  27. //adding glue
  28. add(Box.createHorizontalGlue());
  29. add(delete);
  30. }
The array of colors is initialized with ten different colors:
  1. /**
  2. * init the array of colors
  3. */
  4. private void initColors() {
  5. //initialize colors
  6. colors = new Color[10];
  7. colors[0] = Color.blue;
  8. colors[1] = Color.cyan;
  9. colors[2] = Color.darkGray;
  10. colors[3] = Color.green;
  11. colors[4] = Color.magenta;
  12. colors[5] = Color.orange;
  13. colors[6] = Color.pink;
  14. colors[7] = Color.yellow;
  15. colors[8] = Color.white;
  16. colors[9] = Color.red;
  17. }
The interaction with the main class ti send the cost of the expense is done by a public method:
  1. public float getCost(){
  2. return cost;
  3. }
The background of the panel is set in public void paintComponent(Graphics g)
  1. public void paintComponent(Graphics g){
  2. //setting the color of expense according to it's number
  3. this.setBackground(colors[number%10]);
  4. super.paintComponent(g);
  5. }
The last thing that should be implemented is the delete option:
  1. @Override
  2. public void actionPerformed(ActionEvent e ) {
  3. if(e.getSource() == delete){
  4. //delete from panel3
  5. JPanel parent = (JPanel)this.getParent();
  6. parent.remove(this);
  7. //getting the Expenses class to update stats and modify vector
  8. Expenses e1 = (Expenses) parent.getParent().getParent().getParent().getParent().getParent().getParent().getParent();
  9. if(number!=0)
  10. e1.allExpenses.remove(number - 1);
  11. else
  12. e1.allExpenses.remove(0);
  13. for(int i = 0; i != e1.allExpenses.size();++i){
  14. e1.allExpenses.get(i).number = i;//setting new numbers
  15. }
  16. e1.updateStats();//update statistics
  17. e1.validate();//validate data
  18. e1.repaint();//repaint
  19. }
Now we can implement the application class the will contain the data of all expenses. The list of all GUI elements that will display the data and the information to add expenses is represented by private fields:
  1. //private fields
  2. private JLabel name_label,date_label,cost_label, total_exp, average_exp;
  3. private JTextField name_tf,date_tf,cost_tf, total_tf, average_tf;
  4. private JPanel panel1,panel2,panel3,panel4;
  5. private JButton button1add, button2clear;
  6. ArrayList<ExpensesPanel> allExpenses; //vector to hold expenses
The constructor of this class initializes all the variables. The first step is to set size of the frame, its title and option that the from should me closed if the exit sign is pressed:
  1. //size,title, exit
  2. setSize(400,400);
  3. setTitle("Calculator");
  4. setDefaultCloseOperation(EXIT_ON_CLOSE);
The initialization of the elements it's done by adding text to all the labels and placing them to the different panels. The data of an expense is entered in text fields and it's added by pressing
Add Expense
button:
  1. //panel 1
  2. panel1 = new JPanel();
  3. panel1.setLayout(new BoxLayout(panel1,BoxLayout.Y_AXIS));
  4. getContentPane().add(panel1);
  5. //panel 2
  6. panel2 = new JPanel(new GridLayout(4,2));
  7. panel1.add(panel2);
  8. // creating labels
  9. name_label = new JLabel("name");
  10. date_label = new JLabel("date");
  11. cost_label = new JLabel("cost");
  12. //creating the text fields
  13. name_tf = new JTextField("Name");
  14. date_tf = new JTextField("Date");
  15. cost_tf = new JTextField("Cost");
  16. //aligning the textfields to the right
  17. name_tf.setHorizontalAlignment(JTextField.RIGHT);
  18. date_tf.setHorizontalAlignment(JTextField.RIGHT);
  19. cost_tf.setHorizontalAlignment(JTextField.RIGHT);
  20. panel2.setMaximumSize(new Dimension(Integer.MAX_VALUE,(int)panel2.getPreferredSize().getHeight()));
  21. //adding labels & textfield to panel2
  22. //first row
  23. panel2.add(name_label); panel2.add(name_tf);
  24. //second row
  25. panel2.add(date_label); panel2.add(date_tf);
  26. //third row
  27. panel2.add(cost_label); panel2.add(cost_tf);
  28. //create button(add and clear)
  29. button1add = new JButton("Add Expenses");
  30. button2clear = new JButton("Clear Expenses");
  31. panel2.add(button1add);
  32. panel2.add(button2clear);
  33. //panel 3,vertical layout,scrollpane
  34. panel3 = new JPanel();
  35. panel3.setLayout(new BoxLayout(panel3,BoxLayout.Y_AXIS));
  36. //JTextArea ta = new JTextArea();
  37. sp = new JScrollPane(panel3);
  38. //panel3.add(sp);
  39. panel1.add(sp);
  40. //panel 4, labels total exp and ave exp, with uneditable txtfield
  41. panel4 = new JPanel(new GridLayout(2,2));
  42. panel1.add(panel4);
  43. total_exp = new JLabel("Total Expenses");
  44. average_exp = new JLabel("Average Expenses");
  45. average_tf = new JTextField();
  46. total_tf = new JTextField();
  47. //disable textfields
  48. average_tf.setEditable(false);
  49. total_tf.setEditable(false);
  50. // add new label to panel4 and txtfield
  51. panel4.add(total_exp); panel4.add(total_tf);
  52. panel4.add(average_exp); panel4.add(average_tf);
  53. //set max size of panel4
  54. panel4.setMaximumSize(new Dimension(Integer.MAX_VALUE,(int)panel4.getPreferredSize().getHeight()));
  55. //add action listeners to buttons
  56. button1add.addActionListener(this);
  57. button2clear.addActionListener(this);
  58. //vector for expenses
  59. allExpenses = new ArrayList<ExpensesPanel>();
As you can see, there two buttons that have ActionListeners. Let's take a look on the handling of pressing
Add Expense
button and
clear Expenses
button:
  1. @Override
  2. public void actionPerformed(ActionEvent e) {
  3. // TODO Auto-generated method stub
  4. //add expense
  5. if(e.getSource()==button1add){
  6. addExpense();
  7. updateStats();
  8. }
  9. //clear list
  10. if(e.getSource()==button2clear){
  11. clearExpense();
  12. updateStats();
  13. }
  14.  
  15. }
Adding an expense operation is performed in user defined method:
  1. private void addExpense() {
  2. //creating an Expense
  3. ExpensesPanel newExpense = new ExpensesPanel(name_tf.getText(),date_tf.getText(),Float.parseFloat(cost_tf.getText()),allExpenses.size()+1);
  4. allExpenses.add(newExpense);//add expense to vector
  5. panel3.add(newExpense);//adding new expense to pannel3
  6. //update the stats
  7. updateStats();
  8. panel3.validate();//repaint panel 3
  9. panel3.repaint();
  10. }
An expense is creating b getting data from the input text fields. After this, it's added to the screen and to the array of all expenses. The clearExpenses method simply removes all the data from the array and expense panel:
  1. private void clearExpense() {
  2. // TODO Auto-generated method stub
  3. for(int i = 0; i != allExpenses.size(); ++i){
  4. panel3.remove(allExpenses.get(i));//remove data from vector
  5. }
  6. //repaint panel without data
  7. allExpenses.clear();//clear
  8. panel3.validate();//validate data
  9. panel3.repaint();//repaint panel
  10.  
  11. }
The updateStats method get the total cost of all expenses, calculates average expense and displays these values in the text fields:
  1. void updateStats(){
  2. float total = 0;//total sum is initially 0
  3. for(int i = 0; i != allExpenses.size(); ++i){
  4. total += allExpenses.get(i).getCost();//ading to total cost of all expenses
  5. }
  6. total_tf.setText(new Double(total).toString());//change total text field with achieved data
  7. average_tf.setText(new Double(total/allExpenses.size()).toString());//avg = total/number
  8. }
To start any java application we need to have a main method. In this case, the main method simply creates and start an object of the Expense calculator application:
  1. public static void main(String[] args) {
  2. // TODO Auto-generated method stub
  3. Expenses my = new Expenses();//creates frame
  4. my.setVisible(true);//setting this frame visible
  5.  
  6. }

Tags

Add new comment