8
11/19/2014 Build your own Application to access Twitter using | Packt https://www.packtpub.com/books/content/build-your-own-application-access-twitter-using-java-and-netbeans-part-1 1/8 BUILD YOUR OWN APPLICATION TO ACCESS TWITTER USING JAVA AND NETBEANS: PART 1 Packt Publishing About Us Our Authors Careers with Packt Contact Packt Home > Articles > Application Development > Build your own Application to access Twitter using Java and NetBeans: Part 1 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. Buy Now JavaFX 1.2 Application Development Cookbook Vladimir Vivien August 2010 $20.40 Over 60 recipes to create rich Internet applications with many exciting features Featured Book Cookbook BOOKS & VIDEOS BLOG PACKT SUPPORT | Log in | Register US $

Build Your Own Application to Access Twitter Using _ Packt

Embed Size (px)

DESCRIPTION

twitter

Citation preview

11/19/2014 Build your own Application to access Twitter using | Packt

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

BUILD YOUR OWN APPLICATION TO ACCESS

TWITTER USING JAVA AND NETBEANS: PART 1

Packt Publishing

About Us

Our Authors

Careers with Packt

Contact Packt

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

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

platformTo 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.

Buy Now

JavaFX 1.2 Application

Development Cookbook

Vladimir VivienAugust 2010

$20.40

Over 60 recipes to create

rich Internet applications

with many exciting

features

Featured Book

Cookbook

BOOKS & VIDEOS BLOG PACKT SUPPORT

| Log in | RegisterUS $ ▼

11/19/2014 Build your own Application to access Twitter using | Packt

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

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:

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:

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 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

XClaim Your FreeGuideGet 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

11/19/2014 Build your own Application to access Twitter using | Packt

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

download and integrate the Twitter4J API to your SwingAndTweetJava application.

Downloading and integrating the Twitter4J API into your

NetBeans environmentFor 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:

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:

11/19/2014 Build your own Application to access Twitter using | Packt

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

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, 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:

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

11/19/2014 Build your own Application to access Twitter using | Packt

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

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:

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:

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 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:

11/19/2014 Build your own Application to access Twitter using | Packt

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

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 codeOk, 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

11/19/2014 Build your own Application to access Twitter using | Packt

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

Back to Articles Back to the top

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.

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

NetBeans.

Books to Consider

JavaFX 1.2ApplicationDevelopmentCookbook$ 20.40

Java EEDevelopment withNetBeans 7 [Video]

$ 10.00

Java EE 6Development withNetBeans 7

$ 25.50

Java EE 5Development withNetBeans 6

$ 18.00

11/19/2014 Build your own Application to access Twitter using | Packt

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

© Packt Publishing Limited.

All Rights ReservedView our Cookie Policy Our Privacy Policy

Contact Us

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

Help & Support

Click here for FAQs, order information,

T&Cs, errata and code downloads.

Submit

Alerts & Offers

Sign up to our emails for regular updates, bespoke

offers, exclusive discounts and great free content.

Enter your email address

Customizing SharePoint Communities forWindows Phone 72 comments • 3 months ago

SharePoint development company — Do youwork with SharePoint 2013? I need all theinformation of SharePoint 2013 in …

Creating Our First Game17 comments • 2 months ago

Kim 김 — gf.startPreloading =function(endCallback, progressCallback) { ...

Packt Publishing1 comment • 3 months ago

the computer tutor — impressive...

Creating New Characters with Morphs1 comment • 3 months ago

Chester Field — MGTOW!

ALSO ON PACKTPUB

1 Comment PacktPub Login

Sort by Best Share ⤤

Join the discussion…

• Reply •

Ketan Bhatt • 21 days ago

The following way doesnt work! Can you help? △ ▽

WHAT'S THIS?

Subscribe✉ Add Disqus to your sited Privacy

Favorite ★

Share ›