Writing Your own Twitter Application Using Java, Swing, and Twitter4j

Want to build your own Twitter app? Read on to figure out what
it takes to get started.

Introduction

This article is brief introduction to using the twitter4j API, which is used for creating your own Twitter applications in Java. This API gives access to the Twitter infrastructure, and allows you to do such tasks as updating your status, getting a list of your followers, and many other useful tasks all from your Java program.

A good understanding of Java and Swing gui's is needed. Our goal is to build a basic desktop application using Swing as our view technology, that will:

Login through a pop-up

Display the users followers

Display the users updates

Allow the user to update his status on Twitter (send a tweet)

Search for Tweets

Send direct tweets

This will serve as a skeleton for your own applications. Use your imagination, and feel free to embellish on the example we create here. Although you could use any view technology, such as JSP, I've decided to use Swing in order to avoid entering into too many additional topics.

Currently, there are three Java Twitter API's; Twitter4J by Yusuke Yamamoto, Java-Twitter by DeWitt Clinton, and JTwitter by Daniel Winterstein. At the time of this writing Twitter4J is at version 2.0.8, Java-Twitter is at version 0.9, and JTwitter is at version 1.2. We'll be using Twitter4J since it's the most mature of the three API's.

Before getting started, you will need a Twitter account; this takes all of 3 minutes to complete at most. You will also need to understand the basics. What a tweet is, following others, and sending direct tweets. And off we go!

In the preceding code, we first need to import the twitter4j classes. Inside of the main method, an instance of the Twitter class is created. The user name and password are passed in as strings to the constructor. If the login is successful, the users status is updated with the call to the method updateStatus. You can verify that the update worked by logging in to your Twitter account.

Since a login is obviously required to do anything, our application should first display a dialog which requires the necessary data to login. This dialog will have two JLabels, a JTextField, a JPasswordField, a confirmation JButton, and a cancel JButton in case the user changes their mind. Just to keep it clean, we'll create a class for our login dialog.

Up to now, this is all pretty straight forward, old fashion Java code. Here we are using a FlowLayout, and we're inheriting from JDialog. Our implemented action is to either close the dialog window if the ok button is pressed, or to exit the program all together. There are two getter methods; getUserName() and getPassword(). If the ok button is pressed, we will pass on the information through the get methods. The actual login will occur in the main program which will hold our Twitter instance, and pass it around as needed. If you want to test this you can add a main to this class such as this:

Displaying your Followers

Our sample application will contain three main panels. One for displaying your followers, a second for displaying your tweets and updating them, and a third that will both search for tweets and send direct messages. The following code listing shows the code for follower display panel.

The constructor requires a single argument of type Twitter, and throws an exception of TwitterException. We make a call to method twitter.getFollowers() which returns a List of type twitter4j.User. We iterate through the list of users, and retrieve each user image location by a call to getProfileImageURL(), and the user name by a call to method getName(). Notice we're not actually getting the byte data for the image, but rather a URL which is all we need to create a new ImageIcon.

Class FollowerPanel inherits from JPanel. Because it's nice to both have the image and the display name of our followers, we'll create a JPanel that has a JLabel (containing the name of the follower), and an ImageIcon that will hold the followers display picture.

Each follower JPanel is positioned using the GridLayout nested inside of the previously mentioned JPanel which itself is placed inside of a JScrollBar. The JScrollBar is then added to the instance, which again is a JPanel. The following figure shows the resulting panel.

Figure 3 - The follower panel

The Time Line

The single most important thing you're going to want to do is send tweets! You're probably going to want to see the time line of your updates as well. Note, we're not going to duplicate the time line exactly how it works on Twitter, which mixes updates from everyone that you follow, but rather just display your own. Again, modify to your hearts content.

At the top of this panel, we'll place a JTextField for entering the tweet, followed by JButton for updating. In a sub panel underneath, is a JList which will display all of the users tweets. Upon pressing the update button either a pop up will appear, giving an error message, or a tweet is sent to the users account, and the JList is updated with the new tweet.

Again, as with the follower panel, an instance of the Twitter object is passed in to the constructor. In order to retrieve the list of updates, which we want to use to populate the status JList upon loading the program, we get the list of tweets using the method getUserTimeline() of object twitter. This returns a List of type Status. The time line area, will display both the time of the tweet, and the message. The time of the tweet is retrieved with the method getCreatedAt() of object Status, which returns a Date object. A SimpleDateFormat object is used to return the date as a string in format dd-MMM-yy HH:mm for clarity. Each tweet message is retrieved by a call to method getText(). The date and message are concatenated together and inserted into a string array. The status JList is then populated with the status string array, statusArr. Since, you almost certainly have hundreds of tweets :-) we'll place our JList in a scrollbar for easy viewing.

In short, when the update button is pressed, the method actionPerformed, sends a tweet, clears the text area, updates the time panel, and redraws the interface with the updated information. If anything goes wrong with the update process, a pop up appears warning the user of an error.

Searching For Tweets

For this part of the application we'll place the last three pieces of functionality, searching for tweets, sending a direct message, and displaying current trends, on a panel which we will generically refer to as the right side bar.

The previous code listing shows the setup for the RightSideBar class. It inherits from JPanel, uses a flow layout, and contains instances of SearchTweetsPanel, DirectMessagePanel, and TrendsPanel. The class definition of SearchTweetsPanel is as follows:

This class contains a JButton(searchTweetsButton), a JTextField, a dialog window defined inside of the constructor, and a JOptionPane which displays on error if there are any problems querying the tweets. Just to keep things compact, we use an anonymous inner class defined inside of the addActionListener method of the searchTweetsButton. This is where all the tweeting magic goes on. The method twitter.search() expects a twitter4j.Query object, which itself expects a string as input. This string contains the tokens that we're searching for in tweets. For example,

Query q = new Query(terminator);

This creates a Query object that's to search for tweets that contain the string terminator. In order to actually get some searching done, we call the method twitter.search(new Query(my query string)). In our application, we get our string from the JTextField, searchTweetsTextField by calling it's getText() method.

The call to search returns a QueryResult object. To actually get the tweet strings is a little bit more involved. First, we need a java.util.List collection which contains the type Tweet. In order to populate the list, call the QueryResult objects getTweets() method. Easy enough. Now, we create an array of strings, tweetArr, that will hold each tweet text. We iterate through the list of tweets, and insert into tweetArr the user name, and that tweet. The result of the search is displayed in resultDialog which is of type JFrame.

the first thing to notice is that we inherit from JFrame this time. The SendDirectMessageDialog consists of a JTextField, where the user inputs the message, a JComboBox which displays the people we can send direct messages to, and the all important send JButton.

To get the list of your followers, use the Twitter object's method getFollowers() which returns a List of User objects. Using a for loop, we iterate through this list, and insert each user name into a string array, as done previously. The follower string array, is then passed into the constructor of the JComboBox upon instantiation. To actually send the message, use the method sendDirectMessage() of the Twitter object, which requires two arguments; the user name, and the message to be sent. The user name is taken from the selected item of the JComboBox, and the message string from the JTextField. If everything is a-ok, a pop-up confirming the message appears. If any exception is raised, it is caught and another pop up appears displaying an error message.

Figure 8 - Direct message success pop up

Displaying Current Trends

Finally, the last part of our sample application is a component that displays the current trends on Twitter. This component contains a JLabel with the text Trends, and a JList which displays the trends.

The TrendsPanel, again, inherits from JPanel, uses a flow layout, and throws a TwitterException if there are any problems when the method twitter.getTrends() is called. The getTrends returns a single Trends object (notice it's in plural form). The method getTrends() of class Trend, returns an array of Trend objects (notice it's in singular form). In a similar fashion to how we extracted the searched tweets earlier, we create a string array called trendsArr and populate it with a for loop that gets each trend by calling trends.getTrends()[i].getName(), where it is the index value from the loop. The trends array is then passed in to the JList. You should see something like the following:

Figure 9 - The current trends JPanel.

Putting it All Together

Now that all of our classes are defined, it's just a matter of creating a main, and putting all of the components together.

We create a class, Application, which extends from JFrame, and throws both MalformedURLException and TwitterException. This time, we use a box layout to place our three main components, the FollowerPanel, StatusTimeLine, and RightSideBar. In following with the originally prescribed requirements, the LoginDialog is first created, from that we get the user name and password which are passed in to the instantiation of our top level Twitter object.

In the main, we create the Application instance, set the default close operation to exit on close, and make it so the window is maximized. If everything is good with the world, when you compile and run, you should see the login dialog.

Conclusion

You've probably noticed that this program can't do half the things that the Twitter website can do. It's not meant as a replacement, but rather a foundation for your creativity. You could create a desktop application that shows recent updates, automatically, or use the twitter4j api to get statistics and then save it to an SQL database or even, write a web application that adds your twitter information to a small sidebar.

There are already dozens of Twitter applications out there, not just on the web, but also on mobile platforms like the iPhone. One of the more interesting applications I found while researching for this article, is http://asktwitr.com which searches for tweets. But different from other twitter search applications, this one shows the location of the person who sent the tweet on a Google map.

Advertiser Disclosure:
Some of the products that appear on this site are from companies from which QuinStreet receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. QuinStreet does not include all companies or all types of products available in the marketplace.