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

Exclusive offer: get 50% off this eBook here
NetBeans Platform 6.9 Developer's Guide

NetBeans Platform 6.9 Developer's Guide — Save 50%

Create professional desktop rich-client Swing applications using the world's only modular Swing application framework

$23.99    $12.00
by Alfonso V. Romero | June 2010 | Java Web Development

This is the final article of the article series—Build your own application to access Twitter using Java and NetBeans.

In this article by Alfonso Romero, we will:

  • Add a new tab to your JTabbedPane component programmatically.
  • Add a JEditorPane component to your SwingAndTweet application, so the URL links from your friend’s timeline appear as real hyperlinks.
  • Use the addHyperlinkListener method from your JEditorPane component, so it can listen for hyperlink events that will trigger every time you click on a URL from your friends’ timeline.
  • Use the Pattern and Matcher classes from the java.util.regex package to convert the URL hyperlinks from your friends’ timeline into clickable hyperlinks via a regular expression.

In the 3rd part of this article series, we learnt about:

  • Added a Tabbed Pane component to your SwingAndTweet application, to show your own timeline on one tab and your friend’s timeline on another tab
  • Used a JScrollPane component to add vertical and horizontal scrollbars to your friends’ timeline list
  • Used the getFriendsTimeline() method from the Twitter4J API to get the 20 most recent tweets from your friend’s timeline
  • Applied font styles to your JLabel components via the Font class
  • Added a black border to separate each individual tweet by using the BorderFactory and Color classes
  • Added 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.

All those things, we learnt in the third part of the article series were a big improvement for our Twitter client, but wouldn’t it be cool if you could click on the URL links from your friends’ time line and then a web browser window would open automatically to show you the related webpage? Well, after reading this part of the article series, you’ll be able to integrate this functionality into your own Twitter client among other things.

Here are the links to the earlier articles of this article series:

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

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

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

Using a JEditorPane component

Till now, we’ve been working with JPanel objects to show your Twitter information inside the JTabbedPane component. But as you can see from your friends’ tweets, the URL links that show up aren’t clickable. And how can we make them clickable? Well, fortunately for us there’s a Swing component called JEditorPane that will let us use HTML markup, so the URL hyperlinks will show up as if you were on a web page. Cool, huh? Now let’s start with the dirty job…

  1. Open your NetBeans IDE along with your SwingAndTweet project, and make sure you’re in the Source View.
  2. Scroll up to the import declarations section and type import javax.swing.JEditorPane; right below the last import declaration, so your code looks as shown below:

  3. Now scroll down to the last line of code, JLabel statusUser;, and type JEditorPane statusPane; just below that line, as shown in the following screenshot:

  4. The next step is to add statusPane to the JTabbedPane1 component in your application. Scroll through the code until you locate the //code for the Friends timelineline and the try-block code below that line; then type the following code block just above the for statement:
    String paneContent = new String();
    statusPane = new JEditorPane();
    statusPane.setContentType("text/html");
    statusPane.setEditable(false);
  5. The following screenshot shows how your code must look like after inserting the above block of code (the red square indicates the lines you must add):
  6. Now scroll down through the code inside the for statement and type paneContent = paneContent + statusUser.getText() + "<br>" + statusText.getText() + "<hr>"; right after the jPanel1.add(individualStatus); line, as shown below:
  7. Then add the following two lines of code after the closing brace of the try block:
    statusPane.setText(paneContent);
    jTabbedPane1.add("Friends - Enhanced", statusPane);
  8. The following screenshot shows how your code must look like after the insertion:
  9. Run your application and log into your Twitter account. A new tab will appear in your Twitter client, and if you click on it you’ll see your friends’ latest tweets, as in the following screenshot:
  10. If you take a good look at the screen, you’ll notice the new tab you added with the JEditorPane component doesn’t show a vertical scroll bar so you can scroll up and down to see the complete list. That’s pretty easy to fix: First add the import javax.swing.JScrollPane; line to the import declarations section and then replace the jTabbedPane1.add("Friends - Enhanced", statusPane); line you added on step 9 with the following lines:
    JScrollPane editorScrollPane = new JScrollPane(statusPane,
    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, // vertical bar policy
    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER ); // horizontal bar policy
    jTabbedPane1.add("Friends - Enhanced", editorScrollPane);
  11. Your code should now look like this:
  12. Run your Twitter application again and this time you’ll see the vertical scrollbar:

Let’s stop for a while to review our progress so far. In the first step above the exercise, you added an import declaration to tell the Java compiler that we need to use an object from the JEditorPane class. In step 3, you added a JEditorPane object called statusPane to your application. This object acts as a container for your friends’ tweets.

And in case you’re wondering why we didn’t use a regular JPanel object, just remember that we want to make the URL links in your friends’ tweets clickable, so when you click on one of them, a web browser window will pop up to show you the web page associated to that hyperlink.

Now let’s get back to our exercise. In step 4, you added four lines to your application’s code. The first line:

String paneContent = new String();

creates a String variable called paneContent to store the username and text of each individual tweet from your friends’ timeline. The next three lines:

statusPane = new JEditorPane();
statusPane.setContentType("text/html");
statusPane.setEditable(false);

create a JEditorPane object called statusPane, set its content type to text/html so we can include HTML markup and make the statusPane non-editable, so nothing gets messed up when showing your friends’ timeline.

Now that we have the statusPane ready to roll, we need to fill it up with the information related to each individual tweet from your friends. That’s why we need the paneContent variable. In step 6, you inserted the following line:

paneContent = paneContent + statusUser.getText() + "<br>" + statusText.getText() + "<hr>";

inside the for block to add the username and the text of each individual tweet to the paneContent variable. The <br> HTML tag inserts a line break so the username appears in one line and the text of each tweet appears in another line. The <hr> HTML tag inserts a horizontal line to separate one tweet from the other.

Once the for loop ends, we need to add the information from the paneContent variable to the JEditorPane object called statusPane. That’s why in step 7, you added the following line:

statusPane.setText(paneContent);

and then the

jTabbedPane1.add("Friends - Enhanced", statusPane);

line creates a new tab in the jTabbedPane1 component and adds the statusPane component to it, so you can see the friends timeline with HTML markup.

In step 10, you learned how to create a JScrollPane object called editorScrollPane to add scrollbars to your statusPane component and integrate them into the jTabbedPane1 container. In this example, the JScrollPane constructor requires arguments: the statusPane component, the vertical scrollbar policy and the horizontal scrollbar policy. There are three options you can choose for your vertical and horizontal scrollbars: show them as needed, never show them or always show them.

In this specific case, we need the vertical scrollbar to show up as needed, in case the list of your friends’ tweets doesn’t fit the screen, so we use the JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED policy. And since we don’t need the horizontal bar to show up because the statusPane component can adjust its horizontal size to fit your application’s window, we use the JScrollPane.HORIZONTAL_SCROLLBAR_NEVER policy.

The last line of code from step 10 adds the editorScrollPane component to the jTabbedPane1 container instead of adding the statusPane component directly, because now the JEditorPane component is contained within the JScrollPane component.

Now let’s see how to convert the URL links to real hyperlinks.

NetBeans Platform 6.9 Developer's Guide Create professional desktop rich-client Swing applications using the world's only modular Swing application framework
Published: August 2010
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

Turning URLs from your friends’ tweets into real hyperlinks via a regular expression

While the regular expressions subject is quite complex and lengthy, there are a lot of predefined patterns available for us to avoid the hassle. But if you have the time, I really recommend you to delve into the world of regular expressions, because you’ll probably need them sooner or later in your applications. In the following exercise, I’ll show you how to use a regular expression in our Twitter application to convert text URLs into clickable hyperlinks.

  1. Go to the import declarations section in your code and insert the following two lines right after the rest of the import statements:
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
  2. Scroll down to the JEditorPane statusPane; line at the end of the code window and type the Matcher matcher; right after it, as shown in the following screenshot:

  3. Go to the try block just below the //code for the Friends timeline line and type the following lines just before the for statement:
    // create a string for the regexp
    String s = "";
    Pattern pattern = Pattern.compile("http://((\\w|\\d)+\\.)+(\\w|\\d)+(/(\\w|\\d)+)+");
    String replacementStr = "<a href=\"$0\">$0</a>";
  4. Your code should now look like this:
  5. Now scroll down to the for loop and replace the statusText = new JLabel(String.valueOf(statusList.get(i).getText())); line with the following lines:
    s = String.valueOf(statusList.get(i).getText());
    matcher = pattern.matcher(s);
    s = matcher.replaceAll(replacementStr);
    statusText = new JLabel(s);
  6. The screenshot below shows how your code should look after the replacement process:
  7. Run your application. This time, the URL links in your friends’ tweets will appear as clickable hyperlinks:
  8. Cool, right? The only drawback is that if you click in a hyperlink, you won’t be taken anywhere because the statusPane component doesn’t know yet what to do when you click inside it! That’s why we’re going to add a hyperlink event via the addHyperlinkListener method next.
  9. Close your Twitter application to return to the NetBeans IDE. Add the following lines to the import declarations section in your code:
    import java.io.*; 
    import javax.swing.event.HyperlinkEvent;
    import javax.swing.event.HyperlinkListener;
  10. Now scroll down the code until you locate the statusPane.setEditable(false) line and add the following lines right after it:
    statusPane.addHyperlinkListener(
    new HyperlinkListener()
    {
    public void hyperlinkUpdate( HyperlinkEvent event )
    {
    if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED )
    try {
    java.awt.Desktop.getDesktop().browse(
    java.net.URI.create(event.getURL().toString()));
    } catch (IOException e) {
    JOptionPane.showMessageDialog (null, "IO Failed");
    }
    }

    }
    );
  11. Your code will look like the following screenshot:
  12. Run your application again, and this time click on a hyperlink. A web browser window will pop up automatically to show you the corresponding web page:
  13. Ok, let’s stop at this point and review what we’ve done. In step 1, you added two import statements to your Twitter application, to tell the Java compiler you’re going to use the Matcher and Pattern classes to create the regular expression that’s going to help you to convert the ordinary text URL links from your friends’ tweets into real clickable hyperlinks.
  14. In step 2, you added a Matcher object called (duh!) matcher that will take care of matching every occurrence of a URL in your friends’ tweets and replacing it with the required HTML code to convert the URL into a clickable hyperlink. Then in step 3, you added a Pattern object called (double duh!) pattern to store the regular expression pattern that represents a URL, along with two strings: s and replacementStr. The s string is going to store the text of an individual tweet, and replacementStr has the HTML code that’s going to replace every URL matched by the regular expression stored in pattern.

The real trick is in the

Pattern pattern = Pattern.compile("(http://)*((\\w|\\d)+\\.)+(\\w|\\d)+(/(\\w|\\d)+)+");
String replacementStr = "<a href=\"$0\">$0</a>";

lines. First, we need to use the compile method from the Pattern class to compile the regular expression and store it in the pattern object. In this case, the regular expression will match any string starting with or without the famous http:// text sequence, which must then be followed by one or more letters or digits, a dot (.), then one or more letters or digits, the / character and finally one or more letters or digits. This text sequence represents almost every URL that I’ve seen in twitter posts, like http://bit.ly/b7WOJ1, http://post.ly/kG4b, etc.

In step 5, you replaced the line that assigns an individual tweet to the statusText component with several lines. The first one of them,

s = String.valueOf(statusList.get(i).getText());

assigns an individual tweet from your friend’s timeline to the s string variable. The next line,

matcher = pattern.matcher(s);

creates the specific matcher object used to match the s string –given to the matcher method as the input parameter –against the regular expression pattern, and the

s = matcher.replaceAll(replacementStr);

line replaces every URL sequence that matches the pattern with the given HTML code in replacementStr.

In step 9, you added the three import declarations required to use a hyperlink event in your code. In step 10, you added a block of code to handle the hyperlink events. The addHyperlinkListener method adds a HyperlinkListener object to listen to any of the hyperlink event inside the statusPane component. When you click on a hyperlink, the code inside the try block executes. The

java.awt.Desktop.getDesktop().browse (

line launches a web browser window and the

java.net.URI.create(event.getURL().toString())

line generates the Uniform Resource Identifier (URI) required by the browse method from the previous line. This line calls the getUrl() method from the event object to get the URL from the hyperlink event that is triggered when you click on a hyperlink in one of your friend’s tweets, and then uses the toString method to convert it into a string object so the create method can generate the appropriate URI.

If everything goes out well, a web browser window pops up automatically and shows you the webpage that corresponds to the URL from the tweet in your friend’s timeline. If an error occurs when trying to process the hyperlink event, an IOException is generated along with an error message and the web browser window doesn’t pop up.

Well, that was a great way of enhancing your Twitter application, don’t you think so? I hope you enjoyed reading as much as I enjoyed writing the final part of the article series.

Summary

In this article, we discussed:

  • Add a new tab to your JTabbedPane component programmatically.
  • Add a JEditorPane component to your SwingAndTweet application, so the URL links from your friend’s timeline appear as real hyperlinks.
  • Use the addHyperlinkListener method from your JEditorPane component, so it can listen for hyperlink events that will trigger every time you click on a URL from your friends’ timeline.
  • Use the Pattern and Matcher classes from the java.util.regex package to convert the URL hyperlinks from your friends’ timeline into clickable hyperlinks via a regular expression.
NetBeans Platform 6.9 Developer's Guide Create professional desktop rich-client Swing applications using the world's only modular Swing application framework
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.7
iReport 3.7

GlassFish Security
GlassFish Security

JSF 2.0 Cookbook
JSF 2.0 Cookbook

Yahoo User Interface 2.X Cookbook
Yahoo User Interface 2.X Cookbook

Spring Security 3
Spring Security 3

jBPM Developer Guide
jBPM Developer Guide

JBoss AS 5 Development
JBoss AS 5 Development

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

 


No votes yet
Hot to access twitter search from java app by
can anyone tel me how to access the twitter search from my java application dynamically. Because i want to search the tweets of the twitter user's with a keyword . and the keyword to the search should be given dynamically. Thank you

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
8
7
F
f
B
x
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