Java Translator Application – Break the Language Barrier

FREE Online Courses: Elevate Skills, Zero Cost. Enroll Now!

This project guides you through the process of creating a Java-based Translator application. The application empowers users to input text in a specific language and seamlessly translate it to another language using the powerful MyMemory translation API.

By following this project, you will gain a comprehensive understanding of how to develop a simple yet functional Translator application using Java. With the application, users can effortlessly convert text from one language to another, thanks to the robust capabilities of the MyMemory translation API.

About Java Translator Project

This Java translator project aims to showcase the process of making HTTP requests to a translation API, parsing the JSON response, and presenting the translated text within a graphical user interface.

Throughout the project, you will learn how to effectively utilize Java to interact with the translation API via HTTP requests. By parsing the JSON response received from the API, you will extract the translated text and integrate it into a user-friendly graphical interface. This step-by-step guide will equip you with the skills necessary to seamlessly integrate translation capabilities into your Java applications, facilitating multilingual communication and enhancing user experience.

Prerequisites for Translator using Java

  • Java Development Kit (JDK): Install the latest JDK from Oracle.
  • Maven: Install Maven for dependency management and building the application(On Eclipse and IntelliJ Maven is built-in).
  • Any Integrated Development Environment (IDE): Use Eclipse or IntelliJ IDEA(This project is made using Eclipse).
  • Internet Connection: Since the application relies on making API requests to the MyMemory translation service, you will need an active internet connection to access the translation API and retrieve translations.
  • Basic Java Knowledge: Understand Java fundamentals.
  • Familiarity with Maven: Basic understanding of Maven concepts.

Download Java Translator Project

Please download the source code of Java Translator Project from the following link: Java Translator Project Code

Steps to Create Translator using Java

Following are the steps for developing the Java Translator:

Step 1: Set up the project:

Step 2: Adding the dependency:

Step 3: Implementing the application:

Step 1:Set up the project:

Create a new Java project in your preferred IDE. (For eclipse, the Steps are given below):
1. Go to File then click New, then click Project, then click Maven Project.
2. In the New Maven Project wizard, search/filter “quickStart”, select the one displayed in the image below and click Next.
3. Fill in the Group Id, Artifact Id, and Package name fields, then click Finish.

Step 2: Adding the dependency:

Add the following dependency under the dependencies tag:

<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20230227</version>
</dependency>

Step 3:Impelmenting the application:

Inside the App class, we will implement the code which is given below:

package org.ProjectGurukul.translator;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.swing.JFrame;

import org.json.JSONObject;
import java.awt.GridLayout;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;

public class App {
    private JFrame frame;
    private String[] languages = {
            "en| English",
            "es| Spanish",
            "zh| Mandarin Chinese",
            "hi| Hindi",
            "ar| Arabic",
            "bn| Bengali",
            "ru| Russian",
            "pt| Portuguese",
            "ja| Japanese",
            "de| German",
            "fr| French",
            "ms| Malay",
            "sw| Swahili",
            "ko| Korean",
            "it| Italian"
        };
    public App() {
        initialize();
    }
    
    public String translate(String query,String sourceLang,String targetLang) {
        try {
            String encodedQuery = URLEncoder.encode(query, "UTF-8");
            String langPair = sourceLang+"|"+targetLang;
            langPair = URLEncoder.encode(langPair,"UTF-8");
            String apiUrl = "https://api.mymemory.translated.net/get?q=" + encodedQuery + "&langpair=" + langPair;
            
            URL url = new URL(apiUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                
                String jsonResponse = response.toString();
                // Parse the JSON response
                JSONObject object = new JSONObject(jsonResponse);
                JSONObject responseData = object.getJSONObject("responseData");
                String translatedText = responseData.getString("translatedText");
                
                System.out.println("Response Data: " + responseData);
                System.out.println("Translated Text: " + translatedText);
                connection.disconnect();
                return translatedText;
            } else {
                System.out.println("Request failed with response code: " + responseCode);
                connection.disconnect();
                return "Request failed with response code: " +responseCode;
            }
            
        } catch (IOException e) {
            e.printStackTrace();
            
            return e.getMessage();
        }
    }
    
    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        
        frame = new JFrame();
        frame.setBounds(100, 100,600, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("Translator by ProjectGurukul");
        frame.getContentPane().setLayout(new GridLayout(0, 2, 0, 0));
        
        JPanel sourcePanel = new JPanel();
        frame.getContentPane().add(sourcePanel);
        sourcePanel.setLayout(null);
        
        final JTextArea txtrSourcetextarea = new JTextArea();
        txtrSourcetextarea.setLineWrap(true);
        txtrSourcetextarea.setWrapStyleWord(true);
        txtrSourcetextarea.setText("Enter Here to translate");
        txtrSourcetextarea.setBounds(22, 65, 248, 264);
        sourcePanel.add(txtrSourcetextarea);
        
        final JComboBox sourceComboBox = new JComboBox(languages);
        sourceComboBox.setBounds(32, 23, 216, 31);
        sourcePanel.add(sourceComboBox);
        
        JLabel lblTo = new JLabel("To->");
        lblTo.setBounds(257, 31, 70, 15);
        sourcePanel.add(lblTo);
        
        JPanel targetPanel = new JPanel();
        frame.getContentPane().add(targetPanel);
        targetPanel.setLayout(null);
        
        final JTextArea txtTargetTextarea = new JTextArea();
        txtTargetTextarea.setLineWrap(true);
        txtTargetTextarea.setWrapStyleWord(true);
        txtTargetTextarea.setBounds(12, 65, 248, 264);
        targetPanel.add(txtTargetTextarea);
        
        final JComboBox targetComboBox = new JComboBox(languages);
        targetComboBox.setBounds(22, 23, 216, 31);
        targetPanel.add(targetComboBox);
        
        JButton btnTranslate = new JButton("Translate");
        btnTranslate.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                txtTargetTextarea.setText(translate(txtrSourcetextarea.getText(),
                                                    ((String)sourceComboBox.getSelectedItem()).substring(0,2),
                                                    ((String)targetComboBox.getSelectedItem()).substring(0,2)));
            }
        });
        btnTranslate.setBounds(40, 330, 200, 30);
        targetPanel.add(btnTranslate);
        
        frame.setVisible(true);
    }
    
    public static void main(String[] args) {
    	new App();
    	
    }
}

Code Explanation:

Import Statements:

1. The java.io.BufferedReader, java.io.IOException, and java.io.InputStreamReader classes are imported to read the response from the API.
2. The java.net.HttpURLConnection and java.net.URL classes are imported to make HTTP requests to the translation API.
3. The java.net.URLEncoder class is imported to encode the query parameters for the API request.
4. The javax.swing.JFrame class is imported to create a graphical user interface window.
5. The org.json.JSONObject class is imported to parse the JSON response from the API.

Class Definition:

1. The App class is defined, which serves as the main class for our application.
2. The class extends the JFrame class to create a graphical user interface window.
3. It declares a private frame variable to hold the JFrame instance.
4. It declares a languages array to store the supported languages for translation.

translate Method:

1. The translation method is defined, which takes the query text, source language, and target language as parameters.
2. Inside the method, the query text is encoded using URLEncoder.encode to ensure proper formatting in the API request.
3. The langPair variable is constructed by concatenating the source and target languages with a pipe separator.
4. The langPair is then encoded using URLEncoder.encode.
5. The apiUrl variable is constructed by appending the encoded query and langPair to the API base URL.
6. A URL object is created with the apiUrl.
7. An HttpURLConnection object is created and initialized with the URL connection.
8. The request method is set to “GET”.
9. The response code is obtained using connection.getResponseCode().
10. If the response code is HTTP_OK (200), the response from the API is read and parsed.
11. The translated text is extracted from the JSON response using the JSONObject class.
12. The method prints the response data and translated text to the console and returns the translated text.
13. If the response code is not HTTP_OK, the error message will be printed and the method will return a error string.

initialize Method:

1. The initialize method is defined, which sets up the graphical user interface components.
2. It creates a new JFrame instance and sets its properties.
3. It creates a sourcePanel and targetPanel as JPanel instances.
4. Inside the sourcePanel, a JTextArea is created to enter the source text, a JComboBox is created to select the source language, and a label is added to indicate the “To” field.

Java Translator Output

translator hindi output

translator bengali output

Summary:

In this project, we have built a simple Translator application using Java. We have learned how to make HTTP requests to a translation API, parse the JSON response, and display the translated text in a graphical user interface. You can further enhance this application by adding error handling, language detection, or additional features like more languages based on your requirements.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google | Facebook

Leave a Reply

Your email address will not be published. Required fields are marked *