In this article, we will extract TMDB data which means The Movie Database, and then display the details of the searched movie name in the Java Swing window. We will create a search bar and a search button in Java Swing, we will enter the movie name required and as soon as we click the button the compiler will search for all the similar matches in TMDB using the movie database API we will use in our code.
We will go through some steps to complete this project, so let’s start with it:
Create an account to get started with the API
Go to the web and create an account in The Movie Database, after creating an account successfully and logging in, navigate to the More section on the top taskbar and select the API option. A new window will be opened and in that you will need to click on the create option (if it’s not there go to the settings menu and select the API option there), select the developer option when asked to choose and accept the terms and conditions, now complete the form by filling all the text boxes with the correct information and by following the instructions given further, after that you will receive your API key.
Adding Adequate External Libraries to the Project
There are some external libraries that we need to add to our project so that the compiler can run the variation in code effortlessly:
- The JSON library: The JSON library is used for the compiler to understand the format used by the API and give inputs and outputs regarding it, it is also used to build the connection between the project and the API website, and make sure you are connected to the internet. The library can be downloaded from JSON Library.
- Any other external libraries can also be added which depends on the existing libraries you are using, in some cases, there can be a requirement for swing libraries and other such libraries.
Working on the Code
The final step would be writing the code to execute our scenario. We will create a text field to enter the movie name and a search button that will show us all the names related to the one entered on the search bar.
The link that I used contains the list of all the movies present in the database (https://api.themoviedb.org/3/search/movie), it can be obtained through the following steps:
- Go to the API section of your TMDB site.
- In the Overview section, there is a link to go to the documentation page.
- Once you go to the documentation page click on API References, and then on the left scroll panel navigate to the Search section and click on Movie on it.
4. As you can see the link is visible on the page it can be copied from there and pasted into the code along with the API Key.
The code is as follows (don’t forget to note how the API is used and called and how it is executed):
import org.json.JSONArray; import org.json.JSONObject; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.net.URI; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class MovieSearchApp { public static void main(String[] args) { SwingUtilities.invokeLater(MovieSearchApp::createAndShowGUI); } private static void createAndShowGUI() { JFrame frame = new JFrame("Movie Information Viewer"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(600, 400); JTextField searchField = new JTextField(30); JButton searchButton = new JButton("Search"); JTextArea textArea = new JTextArea(); textArea.setEditable(false); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); JPanel panel = new JPanel(); panel.add(new JLabel("Enter Movie Name:")); panel.add(searchField); panel.add(searchButton); JScrollPane scrollPane = new JScrollPane(textArea); frame.add(panel, BorderLayout.NORTH); frame.add(scrollPane, BorderLayout.CENTER); frame.setVisible(true); searchButton.addActionListener(e -> { String movieName = searchField.getText().trim(); if (!movieName.isEmpty()) { searchMovie(movieName, textArea); } else { textArea.setText("Please enter a movie name."); } }); } private static void searchMovie(String movieName, JTextArea textArea) { new Thread(() -> { try { String apiKey = "40ce8481e300e13b6c446b57698728b0"; //here you have to use your api key, I have inserted the one i created through the website String encodedMovieName = URLEncoder.encode(movieName, StandardCharsets.UTF_8); String url = "https://api.themoviedb.org/3/search/movie?api_key=" + apiKey + "&query=" + encodedMovieName; HttpRequest request = HttpRequest.newBuilder().GET().uri(URI.create(url)).build(); HttpClient client = HttpClient.newBuilder().build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() == 200) { JSONObject jsonObject = new JSONObject(response.body()); JSONArray results = jsonObject.getJSONArray("results"); if (results.length() > 0) { SwingUtilities.invokeLater(() -> { textArea.setText(""); // Clear the text area before displaying new results for (int i = 0; i < results.length(); i++) { JSONObject movie = results.getJSONObject(i); String title = movie.getString("title"); int id = movie.getInt("id"); String releaseDate = movie.getString("release_date"); double voteAverage = movie.getDouble("vote_average"); String overview = movie.getString("overview"); textArea.append("Title: " + title + "\n"); textArea.append("ID: " + id + "\n"); textArea.append("Release Date: " + releaseDate + "\n"); textArea.append("Vote Average: " + voteAverage + "\n\n"); textArea.append("Overview:\n" + overview + "\n\n"); textArea.append("--------------------------------------------------------\n\n"); } }); } else { SwingUtilities.invokeLater(() -> textArea.setText("No results found for the movie: " + movieName)); } } else { SwingUtilities.invokeLater(() -> textArea.setText("Error: Received status code " + response.statusCode())); } } catch (IOException | InterruptedException e) { e.printStackTrace(); SwingUtilities.invokeLater(() -> textArea.setText("Error: " + e.getMessage())); } }).start(); } }
The output can be noticed as follows:
I hope you find it helpful 🙂