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

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 | March 2010 | Java

In this article by Alfonso Romero, you will learn how to add your friends timeline to the custom SwingAndTweet application.

Basically, you’ll learn how to:

  • Add a Tabbed Pane component to your SwingAndTweet application, so you can show your own timeline on one tab and your friends’ timeline on another tab.
  • Use a JScrollPane component to add vertical and horizontal scrollbars to your friends’ timeline list.
  • Use the getFriendsTimeline() method from the Twitter4J API to get the 20 most recent tweets from your friends’ timeline.
  • Apply font styles to your JLabel components via the Font class
  • Add a black border to separate each individual tweet by using the BorderFactory and Color classes.
  • Add the date and time of creation of each individual tweet by using the getCreatedAt() method from the twitter4j.Status interface, along with the Date class.

This is the third part of the Twitter Java client tutorial article series! In Build your own Application to access Twitter using Java and NetBeans: Part 2 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

Showing your Twitter friends’ timeline

  1. Open your NetBeans IDE along with your SwingAndTweet project, and make sure you’re in the Design View.
  2. Select the Tabbed Pane component from the Palette panel and drag it into the SwingAndTweetUI JFrame component:

  3. A new JTabbedPane1 container will appear below the JScrollPane1 control in the Inspector panel. Now drag the JScrollPane1 control into the JTabbedPane1 container:

  4. The jScrollPane1 control will merge with the jTabbedPane1 and a tab will appear. Double-click on the tab, replace its default name –tab1– with Home, and press Enter:

  5. Resize the jTabbedPane1 control so it takes all the available space from the main window:

  6. Now drag a Scroll Pane container from the Palette panel and drop it into the white area of the jTabbedPane1 control:

     

  7. A new tab will appear, containing the new jScrollPane2 object you’ve just dropped in. Now drag a Panel container from the Palette panel and drop it into the white area of the jTabbedPane1 control:

  8. A JPanel1 container will appear inside the jScrollPane2 container, as shown in the next screenshot:

  9. Change the name of the new tab to Friends and then click on the Source tab to change to the Source view. Once your app code shows up, locate the btnLoginActionPerformed method and type the following code at the end of this method, right below the jTextArea1.updateUI() line:

    //code for the Friends timeline

    try {

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

    jPanel1.setLayout(new GridLayout(statusList.size(),1));

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

    statusText = new JLabel(String.valueOf(statusList.get(i).getText()));

    statusUser = new JLabel(statusList.get(i).getUser().getName());

    JPanel individualStatus = new JPanel(new GridLayout(2,1));

    individualStatus.add(statusUser);

    individualStatus.add(statusText);

    jPanel1.add(individualStatus);

    }

    } catch (TwitterException e) {

    JOptionPane.showMessageDialog (null, "A Twitter error ocurred!");}

    jPanel1.updateUI();

  10. The next screenshot shows how the code in your btnLoginActionPerformed method should look like after adding the code:

  11. One important thing you should notice is that there will be 6 error icons due to the fact that we need to declare some variables and write some import statements. Scroll up the code window until you locate the import twitter4j.*; and the import javax.swing.JOptionPane; lines, and add the following lines right after them:

    import java.awt.GridLayout;

    import javax.swing.JLabel;

    import javax.swing.JPanel;

  12. Now scroll down the code until you locate the Twitter twitter; line you added in Swinging and Tweeting with Java and NetBeans: Part 2 of this tutorial series and add the following lines:

    JLabel statusText;

    JLabel statusUser;

  13. If you go back to the buttonUpdateStatusActionPerformed method, you’ll notice the errors have disappeared. Now everything is ready for you to test the new functionality in your Twitter client! Press F6 to run your SwingAndTweet application and log in with your Twitter credentials. The main window will show your last 20 tweets, and if you click on the Friends tab, you will see the last 20 tweets of the people you’re following, along with your own tweets:

  14. Close your SwingAndTweet application to return to NetBeans.

Let’s examine what we did in the previous exercise. On steps 2-5 you added a JTabbedPane container and created a Home tab where the JScrollPane1 and JTextArea1 controls show your latest tweets, and then on steps 6-8 you added the JPanel1 container inside the JScrollPane2 container.

On step 9 you changed the name of the new tab to Friends and then added some code to show your friends’ latest tweets. As in previous exercises, we need to add the code inside a try-catch block because we are going to call the Twitter4J API to get the last 20 tweets on your friends timeline.

The first line inside the try block is:

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

This line gets the 20 most recent tweets from your friends’ timeline, and assigns them to the statusList variable. The next line,

jPanel1.setLayout(new GridLayout(statusList.size(),1));

sets your jPanel1 container to use a layout manager called GridLayout, so the components inside jPanel1 can be arranged into rows and columns. The GridLayout constructor requires two parameters; the first one defines the number of rows, so we use the statusList.size() function to retrieve the number of tweets obtained with the getFriendsTimeline() function in the previous line of code. The second parameter defines the number of columns, and in this case we only need 1 column.

The next line,


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

starts a for loop that iterates through all the tweets obtained from your friends’ timeline. The next 6 lines are executed inside the for loop. The next line in the execution path is

statusText = new JLabel(String.valueOf(statusList.get(i).getText()));

This line assigns the text of an individual tweet to a JLabel control called statusText. You can omit the String.valueOf function in this line because the getText() already returns a string value –I used it because at first I was having trouble getting NetBeans to compile this line, I still haven’t found out why, but as soon as I have an answer, I’ll let you know. As you can see, the statusText JLabel control was created programmatically; this means we didn’t use the NetBeans GUI interface.

The next line,



statusUser = new JLabel(statusList.get(i).getUser().getName());

creates a JLabel component called statusUser, gets the name of the user that wrote the tweet through the statusList.get(i).getUser().getName() method and assigns this value to the statusUser component. The next line,

JPanel individualStatus = new JPanel(new GridLayout(2,1));

creates a JPanel container named individualStatus to contain the two JLabels we created in the last two lines of code. This panel has a GridLayout with 2 rows and one column. The first row will contain the name of the user that wrote the tweet, and the second row will contain the text of that particular tweet. The next two lines,

individualStatus.add(statusUser);

individualStatus.add(statusText);

add the name of the user (statusUser) and the text of the individual tweet (statusText) to the individualStatus container, and the next line,

jPanel1.add(individualStatus);

adds the individualStatus JPanel component – which contains the username and text of one individual tweet –to the jPanel1 container. This is the last line of code inside the for loop. The catch block shows an error message in case an error occurs when executing the getFriendsTimeline() function, and the jPanel1.updateUI(); line updates the jPanel1 container so it shows the most recent information added to it.

Now you can see your friends’ latest tweets along with your own tweets, but we need to improve the way tweets are displayed, don’t you think so?

Improving the way your friends’ tweets are displayed

For starters, let’s change some font attributes to show the user name in bold style and the text of the tweet in plain style. Then we’ll add a black border to separate each individual tweet.

  1. Add the following line below the other import statements in your code:

    import java.awt.Font;

  2. Scroll down until you locate the btnLoginActionPerformed method and add the following two lines below the statusUser = new JLabel(statusList.get(i).getUser().getName()) line:

    Font newLabelFont = new Font(statusUser.getFont().getName(),Font.PLAIN,statusUser.getFont().getSize());<!-- This is one line -->

    statusText.setFont(newLabelFont);

  3. The following screenshot shows the btnLoginActionPerformed method after adding those two lines:

     

     

  4. Press F6 to run your SwingAndTweet application. Now you will be able to differentiate the user name from the text of your friends’ tweets:

  5. And now let’s add a black border to each individual tweet. Scroll up the code until you locate the import declarations and add the following lines below the import statement you added on step 1 of this exercise:

    import javax.swing.BorderFactory;

    import java.awt.Color;

  6. Scroll down to the btnLoginActionPerformed method and add the following line right after the individualStatus.add(statusText) line:

    individualStatus.setBorder(BorderFactory.createLineBorder(Color.black));

  7. The next screenshot shows the appearance of your friends’ timeline tab with a black border separating each individual tweet:

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:

Cool, huh? Now let’s examine the code you added in the previous exercise. On step 1 you added the import java.awt.Font line to use the Font class in your application. The next line you added,

Font newLabelFont = new Font(statusUser.getFont().getName(),Font.PLAIN,statusUser.getFont().getSize());

lets you create a new Font object with three parameters. The first parameter defines the name of the new font. Since we’re going to use the same font, we use statusUser.getFont().getName() to get its name from the statusUser component. The second parameter defines the style of the new font. In this case we’re using Font.PLAIN to define a plain style. And the third parameter is the size of the font. Since we don’t want to change the size, we use statusUser.getFont().getSize()) to get the size of the current font. So basically we just changed the style of the font, from bold to plain.

The next line, statusText.setFont(newLabelFont), changes the font of the statusText component to show the text of an individual tweet in a plain style. The user name will show in bold style, since we didn’t change the font of the statusUser component.

On step 5 you added two import statements to use the BorderFactory and Color classes in your application. Then, on step 6, the

individualStatus.setBorder(BorderFactory.createLineBorder(Color.black))

line adds a black line border to the individualStatus JPanel component using the createLineBorder method from the BorderFactory class. The black object from the Color class defines the color of the border. You can use other predefined objects like Color.yellow, Color.white, etc., depending on which color you want to use.

Adding more information to your friends’ timeline

Now let’s see how to add the date and time of each individual tweet in your friends’ timeline.

  1. Add the following line below the other import statements in your code:

    import java.util.Date;

  2. Scroll down to the btnLoginActionPerformed method and add the following two lines below the statusText.setFont(newLabelFont) line:

    Date statusDate = statusList.get(i).getCreatedAt();

    statusUser.setText(statusUser.getText() + " - " + String.valueOf(statusDate));

  3. Run your application and log in. The date of creation of each tweet will show up next to the user name that wrote it:

     

     

  4. You can close your SwingAndTweet application now.

In this short exercise you saw how to show the creation date of each tweet from your friends’ timeline.

The first line of code we added,

import java.util.Date;

lets you use the Date class in your SwingAndTweet application. The next line,

Date statusDate = statusList.get(i).getCreatedAt();

creates a Date object named statusDate, and then gets the date of creation of each individual tweet via the getCreatedAt() method from the twitter4j.Status interface. The next line,

statusUser.setText(statusUser.getText() + " - " + String.valueOf(statusDate));

converts the date stored in the statusDate object to a string via the String.valueOf method and then adds it to the statusUser JLabel component via the setText method, along with a "-" character to separate the user name from the creation date.

That’s all for now! I hope you enjoyed this third part of the article series, and stay tuned because one of the cool tricks I’m going to show you in the next part of this series is how to enable the hyperlinks in your SwingAndTweet application, so you can click on one of them and a web browser window will open up automatically, just like when using the Twitter web interface. I’m also going to show you how to add the picture from the user’s profile for each individual tweet, along with some other cool stuff.

Summary

We added one more functionality to your SwingAndTweet application- added friends timeline. We learnt how to:

  • Add a Tabbed Pane component to your SwingAndTweet application, so you can show your own timeline on one tab and your friends’ timeline on another tab.
  • Use a JScrollPane component to add vertical and horizontal scrollbars to your friends’ timeline list.
  • Use the getFriendsTimeline() method from the Twitter4J API to get the 20 most recent tweets from your friends’ timeline.
  • Apply font styles to your JLabel components via the Font class
  • Add a black border to separate each individual tweet by using the BorderFactory and Color classes.
  • Add the date and time of creation of each individual tweet by using the getCreatedAt() method from the twitter4j.Status interface, along with the Date class.
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

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

 

 

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