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

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

$23.99    $12.00
by Alfonso V. Romero | February 2010 | Cookbooks Java Open Source Web Development

In Build your own Application to access Twitter using Java and NetBeans: Part 1 of this article series, we saw a simple way to see your last tweet via a Java application called SwingAndTweet using the Twitter4J API.

In this article by Alfonso Romero, we will add some more functionality to our SwingAndTweet Java application.

Here, we will learn how to:

  • Create a twitterLogin dialog to take care of the login process
  • Add functionality to show your 20 most recent tweets right after logging in
  • Add the functionality to update your Twitter status

In this tutorial, we’ll develop the simple Java application further to add some more functions. Now that we can connect to our Twitter account via the Twitter4J API, it would be nice to use a login dialog instead of hard-coding our Twitter username and password in the Java application.

But before we start to build our enhanced SwingAndTweet application, let me show you how it will look like once we finish all the exercises in this part of the tutorial:

JavaFX 1.2 Application Development Cookbook

And now, let the show begin…

Creating a Login dialog for our SwingAndTweet application

  1. Open your NetBeans IDE along with your SwingAndTweet project, and make sure you’re in the Design View.
  2. Go to the Palette window and locate the Dialog component under the Swing Windows section; then drag and drop it anywhere inside the SwingAndTweetUI JFrame component:

    JavaFX 1.2 Application Development Cookbook

  3. A JDialog will be added automatically to your SwingAndTweet application, and it will show up in the Component Inspector tab located at the lower-left part of the screen, under Other Components:

    JavaFX 1.2 Application Development Cookbook

  4. Right-click on the jDialog1 component in the Inspector tab and select Change Variable Name… from the pop-up menu. The Rename dialog will show up next. Type twitterLogin in the New Name field and press Enter to change the dialog’s name.
  5. Now you can start adding text fields, labels and buttons to your twitterLogin dialog. Double-click on the twitterLogin component under the Inspector tab. The twitterLogin dialog will show up empty in the Design Editor window. Use the Palette window to add two JLabels, one JTextField, one JPasswordField and two JButtons to the twitterLogin dialog. Arrange these controls as shown below:

    JavaFX 1.2 Application Development Cookbook

  6. Now let’s change the names of the JTextField control, the JPasswordField control and the two JButton controls, so we can easily identify them within your SwingAndTweet application’s code. Right-click on the first text field (jLabel2), select Change Variable Name… from the pop-up menu and replace the text field’s name with txtUsername.
  7. Do the same with the other fields; use txtPassword for the JPasswordField control, btnLogin for the Login button and btnExit for the Exit button.
  8. And now the last touch. Right-click anywhere inside the twitterLogin dialog, being careful not to right-click inside any of the controls, and select the Properties option from the pop-up menu. The twitterLogin [JDialog] – Properties dialog will appear next.
  9. Locate the title property, double-click on the null value and type Twitter Login to replace it. Next, scroll down the properties list until you find the modal property; click on its checkbox to enable it and then click on Close to save your changes.

Basically, in the previous exercise we added all the Swing controls you’re going to need to type your username and password, so you can connect to your Twitter account. The twitterLogin dialog is going to take care of the login process for your SwingAndTweet application. We replaced the default names for the JTextField, the JPasswordField and the two JButton controls because it will be easier to identify them during the coding process of the application. On step 8 we used the Properties window of the twitterLogin dialog to change the title property and give your dialog a decent title. We also enabled the modal property on step 9, so you can’t just close the dialog and jump right to the SwingAndTweetUI main window; you’ll have to enter a valid Twitter username and password combination for that.

Invoking the Login dialog

Ok, now we have a good-looking dialog called twitterLogin. The next step is to invoke it before our main SwingAndTweet JFrame component shows up, so we need to insert some code inside the SwingAndTweetUI() constructor method.

  1. Click on the Source button of the Editor window to change to the Source View:

    JavaFX 1.2 Application Development Cookbook

  2. Now locate the SwingAndTweetUI() constructor, and type the following lines right after the initComponents(); line:
    int loginWidth = twitterLogin.getPreferredSize().width;

    int loginHeight = twitterLogin.getPreferredSize().height;

    twitterLogin.setBounds(0,0,loginWidth,loginHeight);

    twitterLogin.setVisible(true);
  3. The code inside the SwingAndTweetUI() constructor method shall now look like this:

    JavaFX 1.2 Application Development Cookbook

  4. To see your new twitterLogin dialog in action, press F6 or select Run | Run Project to run your SwingAndTweetUI application.
  5. The twitterLogin dialog will pop right up. You’ll be able to type in your username and password, but since we haven’t added any functionality yet, the buttons won’t do anything right now. Click on the Close (X) button to close the dialog window and the SwingAndTweetUI main window will appear next. Click on its Close (X) button to exit your Twitter Java application.

Now let’s take a look at the code we added to your twitterLogin dialog. On the first line,

int loginWidth = twitterLogin.getPreferredSize().width;

we declare an integer variable named loginWidth, and assign to it the preferred width of the twitterLogin dialog. The getPreferredSize method retrieves the value of the preferredSize property from the twitterLogin dialog through the .width field.

On the second line,

int loginHeight = twitterLogin.getPreferredSize().height;

we declare another integer variable named loginHeight, and assign to it the preferred height of the twitterLogin dialog. This time, the getPreferredSize() method retrieves the value of the preferredWidth property from the twitterLogin dialog through the .height field.

On the next line,

twitterLogin.setBounds(0,0,loginWidth,loginHeight);

we use the setBounds method to set the x,y coordinates where the dialog should appear on the screen, along with its corresponding width and height. The first two parameters are for the x,y coordinates; in this case, x=0 and y=0, which means the twitterLogin dialog will show up at the upper-left part of the screen. The last two parameters receive the value of the loginWidth and loginHeight variables to establish the twitterLogin dialog’s width and height, respectively.

The last line,

twitterLogin.setVisible(true);

makes the twitterLogin dialog appear on the screen. And since the modal property of this dialog is enabled, once it shows up on the screen it won’t let you do anything else with your SwingAndTweet1 application until you close it up or enter a valid Twitter username and password, as we’ll see in the next exercise.

Adding functionality to the twitterLogin dialog

Now your twitterLogin dialog is ready to roll! Basically, it won’t let you go to the SwingAndTweet main window until you’ve entered a valid Twitter username and password. And for doing that, we’re going to use the same login code from Build your own Application to access Twitter using Java and NetBeans: Part 1 of this article series.

  1. Go to the end of your SwingAndTweetUI application source code and locate the // Variables declaration – do not modify line. Below this line, you’ll see all the variables used in your application: the btnExit and btnLogin buttons, the text fields from your twitterLogin dialog and your SwingAndTweetUI main window, etc.
  2. Add the following line just below the // End of variables declaration line:
    Twitter twitter; 
  3. Now click on the Design button to change to the Design View:

    JavaFX 1.2 Application Development Cookbook

  4. You’ll see the twitterLogin dialog again –in case you don’t, double-click on the twitterLogin component under the Inspector tab. Now double-click on the Login button to go back to the Code View. The btnLoginActionPerformed method will show up next. Add the following code inside this method:
    try {
    twitter = new Twitter(txtUsername.getText(), String.valueOf(txtPassword.getPassword()));
    twitter.verifyCredentials();
    JOptionPane.showMessageDialog(null, "You're logged in!");
    twitterLogin.dispose();
    } catch (TwitterException e) {
    JOptionPane.showMessageDialog (null, "Login failed");
    }
  5. Make sure you write each line on its own, to avoid errors. The btnLoginActionPerformed method shall look like this:
    JavaFX 1.2 Application Development Cookbook
  6. Now you’re ready to test your twitterLogin dialog. Press F6 to run your application. The Twitter Login dialog will show up next. Type your Twitter username and password, and then click on the OK button. If the username and password are correct, the You’re logged in! dialog will show up and you’ll be able to go to the SwingAndTweetUI main window. If they’re not correct, the Login failed dialog will appear instead and, after you click on the OK button, you’ll return to the twitterLogin dialog until you type a correct Twitter username and password combination.
  7. To exit your SwingAndTweetUI application, click on the Close(X) button of the twitterLogin dialog and then on the Close(X) button of the SwingAndTweetUI window. You’ll be taken back to the NetBeans IDE.
  8. Click on the Design button to go back to the Design View, and double-click on the Exit button to open the btnExitActionPerformed method.
  9. Type System.exit(0); inside the btnExitActionPerformed method, as shown below:
    JavaFX 1.2 Application Development Cookbook
  10. Now go back to the Design View again, right-click anywhere inside the twitterLogin dialog (just be careful not to right-click over any of the dialog’s controls) and select the Events | Window | windowClosing option from the pop-up menu:

    JavaFX 1.2 Application Development Cookbook

  11. NetBeans will change to Code View automatically and you’ll be inside the twitterLoginWindowClosing method. Type System.exit(0); inside this method, as shown below:
    JavaFX 1.2 Application Development Cookbook
  12. Now run your application to test the new functionality in your loginTwitter dialog. You’ll be able to exit the SwingAndTweet application when clicking on the Exit or Close(X) buttons, and you’ll be able to go to your application’s main window if you type a correct Twitter username and password combination.
  13. You can close your SwingAndTweet application now.

And now, let’s examine what we just accomplished. First you added the

Twitter twitter;

line to your application code. With this line we’re declaring a Twitter object named twitter, and it will be available throughout all the application code.

On step 4, you added some lines of code to the btnLoginActionPerformed method; this code will be executed every time you click on the Login button from the twitterLogin dialog. All the code is enclosed in a try block, so that if an error occurs during the login process, a TwitterException will be thrown and the code inside the catch block will execute.

The first line inside the try block is

twitter = new Twitter(txtUsername.getText(),String.valueOf(txtPassword.getPassword()));

This code creates the twitter object that we’re going to use throughout the application. It uses the text value you entered in the txtUsername and txtPassword fields to log into your Twitter account. The next line,

twitter.verifyCredentials();

checks to see if the username and password provided to the twitter object are correct; if that’s true, a message dialog box shows up in the screen with the You’re logged in! message and the rest of the code executes once you click on the OK button of this message dialog; otherwise, the code in the catch block executes and a message dialog shows up in the screen with the Login failed message, and the twitterLogin dialog keeps waiting for you to type a correct username and password combination.

The next line in the sequence,

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

shows the message dialog that we talked about before, and the last line inside the try block,

twitterLogin.dispose();

makes the twitterLogin dialog disappear from the screen once you’ve logged into your Twitter account successfully.

The only line of code inside the catch block is

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

This line executes when there’s an error in the Twitter login process; it shows the Login failed message in the screen and waits for you to press the OK button.

On step 9 we added one line of code to the btnExitActionPerformed method:

System.exit(0);

This line closes your SwingAndTweet application whenever you click on the Exit button.

Finally, on steps 10-12 we added another System.exit(0); line to the twitterLoginWindowClosing method, to close your SwingAndTweet application whenever you click on the Close(X) button of the twitterLogin dialog.

Showing your Twitter timeline right after logging in

Now let’s see some real Twitter action! The following exercise will show you how to show your most recent tweets inside a text area.

  1. Click on the Design button to go to the Design View; then double-click on the [JFrame] component under the Inspector tab to show the SwingAndTweetUI dialog in the Design View window:

    JavaFX 1.2 Application Development Cookbook

  2. The SwingAndTweet frame will show the three controls we created during Build your own Application to access Twitter using Java and NetBeans: Part 1. Replace the My Last Tweet text in the JLabel control with the What’s happening text.
  3. Then right-click on the JTextField control and select the Change Variable Name… option from the pop-up menu, to change its name from jTextField1 to txtUpdateStatus.
  4. Now do the same with the JButton control. Right-click on it and select the Change Variable Name… option from the pop-up menu to change its name from jButton1 to btnUpdateStatus. Right-click on the same button again, but this time select the Edit Text option from the pop-up menu and replace the Login text with Update.
  5. Rearrange the three controls as per the following screenshot (you’ll need to make the SwingAndTweet container wider):

    JavaFX 1.2 Application Development Cookbook

  6. Now drag a JTextArea control from the Palette window and drop it inside the SwingAndTweetUI container. Resize the text area so it fills up the rest of the container, as shown below:

    JavaFX 1.2 Application Development Cookbook

  7. Double-click on the Update button to open the btnUpdateStatusActionPerformed method. The first thing you’ll notice is that it’s not empty; this is because this used to be the old Login button, remember? Now just replace all the code inside this method, as shown below:
    private void btnUpdateStatusActionPerformed(java.awt.event.ActionEvent evt) { 
    try {
    if (txtUpdateStatus.getText().isEmpty())
    JOptionPane.showMessageDialog (null, "You must write something!");
    else {
    twitter.updateStatus(txtUpdateStatus.getText());
    jTextArea1.setText(null);
    java.util.List<Status> statusList = twitter.getUserTimeline();
    for (int i=0; i<statusList.size(); i++) {
    jTextArea1.append(String.valueOf(statusList.get(i).getText())+"\n");
    jTextArea1.append("-----------------------------\n");
    }
    }
    } catch (TwitterException e) {
    JOptionPane.showMessageDialog (null, "A Twitter Error ocurred!");
    }
    txtUpdateStatus.setText("");
    jTextArea1.updateUI();
  8. The next step is to modify your btnLoginActionPerformed method; we need to add several lines of code to show your Twitter timeline. The complete method is shown below (the lines you need to add are shown in bold):
    private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
    try {
    twitter = new Twitter(txtUsername.getText(), String.valueOf(txtPassword.getPassword()));
    twitter.verifyCredentials();
    // JOptionPane.showMessageDialog(null, "You're logged in!");

    java.util.List<Status> statusList = twitter.getUserTimeline();
    for (int i=0; i<statusList.size(); i++) {
    jTextArea1.append(String.valueOf(statusList.get(i).getText())+"\n");
    jTextArea1.append("-----------------------------\n");
    }

    twitterLogin.dispose();
    } catch (TwitterException e) {
    JOptionPane.showMessageDialog (null, "Login failed");
    }
    jTextArea1.updateUI();
    }
  9. Once you have added all the necessary code in each button’s actionPerformed method, press F6 to run the SwingAndTweet application and check if all things work as intended. If you type a message in the txtUpdateStatus text field and then click on the Update button, the timeline information inside the JTextArea1 control will change to reflect your new Twitter status:

    JavaFX 1.2 Application Development Cookbook

  10. You can close your SwingAndTweet application now.

That was cool, right? Now you have a much better-looking Twitter client! And you can update your status, too! Let’s examine the code we added in this last exercise…

private void btnUpdateStatusActionPerformed(java.awt.event.ActionEvent evt) {
try {
if (txtUpdateStatus.getText().isEmpty())
JOptionPane.showMessageDialog (null, "You must write something!");
else {
twitter.updateStatus(txtUpdateStatus.getText());
jTextArea1.setText(null);
java.util.List<Status> statusList = twitter.getUserTimeline();
for (int i=0; i<statusList.size(); i++) {
jTextArea1.append(String.valueOf(statusList.get(i).getText())+"\n");
jTextArea1.append("-----------------------------\n");
}
}
} catch (TwitterException e) {
JOptionPane.showMessageDialog (null, "A Twitter Error ocurred!");
}
txtUpdateStatus.setText("");
jTextArea1.updateUI();

On step 7 we added some code to the btnUpdateStatusActionPerformed method. This code will execute whenever you click on the Update button to update your Twitter status. First, let’s look at the code inside the try block. The first two lines,

if (txtUpdateStatus.getText().isEmpty())
JOptionPane.showMessageDialog (null, "You must write something!");

are the first part of a simple if-else statement that checks to see if you’ve written something inside the txtUpdateStatus text field; if it’s empty, a message dialog will show the You must write something! message on the screen, and then it will wait for you to click on the OK button. If the txtUpdateStatus text field is not empty, the code inside the else block will execute instead of showing up the message dialog.

The next part of the code is the else block. The first line inside this block,

twitter.updateStatus(txtUpdateStatus.getText());

updates your twitter status with the text you wrote in the txtUpdateStatus text field; if an error occurs at this point, a TwitterException is thrown and the program execution will jump to the catch block. If your Twitter status was updated correctly, the next line to execute is

jTextArea1.setText(null);

This line erases all the information inside the jTextArea1 control. And the next line,

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

gets the 20 most recent tweets from your timeline and assigns them to the statusList variable. The next line is the beginning of a for statement:

for (int i=0; i<statusList.size(); i++) {

Basically, what this for block does is iterate through all the 20 most recent tweets in your timeline, one at a time, executing the two statements inside this block on each iteration:

jTextArea1.append(String.valueOf(statusList.get(i).getText())+"\n");
jTextArea1.append("-----------------------------\n");

Although the getUserTimeline() function retrieves the 20 most recent tweets, we need to use the statusList.size() statement as the loop continuation condition inside the for block to get the real number of tweets obtained, because they can be less than 20, and we can’t iterate through something that maybe doesn’t exist, right?

The first line appends the text of each individual tweet to the jTextArea1 control, along with a new-line character ("\n") so each tweet is shown in one individual line, and the second line appends the "-----------------------------\n" text as a separator between each individual tweet, along with a new-line character. The final result is a list of the 20 most recent tweets inside the jTextArea1 control.

The only line of code inside the catch block displays the A Twitter Error occurred! message in case something goes wrong when trying to update your Twitter status. The next line of code right after the catch block is

txtUpdateStatus.setText("");

This line just clears the content inside the txtUpdateStatus control, so you don’t accidentally insert the same message two times in a row.

And finally, the last line of code in the btnUpdateStatusActionPerformed method is

 jTextArea1.updateUI();

This line updates the jTextArea1 control, so you can see the list of your 20 most recent tweets after updating your status.

private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
try {
twitter = new Twitter(txtUsername.getText(),
String.valueOf(txtPassword.getPassword()));
twitter.verifyCredentials();
// JOptionPane.showMessageDialog(null, "You're logged in!");

java.util.List<Status> statusList = twitter.getUserTimeline();
for (int i=0; i<statusList.size(); i++) {
jTextArea1.append(String.valueOf(statusList.get(i).getText())+"\n");
jTextArea1.append("-----------------------------\n");
}

twitterLogin.dispose();
} catch (TwitterException e) {
JOptionPane.showMessageDialog (null, "Login failed");
}
jTextArea1.updateUI();

And now let’s have a look at the code we added inside the btnLoginActionPerformed method. The first thing you’ll notice is that we’ve added the '//' characters to the

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

line; this means it’s commented out and it won’t be executed, because it’s safe to go directly to the SwingAndTweet main window right after typing your Twitter username and password. The next lines are identical to the ones inside the btnUpdateStatusActionPerformed method we saw before; the first line retrieves your 20 most recent tweets, and the for block displays the list of tweets inside the jTextArea1 control.  And the last line of code,

 jTextArea1.updateUI();

updates the jTextArea1 control so you can see the most recent information regarding your latest tweets.

Summary

Well, now your SwingAndTweet application looks better, don’t you think so? In this article, we enhanced the SwingAndTweet application which we build in the first part of the tutorials series. In short, we:

  • Created a twitterLogin dialog to take care of the login process
  • Added functionality to show your 20 most recent tweets right after logging in
  • Added the functionality to update your Twitter status

In the next part of this tutorial, we’ll see how to add much more functionality to your SwingAndTweet application. I really hope you enjoy reading these articles as much as I enjoy writing them. And if you have any comments or suggestions, you can write to questions@packtpub.com and we’ll be happy to help!

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

About the Author :


Alfonso V. Romero

Alfonso Romero is a freelance computer consultant and translator from Mexico. He's been working with Linux and open source software since 1999. He started operating his first web server (Apache) from a PC at home, offering free hosting services to experiment with Postfix, Squirrel Mail, MySQL, Apache, Tomcat, and Virtual Hosting. Since then, he's been working as a computer consultant for several clients in Mexico – writing Java, C++, and Web applications. Since 2000, he has worked for Pearson Education in Mexico as a computer books freelance translator and consultant. His latest book translations are the Spanish versions of Java How to Program, Seventh Edition, from Deitel & Deitel, and C++ How to Program, Sixth Edition, also from Deitel & Deitel. Al enjoys writing tutorials and teaching about Java, C++, PHP, the Apache Web server, Tomcat, MySQL, Web applications like Apache Roller, and all of the wonderful open source applications used today, and when he's not experimenting with new trends in Open Source applications, he enjoys playing his electric guitar.

Books From Packt

iReport 3.6
iReport 3.6

GlassFish Security
GlassFish Security

NetBeans Platform 6.8 Developer's Guide
NetBeans Platform 6.8 Developer's Guide

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

Spring Security 3 [RAW]
Spring Security 3 [RAW]

jBPM Developer Guide
jBPM Developer Guide

JBoss AS 5 Development
JBoss AS 5 Development

Oracle JRockit: The Definitive Guide
Oracle JRockit: The Definitive Guide

Your rating: None Average: 5 (2 votes)

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
6
6
S
x
z
g
Enter the code without spaces and pay attention to upper/lower case.
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