Swing is a part of the JFC (Java Foundation Classes). Building Graphical User Interface in Java requires the use of Swings. Swing Framework contains a large set of components which allow a high level of customization and provide rich functionalities, and is used to create window-based applications. Java swing components are lightweight, platform-independent, provide powerful components like tables, scroll panels, buttons, list, colour chooser, etc.
In this article, we’ll see how to make a currency converter which includes conversion between INR and Dollar. Two text fields are implemented with the labels Rupees and Dollar.
Note: It is assumed that 1 dollar is equal to 65.25 rupees.
Input: INR = 130.5
One dollar is 65.25 rupees. So, 130.5 rupees is two dollars.
Input: Dollar = 4.5
Approach: To solve this problem, the following steps are followed:
- First, we need to create a frame using JFrame.
- Then, create two labels, two textfields and three buttons(the first button for rupees and the second button is for the dollar) using JLabel, JTextField and JButton.
- Name these components accordingly and set their bounds.
- Now, in order to perform the conversion on button click, we need to add Event Handlers. In this case, we will add ActionListener to perform an action method known as actionPerformed in which first we need to get the values from the text fields which is default as a “string”.
- So, in order to perform mathematical operations, we need to convert them into double data type using Double.parseDouble(Object.getText()) and again converting from double to string to place the final value in the other text field using String.valueOf(object).
- Finally, for changing the values, we use Object.setText(object), the second object is for selecting which field we want to replace.
Below is the implementation of the above approach:
- The window displayed on running the program:
- Converting from INR to the Dollar, i.e., when INR button is clicked:
- Converting from the Dollar to INR, i.e., when the dollar button is clicked:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.