Hospedagem Profissional

Hospedagem Profissional
Clique aqui e ganhe US$ 10,00 para testar durante 1 mês a melhor hospedagem: Digital Ocean!

quinta-feira, 26 de março de 2009

Creating a Graphical Client for Twitter

In this tutorial, you use the NetBeans IDE to create a simple, graphical, REST-based client that displays Twitter public timeline messages and lets you view and update your Twitter status. The application uses Swing and NetBeans IDE's support for Twitter's SaaS operations.

Running client displaying Twitter messages

If you do not have a Twitter account, go to twitter.com and create an account before proceeding with this tutorial.

A complete sample of this application is available for download.

Click here to download the full sample.

Contents

Content on this page applies to NetBeans IDE 6.5

  • Designing the JFrame
  • Showing Your User Status
  • Setting Up Twitter Authentication
  • Adding the updateStatus Operation
  • Displaying Usernames and Statuses in the JFrame
    • Creating a TimerTask
    • Adding a run Method With the getPublicTimeline Operation
    • Creating a List Cell Rendering Component
    • Displaying the Component in TwitterJFrame

To complete this tutorial, you need the following software and resources.

Software or Resource
Version Required

NetBeans IDE
Java download bundle, Version 6.5

Java Development Kit (JDK)
Version 6 or version 5

User name and password for a Twitter account

Designing the JFrame

In this step you create the GUI elements that will display the Twitter public timeline, your user icon, and where you read and update your status. The GUI elements are all wrapped in a JFrame. You do not have to lay out the GUI elements exactly as described in this section. This layout is a suggestion only. For example, you may add more functionality. However you need to create at least all the elements described in this tutorial.

To design the JFrame:

  1. Choose File > New Project. The New Project wizard opens. Select the Java category, then a Java Application project. Click Next.
  2. Name the project TwitterSwingClient. Select a Project Location. Unselect Create Main Class. (The JFrame will be the main class.) Click Finish.
    New Project wizard showing fields for creating the TwitterSwingClient project
  3. The IDE creates the TwitterSwingClient project, which appears in the Projects window. Right-click the TwitterSwingClient project node and choose New > JFrame Form (or New > Other > Swing GUI Forms > JFrame Form). The New JFrame Form wizard opens.
  4. Name the form TwitterJFrame and create a package for it called twitterclient. Click Finish.
    New JFrame Form wizard showing fields for creating TwitterJFrame
  5. The IDE opens TwitterJFrame in the editor, in the Design view. Here you have a palette of all the Swing components you can drag and drop into the JFrame.
    Twitter J Frame in the Design view of the Editor
  6. Click on the Button icon under Swing Controls in the Palette. Drag and drop it into the bottom right corner of the JFrame. Note that the button displays jButton1, which is the name of this JButton object.
    JFrame showing newly added jButton1
  7. Right-click jButton1 and select Edit Text from the context menu. Change the display text to "Update."
  8. Drag and drop a Label (jLabel1) to the bottom left corner of the JFrame. Change its display text to "Icon." Your user icon will be displayed in this label.
  9. Drag and drop a Text Field (jTextField1) between the Label and the Button. Change its display text to "Status." Click on the right border of the text field and stretch it across towards the button. Blue guidelines appear showing you suggested distances from the button.
  10. Right-click on jLabel1 and select Properties from the context menu. The jLabel1 Properties dialog opens. Set the labelFor property to point to jTextField1. (This increases accessibility.)
  11. Find the properties Maximum Size, Minimum Size, and Preferred Size. Set each of these properties to [48,48], to match the 48px X 48px dimensions of Twitter icons.
    Properties of j Label 1 in Twitter J Frame, showing Maximum, Minimum, and Preferred sizes set to 48, 48
  12. Drag and drop a Scroll Pane into the upper part of the JFrame. Drag its borders to expand it to fill most or all of the space above the text field and button. (You may leave a margin if you want to add more functionality later, such as the menu in the sample.)
  13. Drag and drop a List into the Scroll Pane. A sample list of items appears. Save TwitterJFrame. The JFrame should look like the following image:
    Twitter J Frame in the Design view, with all basic GUI elements

You now have all the basic GUI components for the Swing client. It is time to add the first Twitter SaaS (Software as a Service) operation.

Showing Your User Status

In this section you create a new method and add the Twitter getUserTimeline operation to this method. The getUserTimeline operation gets your user icon and your current status. You then add code to the method to display your icon and status in jLabel1 and jTextField, respectively. Finally you add a line to the JFrame's constructor to initialize the method.

To show your user status:

  1. Switch to the Source view of TwitterJFrame.
  2. In the code, add a few empty lines above the main method.
    Code of Twitter J Frame showing empty lines added above main method
  3. In the empty space, type in the following code to create the method initUserInfo.
    private void initUserInfo() {


    }



  4. Open the Services window in the IDE. Under Web Services, navigate to Twitter > What Are You Doing Service > [statuses] > [user_timeline.{format}] > getUserTimeline.

    Services window with Web Services tree showing Twitter getUserTimelineById operation chosen


  5. Drag and drop getUserTimeline into the method body of initUserInfo. The Customize GET SaaS Service dialog opens. Type "1" for the value of count, because you only want to see the last status message. Exit the value cell for count and click OK. (If you do not exit the cell before you click OK, your change will not be saved. Alternatively, you can change the value of count in the code.)


    Properties dialog for get User Timeline operation


  6. The IDE generates code for the getUserStatusById operation. The IDE also creates the org.netbeans.saas package, which contains the RESTful communication code, and the org.netbeans.saas.twitter package, which contains the authenticaton code and the Twitter WhatAreYouDoingService class. The IDE adds an import statement for this class to TwitterJFrame.

    Note: In the Sample, objects and variables in this method such as format and result are numbered format2, result2, etc, because the getUserTimeline code was added after the getPublicTimeline code.



    private void initUserInfo() {

    try {
    String since = null;
    String sinceId = null;
    String page = null;
    String count = "1";
    String format = "xml";

    RestResponse result = TwitterWhatAreYouDoingService.getUserTimeline(since, sinceId, page, count, format);
    if (result.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class) instanceof twitter.whatareyoudoingservice.twitterresponse.Statuses) {
    twitter.whatareyoudoingservice.twitterresponse.Statuses resultObj = result.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class);
    } else if (result.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.NilClasses.class) instanceof twitter.whatareyoudoingservice.twitterresponse.NilClasses) {
    twitter.whatareyoudoingservice.twitterresponse.NilClasses resultObj = result.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.NilClasses.class);
    }
    //TODO - Uncomment the print Statement below to print result.
    //System.out.println("The SaasService returned: "+result.getDataAsString());
    } catch (Exception ex) {
    ex.printStackTrace();
    }

    }



  7. In the generated code, locate the if block.

    if (result.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class) instanceof twitter.whatareyoudoingservice.twitterresponse.Statuses) {
    twitter.whatareyoudoingservice.twitterresponse.Statuses resultObj = result.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class);
    }



  8. At the end of the if block, insert code that gets your user status text and icon URL and uses this data to display your status in jTextField1 and jLabel1.

    if (result.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class) instanceof twitter.whatareyoudoingservice.twitterresponse.Statuses){
    twitter.whatareyoudoingservice.twitterresponse.Statuses resultObj = result.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class);
    StatusType st = resultObj.getStatus().get(0);
    jTextField1.setText(st.getText().trim());
    UserType user = st.getUser();
    String iconSrc = user.getProfileImageUrl();
    URL iconUrl = new URL(iconSrc);
    ImageIcon icon = new ImageIcon(iconUrl, user.getScreenName());
    jLabel1.setIcon(icon);

    }



  9. Press Ctrl-Shift-I to add import statements. A dialog opens with a choice of URL classes to import. Select the default, java.net.URL.


  10. At the top of the TwitterJFrame class, locate the constructor. Add the line initUserInfo(); to the constructor's body.

    public class TwitterJFrame extends javax.swing.JFrame {

    /** Creates new form TwitterJFrame */
    public TwitterJFrame() {
    initComponents();
    initUserInfo();
    }




After you set up authentication, you can run the project. Right-click the project node and select Run from the context menu. An application opens showing your user icon and status.



Running application, showing user icon and status



Setting Up Twitter Authentication




There are two ways you can set up your application to log into Twitter:








To set up automatic login, open org.netbeans.saas.twitter.twitterwhatareyoudoingserviceauthenticator.properties. Type in your username and password and save the file.



Setting the authentication credentials in the authenticator properties file



If you do not set up these properties, a preconfigured login screen appears when you run the application.





Warning: On Windows XP and linux, there are problems rendering the preconfigured login screen. To work around this problem, either set up automatic login or use an alternative login screen. An alternative login screen is provided in the sample. To use the alternative login screen:




  1. Copy the sample's twitterclient.AuthDialog.java to your own twitterclient package.


  2. Replace your version of org.netbeans.saas.twitter.TwitterWhatAreYouDoingServiceAuthenticator.java with the version in the sample.



Adding the updateStatus Operation




In this section you add the Twitter updateStatus operation to JButton1 (the "Update" button), which you created when you designed the JFrame. You also add the code so that when the button is clicked, the client gets the text from JTextField1 (the "Status" field) and sends it to Twitter.





To add the updateStatus operation:







  1. Return to the Design view of TwitterJFrame. Double-click the Update button in the JFrame. The editor switches back to the Source view, in the body of the jButton1ActionPerformed method, which the IDE just created for you.


    TwitterJFrame in Source view, with cursor in middle of newly created jButton1ActionPerformed method


  2. Open the Services window. Under Web Services, navigate to Twitter > WhatAreYouDoingService > Statuses > [update.{format}] > updateStatus.

    Services window showing Web Services tree with Twitter update Service operation selected


  3. Drag and drop the updateStatus operation into the method body of jButton1ActionPerformed. The Customization POST SaaS dialog appears. Accept the defaults and click OK. The IDE generates the code for the updateStatus operation into the method body.


  4. In the generated try block, locate the line String status = "";. Change it to String status = jTextField1.getText().trim();. (Try changing it with code completion!) This gets the text typed into the text field and puts it in the status object that is sent by POST to Twitter.




The application can now update your Twitter status, when you are authenticated.





Displaying Usernames and Statuses in the JFrame




Now you set up the application to display the usernames and public statuses of everyone in the Twitter public timeline.







Creating a TimerTask



To update the display of the Twitter public timeline automatically, wrap the execution code in a TimerTask. Write the TimerTask wrapper first and then fill it in with execution code. Otherwise your code will be full of error warnings.





To create the TimerTask:







  1. Open TwitterJFrame in the Sources view of the editor.


  2. Find the class declaration and the constructor.

    public class TwitterJFrame extends javax.swing.JFrame {

    /** Creates new form TwitterJFrame */
    public TwitterJFrame() {
    initComponents();
    initUserInfo();
    }



  3. In the method body of the constructor, above initComponents();, instantiate the java.util.Timer class. The parameters name the Timer thread "Twitter Updater" and specify that it cannot be run as a daemon.

    public class TwitterJFrame extends javax.swing.JFrame {

    /** Creates new form TwitterJFrame */
    public TwitterJFrame() {
    Timer t = new Timer("Twitter Updater`", false);

    initComponents();
    initUserInfo();
    }



  4. Right-click anywhere in the editor and select Fix Imports from the context menu, or press Ctrl-Shift-I. A dialog opens and gives you a choice of classes to import. Add an import statement for java.util.Timer.


  5. Below the instantiation of Timer, create a new Timer.scheduleAtFixedRate method. The method's parameters are a TimerTask object, the delay before it first runs the task, and the frequency with which it runs the task. Set the method to wait 1.5 seconds and run every 75 seconds. The exact code follows, in bold. An empty line is left where you put the execution code. Note that you have to add an import statement for java.util.TimerTask.

    public class TwitterJFrame extends javax.swing.JFrame {

    /** Creates new form TwitterJFrame */
    public TwitterJFrame() {
    Timer t = new Timer("Twitter Updater`", false);
    t.scheduleAtFixedRate(new TimerTask() {


    }, 1500, 75000);

    initComponents();
    initUserInfo();
    }




The TimerTask wrapper code is now complete. Next you add the execution code.



Adding a run Method With the getPublicTimeline Operation



To display usernames and statuses, the application first gets this data from Twitter. Twitter SaaS provides the getPublicTimeline operation for getting public usernames and statuses. To execute the getPublicTimeline operation when the application runs, the operation needs to be inside a run method. Finally, because the application displays the usernames and statuses in a JList, the application needs to add the results of getPublicTimeline as elements of a DefaultListModel object.



To add a run method with the getPublicTimeline operation:




  1. Above the TwitterJFrame constructor, create a DefaultListModel object named statuses.

    public class TwitterJFrame extends javax.swing.JFrame {

    private DefaultListModel statuses = new DefaultListModel();



    /** Creates new form TwitterJFrame */
    public TwitterJFrame() {



  2. Right-click anywhere in the editor and select Fix Imports from the context menu, or press Ctrl-Shift-I. This action adds an import statement for DefaultListModel.


  3. In the body of the TimerTask object, create a new run method. Use the @Override annotation to override the run method in main.

    public class TwitterJFrame extends javax.swing.JFrame {

    private DefaultListModel statuses = new DefaultListModel();





    /** Creates new form TwitterJFrame */
    public TwitterJFrame() {
    Timer t = new Timer("Twitter Updater`", false);
    t.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run(){

    }

    }, 1500, 75000);
    initComponents();
    initUserInfo();
    }



  4. Open the Services window. In the Web Services tree, navigate to Twitter > What Are You Doing Service > [statuses] > [public_timeline.{format}] > getPublicTimeline.

    Services window showing Twitter getPublicTimeline operation


  5. Drag and drop getPublicTimeline into the body of the run method. A dialog box opens where you can customize the parameters of the GET operation. Accept the defaults and click OK. The IDE adds a try block with getPublicTimeline into your code.

    public class TwitterJFrame extends javax.swing.JFrame {

    private DefaultListModel statuses = new DefaultListModel();

    /** Creates new form TwitterJFrame */
    public TwitterJFrame() {
    Timer t = new Timer("Twitter Updater`", false);
    t.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {

    try {
    String format2 = "xml";

    RestResponse result2 = TwitterWhatAreYouDoingService.getPublicTimeline(format2);
    if (result2.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class) instanceof twitter.whatareyoudoingservice.twitterresponse.Statuses) {
    twitter.whatareyoudoingservice.twitterresponse.Statuses result2Obj = result2.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class);
    } else if (result2.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.NilClasses.class) instanceof twitter.whatareyoudoingservice.twitterresponse.NilClasses) {
    twitter.whatareyoudoingservice.twitterresponse.NilClasses result2Obj = result2.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.NilClasses.class);
    }
    //TODO - Uncomment the print Statement below to print result.
    //System.out.println("The SaasService returned: "+result2.getDataAsString());
    } catch (Exception ex) {
    ex.printStackTrace();
    }


    }
    }, 1500, 75000);
    initComponents();
    initUserInfo();
    }



  6. In the try block, locate the if block.

    if (result2.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class) instanceof twitter.whatareyoudoingservice.twitterresponse.Statuses) {
    twitter.whatareyoudoingservice.twitterresponse.Statuses result2Obj = result2.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class);
    }



  7. At the end of the if block, insert code that adds a list element to statuses (your DefaultListModel object created in Step 1) for every Status object that the method gets from Twitter.

    if (result2.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class) instanceof twitter.whatareyoudoingservice.twitterresponse.Statuses) {
    twitter.whatareyoudoingservice.twitterresponse.Statuses result2Obj = result2.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class);
    for (final StatusType st : result2Obj.getStatus()) {
    SwingUtilities.invokeLater(new Runnable() {

    public void run() {
    statuses.addElement(st);
    }
    });
    }

    }



  8. Press Ctrl-Shift-I to add an import statement for StatusType.



The code for getting statuses from the Twitter public timeline is now complete. Next you write a new class that returns a Component with list elements rendered in GUI components.



Creating a List Cell Rendering Component



Now you have code that gets Status objects from the Twitter Public Timeline and creates a list element for each status. However, you cannot display these raw list elements in a JList. You need to pass the data into GUI components . To accomplish this, create a new JPanel that implements javax.swing.ListCellRenderer. This JPanel returns a java.awt.Component object with the username and status passed in JLabels. You can customize the appearance of the JLabels in the JPanel.



To add a list cell rendering Component:




  1. Right-click the project's node and choose New > JPanel Form. The New JPanel Form wizard opens.


  2. Name the JPanel Item and place it in the twitterclient package.


    New JPanel Form wizard showing panel named Item and package twitterclient


  3. Click Finish. Item.java opens in the Design view of the editor.


  4. Drag and drop a Label and a Text Pane into the JPanel. The Label will display the username and the Text Pane will display that user's status message.


  5. Position the Label and the Text Pane to match how you want the data to be displayed. In the following image, the username is on the left top while the status text is below and slightly indented. The sample project has the data on the top left and the username on the bottom right. Leave enough empty space in the JPanel below the Text Pane for the Text Pane to expand when it contains longer text.


    Layout of jlabels displaying username and status text


  6. Right-click on the JLabel element and select Properties from the context menu. In the Properties, you can change the font, the color, the alignment and other qualities. Set the labelFor property to point to jTextPane1. This improves accessibility. Experiment with the properties of the label until you like the appearance. In the following image, the font color is set to blue in the Foreground property.


    JLabel properties dialog with Foreground set to blue


  7. Open the Properties dialog of the JTextPane and experiment with its appearance.


  8. Change to the Source view for Item.java. Find the Generated Code block and expand it. This shows you the code generated by the IDE when you set the properties of the JLabel and JTextPane.

    In the following image, note the blue color setting for JLabel1. Can you see what properties are set for the JTextPane?



    Code generated in Item.java by setting JLabel properties in the Design view




  9. Find the class declaration and add the code implements ListCellRenderer.

    public class Item extends javax.swing.JPanel implements ListCellRenderer {



  10. Press Ctrl-Shift-I. This action adds an import statement for javax.swing.ListCellRenderer. A warning appears saying that you need to implement all abstract methods.


  11. Add a few empty lines between the generated code block and the variable declarations. Into that space, add the following code, which implements the abstract method getListCellRendererComponent. (You can copy and paste the code, or you can try to reproduce it with code completion.) This code replaces the default label texts "username" and "text" with the Text, User, and ScreenName objects you get with the Twitter StatusType class. The code then returns an instance of Component with these new JLabel text values.

    public Component getListCellRendererComponent(JList list, Object value, int index, boolean sel, boolean focus) {
    StatusType st = (StatusType) value;
    jTextPane1.setText(st.getText());
    jLabel1.setText("<html>" + st.getUser().getScreenName() + "</html>");
    return this;
    }



  12. Press Ctrl-Shift-I. This adds import statements for the StatusType and Component classes. Save Item.java.



Now you have an Item class that returns a Component object with username and status displayed in a JLabel and a JTextPane. Next you modify TwitterJFrame to use this Component.



Displaying the Component in TwitterJFrame



In order to display the Component object created in Item.java, the JList in TwitterJFrame has to use Item.java as its cell renderer.







  1. Return to TwitterJFrame. In the Design view, select the JList. Right-click and open its Properties.

    Properties dialog for the JList element in TwitterJFrame


  2. Select the model property. Press Ctrl-Space. The custom property editor opens, showing the default text displayed in the list.


    J list custom property editor


  3. In the "Set jLlist1's model property using:" drop-down menu, select Custom Code. A text field appears where you type in the properties for jLabel1.setModel. Type statuses in the field and click OK.


    jList custom property editor showing setModel(statuses) chosen in the cusom code editor


  4. In the Properties dialog, select cellRenderer and press Ctrl-Space. The custom property editor opens.


  5. In the "Set jList1's cellRenderer property using:" drop-down menu, select Custom Code. A text field appears where you type in the properties for jList1.cellRenderer. Type new Item() and click OK.


    J List custom cell renderer properties editor showing new Item chosen




Your client application is now complete! Save all files and run the application. (Right-click project node and select Run.) The application opens, showing a list of public timeline messages and a field with your own status.



Running client displaying Twitter messages





More Exercises



Here are a few more ideas for you to explore:




  • Change your Twitter user icon (in a browser) and run the client again. Does the new icon appear?


  • Add a toolbar with some functions to the JFrame.


  • Add a new Scroll Pane with a new List that displays your friends' statuses, using the What Are You Doing Service > [statuses] > [friends_timeline.{format}] > getFriendsTimeline operation. The code is similar to the code for displaying the public timeline.



This article is originaly from http://www.netbeans.org/kb/docs/websvc/twitter-swing.html