Sie sind auf Seite 1von 8

11/19/2014

Build your own Application to access Twitter using | Packt


US $

BOOKS & VIDEOS

BLOG

PACKT

Log in | Register

SUPPORT

Home > Articles > Application Development > Build your own Application to access Twitter using Java and NetBeans: Part 1

BUILD YOUR OWN APPLICATION TO ACCESS


TWITTER USING JAVA AND NETBEANS: PART 1
Packt Publishing
About Us
Our Authors
Careers with Packt
Contact Packt

Featured Book

JavaFX 1.2 Application

Cookbook

Development Cookbook

Over 60 recipes to create

Vladimir Vivien

rich Internet applications

August 2010

with many exciting


features

$20.40
Buy Now

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.

https://www.packtpub.com/books/content/build-your-own-application-access-twitter-using-java-and-netbeans-part-1

1/8

11/19/2014

Build your own Application to access Twitter using | Packt


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 (well
deal with that later), make sure the Set as Main Project box is enabled and click on Next to continue:

Claim Your FreeX


Guide
Get started with Swift, the
innovative, fast, and fun
new language from Apple
by creating your own
original iPhone app with
this free guide from Packt.

Download Guide

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

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:

5. NetBeans will open the SwingAndTweetUI frame in the center panel of the main screen. Now youre
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 were going to put all the
other Swing components required to interact with Twitter. Now Im going to show you how to

https://www.packtpub.com/books/content/build-your-own-application-access-twitter-using-java-and-netbeans-part-1

2/8

11/19/2014

Build your own Application to access Twitter using | Packt


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/twitter4j2.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 projects library path:

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, lets 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, Ill show you how easy it is to start communicating with Twitter from a Java
application, thanks to the Twitter class from the Twitter4J API. Youll also learn how to check your last
tweet through your Java application.
Lets 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:

https://www.packtpub.com/books/content/build-your-own-application-access-twitter-using-java-and-netbeans-part-1

3/8

11/19/2014

Build your own Application to access Twitter using | Packt


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:

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:

5. And now, lets inject some life to our application! Double click on the JButton1 control to open your
applications code window. Youll be inside a java method called jButton1ActionPerformed. This
method will execute every time you click on the Login button, and this is where were 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:

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

https://www.packtpub.com/books/content/build-your-own-application-access-twitter-using-java-and-netbeans-part-1

4/8

11/19/2014

Build your own Application to access Twitter using | Packt


7. If you look closely at the line numbers, youll notice there are five error icons on lines 82, 84, 85, 88
and 89. Thats 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:

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 theyre correct, the following dialog will pop up:

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

12. If you want to be really sure its 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:

https://www.packtpub.com/books/content/build-your-own-application-access-twitter-using-java-and-netbeans-part-1

5/8

11/19/2014

Build your own Application to access Twitter using | Packt

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.

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 whats more important, youll be able to
update your status without having to log into the Web interface anymore!
And know lets talk about the code. Below youll find the complete code for the
jButton1ActionPerformed method, so you dont 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
havent 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 couldve 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 youll return to the main

https://www.packtpub.com/books/content/build-your-own-application-access-twitter-using-java-and-netbeans-part-1

6/8

11/19/2014

Build your own Application to access Twitter using | Packt


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.

Books to Consider

JavaFX 1.2
Application
Development
Cookbook

$ 20.40

Java EE
Development with
NetBeans 7 [Video]

Java EE 6
Development with
NetBeans 7

Java EE 5
Development with
NetBeans 6

$ 10.00

$ 25.50

$ 18.00

Back to Articles

https://www.packtpub.com/books/content/build-your-own-application-access-twitter-using-java-and-netbeans-part-1

Back to the top

7/8

11/19/2014

Build your own Application to access Twitter using | Packt

1 Comment

PacktPub

Login

Share Favorite

Sort by Best

Join the discussion


Ketan Bhatt

21 days ago

The following way doesnt work! Can you help?

Reply Share

WHAT'S THIS?

ALSO ON PACKTPUB

Customizing SharePoint Communities for


Windows Phone 7

Creating Our First Game


17 comments 2 months ago

2 comments 3 months ago

Kim gf.startPreloading =

function(endCallback, progressCallback) { ...

SharePoint development company Do you

work with SharePoint 2013? I need all the


information of SharePoint 2013 in

Packt Publishing

Creating New Characters with Morphs

1 comment 3 months ago

1 comment 3 months ago

the computer tutor impressive...

Subscribe

Add Disqus to your site

Chester Field MGTOW!

Privacy

Contact Us

Help & Support

Alerts & Offers

Get in touch here if you have any queries or issues.

Click here for FAQs, order information,

Sign up to our emails for regular updates, bespoke

T&Cs, errata and code downloads.

offers, exclusive discounts and great free content.

Enter your email address

Packt Publishing Limited.


All Rights Reserved

View our Cookie Policy

Submit

Our Privacy Policy

https://www.packtpub.com/books/content/build-your-own-application-access-twitter-using-java-and-netbeans-part-1

8/8

Das könnte Ihnen auch gefallen