Build your own Application to access Twitter using Java and NetBeans: Part 1

Exclusive offer: get 50% off this eBook here
JavaFX 1.2 Application Development Cookbook

JavaFX 1.2 Application Development Cookbook — Save 50%

Over 60 recipes to create rich Internet applications with many exciting features

£14.99    £7.50
by Alfonso Romero | January 2010 | Java

In this article by Alfonso Romero, we will discuss how to go about building a custom application for Twitter using Java and NetBeans, instead of using the standard web interface. We will learn how to log into Twitter using our application and also see the last tweet posted by you.

Due to the fact that writing a Java app to control your Twitter account is quite a long process and requires several features, I intend to divide this article in several sections, so you can see in extreme detail all the bells and whistles involved in writing Java applications.

Downloading and installing NetBeans for your developing platform

To download NetBeans, open a web browser window and go to the NetBeans website. Then click on the Download button and select the All IDE download bundle. After downloading NetBeans, install it with the default options.

Creating your SwingAndTweet project

  1. Open NetBeans and select File | New Project to open the New Project dialog. Now select Java from the Categories panel and Java Application from the Projects panel. Click on Next to continue.
  2. The New Java Application dialog will show up next. Type SwingAndTweet in the Project Name field, mark the Use Dedicated Folder for Storing Libraries option, deselect the Create Main Class box (we’ll deal with that later), make sure the Set as Main Project box is enabled and click on Next to continue:

    Swinging and Tweeting with Java and NetBeans

  3. NetBeans will create the SwingAndTweet project and will show it under the Projects tab, in the NetBeans main window. Right click on the project’s name and select JFrame Form... in the pop-up menu:

    Swinging and Tweeting with Java and NetBeans

  4. The New JFrame Form window will appear next. Type SwingAndTweetUI in the Class Name field, type swingandtweet in the Package field and click on Finish to continue:

    Swinging and Tweeting with Java and NetBeans

  5. NetBeans will open the SwingAndTweetUI frame in the center panel of the main screen. Now you’re ready to assemble your Tweeter Java application!
  6. Now let me explain a little bit about what we did in the previous exercise: First, we created a new Java application called SwingAndTweet. Then we created a Swing JFrame component and we named it SwingAndTweetUI, because this is going to act as the foundation, where we’re going to put all the other Swing components required to interact with Twitter. Now I’m going to show you how to download and integrate the Twitter4J API to your SwingAndTweetJava application.

Downloading and integrating the Twitter4J API into your NetBeans environment

For us to be able to use the powerful classes and methods from the Twitter4J API, we need to tell NetBeans where to find them and integrate them into our Java applications.

  1. Open a web browser window, go to http://repo1.maven.org/maven2/net/homeip/yusuke/twitter4j/ and search for the latest twitter4j.2.X.X.jar file, or download the most recent version at the time of this writing from here:http://repo1.maven.org/maven2/net/homeip/yusuke/twitter4j/2.0.9/twitter4j-2.0.9.jar.
  2. Once you download it in your computer, go to NetBeans, right-click on the SwingAndTweet project and select Properties from the context menu. Once at the project properties screen, select the Libraries category under the Categories panel, click on the Add JAR/Folder... button at the middle-right part of the screen to open the Add JAR/Folder dialog, navigate to the directory where you downloaded the twitter4j-2.X.X.jar file and double click on it to add it to your project’s library path:

    Swinging and Tweeting with Java and NetBeans

  3. Click on OK to close the Project Properties dialog and return to the NetBeans main screen.

Ok, you have integrated the Twitter4J API to your SwingAndTweet application. Now, let’s see how to log into your Twitter account from our Java application...

Logging into Twitter from Java and seeing your last Tweet

In the following exercise, I’ll show you how easy it is to start communicating with Twitter from a Java application, thanks to the Twitter class from the Twitter4J API. You‘ll also learn how to check your last tweet through your Java application.

Let’s see how to log into a Twitter account:

  1. Go to the Palette window and locate the JLabel component under the Swing Controls section; then drag and drop it into the TweetAndSwing JFrame component:

    Swinging and Tweeting with Java and NetBeans

  2. Now drag a Button and a Text Editor, too. Once you have the three controls inside the SwingAndTweetUI JFrame control, arrange them as shown below:

    Swinging and Tweeting with Java and NetBeans

  3. The next step is to change their names and captions, to make our application look more professional. Right click on the JLabel1 control, select Edit from the context menu, type My Last Tweet and hit Enter. Do the same procedure with the other two controls: erase the text in the jTextField1 control and type Login in the jButton1 control.
  4. Rearrange the jLabel1 and jTextField1 controls, and drag one of the ends of jTextField1 to increase its length all you can. Once done, your application will look like this:

    Swinging and Tweeting with Java and NetBeans

  5. And now, let’s inject some life to our application! Double click on the JButton1 control to open your application’s code window. You’ll be inside a java method called jButton1ActionPerformed. This method will execute every time you click on the Login button, and this is where we’re going to put all the code for logging into your Twitter account.
  6. Delete the // TODO add your handling code here: line and type the following code inside the JButton1ActionPerformed method:

    Swinging and Tweeting with Java and NetBeans

    Remember to replace username and password with your real Twitter username and password.

  7. If you look closely at the line numbers, you‘ll notice there are five error icons on lines 82, 84, 85,  88 and 89. That’s because we need to add some import lines at the beginning of your code, to indicate NetBeans where to find the Twitter and JOptionPane classes, and the TwitterException.
  8. Scroll up until you locate the package swingandtweet; line; then add the following lines:

    Swinging and Tweeting with Java and NetBeans

  9. Now all the errors will disappear from your code. To see your Java application in action, press F6 or select Run  Run | Main Project from the NetBeans main menu. The Run Project window will pop up, asking you to select the main class for your project. The swingandtweet.SwingAndTweetUI class will already be selected, so just click on OK to continue.
  10. Your SwingAndTweetUI application window will appear next, showing the three controls you created. Click on the Login button and wait for the SwingAndTweet application to validate your Twitter username and password. If they’re correct, the following dialog will pop up:

    Swinging and Tweeting with Java and NetBeans

  11. Click on OK to return to your SwingAndTweet application. Now you will see your last tweet on the textbox control:

    Swinging and Tweeting with Java and NetBeans

  12. If you want to be really sure it’s working, go to your Twitter account and update your status through the Web interface; for example, type Testing my Java app. Then return to your SwingAndTweet application and click on the Login button again to see your last tweet. The textbox control will now reflect your latest tweet:

    Swinging and Tweeting with Java and NetBeans

  13. As you can see, your SwingAndTweet Java application can now communicate with your Twitter account! Click on the X button to close the window and exit your SwingAndTweet application.
JavaFX 1.2 Application Development Cookbook Over 60 recipes to create rich Internet applications with many exciting features
Published: August 2010
eBook Price: £14.99
Book Price: £24.99
See more
Select your format and quantity:

Examining the code

Ok, I know this is a very simple example, but nevertheless we need to look at the code you wrote, because it will be the clue to add more features to your new Java app, like seeing your followers, the people you follow, the latest tweets from you and the people you follow, and what’s more important, you’ll be able to update your status without having to log into the Web interface anymore!

And know let’s talk about the code. Below you’ll find the complete code for the jButton1ActionPerformed method, so you don’t have to go back and forth between this article and your code:

try {
Twitter twitter = new Twitter("username", "password");
twitter.verifyCredentials();
JOptionPane.showMessageDialog(null, "You're logged in!");
java.util.List<Status> statusList = twitter.getUserTimeline();
String s = String.valueOf(statusList.get(0).getText());
jTextField1.setText(s);
} catch (TwitterException e) {

JOptionPane.showMessageDialog (null, "Login failed");

}

The first thing to notice is that all the code is surrounded by a try-catch statement. For those of you who haven’t worked with try-catch, just keep in mind that the try block contains the code that will execute until an error shows up; in this case, if the SwingAndTweet application can log into your Twitter account, the try block will execute completely, and the catch block will not execute.

But if an error occurs when trying to log into your Twitter account, the try block will stop executing after the twitter.verifyCredentials() statement and will jump to the JOptionPane.showMessageDialog (null, "Login failed"); statement inside the catch block. The result will be a dialog box indicating the login process failed, and then the application will return to the main screen, without updating your Twitter status.

Inside the try block, the first line creates a Twitter object named twitter (yes, I know I could’ve thought of a more creative name) with your username and your password as parameters. The next line:

twitter.verifyCredentials();

is the one in charge of verifying that you can log into your Twitter account. As I explained before, if an error occurs when trying to log in, an exception will be thrown up and the following lines of code will not execute, because the execution will jump to the line inside the catch block.

Now, if the login process is successful, the execution will continue with: 

JOptionPane.showMessageDialog(null, "You're logged in!"); 

This line is the one that shows the dialog window indicating you could log in successfully to your Twitter account. Then, when you press the OK button on this dialog, it will close and you’ll return to the main screen of your SwingAndTweet application, and the next line of code will execute:

java.util.List<Status> statusList = twitter.getUserTimeline();

In this line we create a List object called statusList, and we assign to this object the result returned by the getUserTimeline method of the twitter object. This method returns all the information regarding your 20 most recent Tweets.

On the next line, we create a String object called s, and we assign to it all the information regarding the text of your first Tweet only, through the statusList.get(0).getText() method. But first we need to use the String.valueOf method to convert the Object value returned by the statusList.get(0).getText() method into a String value that s can receive.

The last line:

jTextField1.setText(s);

assigns the value of the s string to the textbox control named jTextField1, so you can see your latest tweet in the SwingAndTweet main window.

Summary

In this article, we discussed how to go about building a custom application for Twitter using java and NetBeans.

JavaFX 1.2 Application Development Cookbook Over 60 recipes to create rich Internet applications with many exciting features
Published: August 2010
eBook Price: £14.99
Book Price: £24.99
See more
Select your format and quantity:

About the Author :


Alfonso Romero has been working with Linux & Open Source Software since 1999, when he started operating his first Web server (Apache) from a PC at home. Since then he´s been working as a Computer consultant for LASECLAT & ProEco Laboratories in Mexico, along with several other clients, as a Java, C++ & Web applications developer. He also works for Pearson Education in Mexico as a Computer Books Freelance Translator & Consultant. When he’s not experimenting with new trends in Open Source applications, he enjoys spending some quality time with his beautiful wife, his three kids and his three dogs, or playing his old electric guitar.

 

Books From Packt

iReport 3.6
iReport 3.6

GlassFish Security
GlassFish Security

Groovy for Domain-Specific Languages
Groovy for Domain-Specific Languages

Apache MyFaces 1.2 Web Application Development
Apache MyFaces 1.2 Web Application Development

MooTools 1.2 Beginner's Guide
MooTools 1.2 Beginner's Guide

jBPM Developer Guide
jBPM Developer Guide

JBoss AS 5 Development
JBoss AS 5 Development

Apache Roller 4.0 – Beginner's Guide
Apache Roller 4.0 – Beginner's Guide

Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software