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:
The second class will be a class, that will represent an expense panel with the information:
An expense record is represented by the following data:
//data
float cost;
int number;
These fields will be represented in this panel by the Labels:
dataLabel,
costLabel,
numberLabel;
Also, there is an option to delete an expense record by pressing a button:
An array of colors is used to fill every expense panel with different color:
//array of colors for background
The constructor of this class initializes fields and sets data to the labels and adds labels to the panel:
ExpensesPanel
(String _name,
String _data,
float _cost,
int _number
){ initColors();//initializing colors for expenses
//save data
name = _name;
data = _data;
cost = _cost;
number = _number;
//creating labels
costLabel
= new JLabel(new Double(cost
).
toString());//converting double to string numberLabel
= new JLabel(new Integer(number
).
toString());//converting int to string delete
= new JButton("Delete");//a button to delete expense delete.addActionListener(this);//action listener for delete
//horizontal box layout for panel
add(numberLabel);
//adding glue
add
(Box.
createHorizontalGlue()); add(nameLabel);
//adding glue
add
(Box.
createHorizontalGlue()); add(dataLabel);
//adding glue
add
(Box.
createHorizontalGlue()); add(costLabel);
//adding glue
add
(Box.
createHorizontalGlue()); add(delete);
}
The array of colors is initialized with ten different colors:
/**
* init the array of colors
*/
private void initColors() {
//initialize colors
colors
[2] = Color.
darkGray; colors
[4] = Color.
magenta; colors
[5] = Color.
orange; colors
[7] = Color.
yellow; }
The interaction with the main class ti send the cost of the expense is done by a public method:
public float getCost(){
return cost;
}
The background of the panel is set in
public void paintComponent(Graphics g)
//setting the color of expense according to it's number
this.setBackground(colors[number%10]);
super.paintComponent(g);
}
The last thing that should be implemented is the delete option:
@Override
if(e.getSource() == delete){
//delete from panel3
parent.remove(this);
//getting the Expenses class to update stats and modify vector
Expenses e1 = (Expenses) parent.getParent().getParent().getParent().getParent().getParent().getParent().getParent();
if(number!=0)
e1.allExpenses.remove(number - 1);
else
e1.allExpenses.remove(0);
for(int i = 0; i != e1.allExpenses.size();++i){
e1.allExpenses.get(i).number = i;//setting new numbers
}
e1.updateStats();//update statistics
e1.validate();//validate data
e1.repaint();//repaint
}
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:
//private fields
private JLabel name_label,date_label,cost_label, total_exp, average_exp
; private JTextField name_tf,date_tf,cost_tf, total_tf, average_tf
; private JPanel panel1,panel2,panel3,panel4
; private JButton button1add, button2clear
; 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:
//size,title, exit
setSize(400,400);
setTitle("Calculator");
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:
//panel 1
getContentPane().add(panel1);
//panel 2
panel1.add(panel2);
// creating labels
name_label
= new JLabel("name"); date_label
= new JLabel("date"); cost_label
= new JLabel("cost"); //creating the text fields
//aligning the textfields to the right
panel2.
setMaximumSize(new Dimension(Integer.
MAX_VALUE,
(int)panel2.
getPreferredSize().
getHeight())); //adding labels & textfield to panel2
//first row
panel2.add(name_label); panel2.add(name_tf);
//second row
panel2.add(date_label); panel2.add(date_tf);
//third row
panel2.add(cost_label); panel2.add(cost_tf);
//create button(add and clear)
button1add
= new JButton("Add Expenses"); button2clear
= new JButton("Clear Expenses"); panel2.add(button1add);
panel2.add(button2clear);
//panel 3,vertical layout,scrollpane
//JTextArea ta = new JTextArea();
//panel3.add(sp);
panel1.add(sp);
//panel 4, labels total exp and ave exp, with uneditable txtfield
panel1.add(panel4);
total_exp
= new JLabel("Total Expenses"); average_exp
= new JLabel("Average Expenses"); //disable textfields
average_tf.setEditable(false);
total_tf.setEditable(false);
// add new label to panel4 and txtfield
panel4.add(total_exp); panel4.add(total_tf);
panel4.add(average_exp); panel4.add(average_tf);
//set max size of panel4
panel4.
setMaximumSize(new Dimension(Integer.
MAX_VALUE,
(int)panel4.
getPreferredSize().
getHeight())); //add action listeners to buttons
button1add.addActionListener(this);
button2clear.addActionListener(this);
//vector for expenses
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:
@Override
// TODO Auto-generated method stub
//add expense
if(e.getSource()==button1add){
addExpense();
updateStats();
}
//clear list
if(e.getSource()==button2clear){
clearExpense();
updateStats();
}
}
Adding an expense operation is performed in user defined method:
private void addExpense() {
//creating an Expense
ExpensesPanel newExpense
= new ExpensesPanel
(name_tf.
getText(),date_tf.
getText(),
Float.
parseFloat(cost_tf.
getText()),allExpenses.
size()+1); allExpenses.add(newExpense);//add expense to vector
panel3.add(newExpense);//adding new expense to pannel3
//update the stats
updateStats();
panel3.validate();//repaint panel 3
panel3.repaint();
}
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:
private void clearExpense() {
// TODO Auto-generated method stub
for(int i = 0; i != allExpenses.size(); ++i){
panel3.remove(allExpenses.get(i));//remove data from vector
}
//repaint panel without data
allExpenses.clear();//clear
panel3.validate();//validate data
panel3.repaint();//repaint panel
}
The updateStats method get the total cost of all expenses, calculates average expense and displays these values in the text fields:
void updateStats(){
float total = 0;//total sum is initially 0
for(int i = 0; i != allExpenses.size(); ++i){
total += allExpenses.get(i).getCost();//ading to total cost of all expenses
}
total_tf.
setText(new Double(total
).
toString());//change total text field with achieved data average_tf.
setText(new Double(total
/allExpenses.
size()).
toString());//avg = total/number }
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:
public static void main
(String[] args
) { // TODO Auto-generated method stub
Expenses my = new Expenses();//creates frame
my.setVisible(true);//setting this frame visible
}