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 friends 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 sample.

Contents

Content on this page applies to NetBeans IDE 6.9-7.1

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

Software or Resource Version Required
NetBeans IDE Java EE download bundle
Java Development Kit (JDK) Version 6 or version 7
User name and password for a Twitter account

Designing the JFrame

In this step you create the GUI elements that will display the Twitter friends 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. Press Alt-Insert, or right-click and select Insert Code from the context menu. A menu of code to insert opens.

    Important: If the Generate REST Client option does not appear, Java EE support is either not installed or not activated. Go to Tools > Plugins, open the Installed tab, and check that Java Web and EE support is present and activated. If Java Web and EE support is not listed, open the Available Plugins tab and install it. If you do not want to install or activate all Java Web and EE support, you can install and activate only RESTful Web Services support.

    Menu of code to insert in initUserInfo method
  3. Click Generate REST Client. The Available REST Resources dialog opens.
    Available REST Resources dialog
  4. Select the IDE Registered radio button and click Browse. Navigate to Twitter > Twitter OAuth > [statuses] > [user_timeline.{format}]. Click OK.
    Services window with Web Services tree showing Twitter getUserTimelineById operation chosen
  5. The Available REST Resources dialog now shows the selected Twitter OAuth user_timeline resource, the corresponding class name, and OAuth authentication type. Click OK.
    Filled out Available REST Resource dialog
  6. A dialog opens asking if you want to generate Java objects from the XML schema references in the WADL file. Click Yes.
  7. At the end of the TwitterJFrame class, the IDE generates an internal class called Twitter_OAuth_user_timeline__format_JerseyClient.

    The internal class is complex and contains the following fields, methods and inner classes:

    • CONSUMER_KEY: Consumer Key string
    • CONSUMER_SECRET: Consumer Sectret string
    • initOAuth(): method for OAuh intitialization
    • getUserTimeline(): method corresponding to HTTP method: getUserTimeline (from the REST resource)
    • makeOAuthRequestUnique(): useful for multiple API calls in one session
    • login: used to login to the Twitter Application (forces the authorization). This method calls two more generated methods, getOAuthAccessToken and getOAuthRequestToken.

    Here is the class structure as shown in the Navigator window.

    Navigator window showing Twitter_OAuth_user_timeline__format_JerseyClient class
  8. In TwitterJFrame immediately above the internal Twitter_OAuth_user_timeline__format_JerseyClient class, insert the following line of code. This code creates a variable called client to represent an instance of the internal class.
    private Twitter_OAuth_user_timeline__format_JerseyClient client;
    Code snippet showing client variable immediately above internal class
  9. Locate the main method in TwitterJFrame. Above this method, create a new method called initUserInfo that throws a MalformedURLException and an IOException.
    private void initUserInfo() throws MalformedURLException, IOException {
    
    
    
    }
  10. Insert the following code into the method body of initUserInfo. Comments in the code explain what the code does.
    private void initUserInfo() throws MalformedURLException, IOException {
    
    //Create an instance of the internal service class client = new Twitter_OAuth_user_timeline__format_JerseyClient("xml");
    //Log in, get tokens, and append the tokens to the consumer and secret //keys client.login(); client.initOAuth();
    //Call getUserTimeline, get a list of statuses, pass the most recent //status as a StatusType object, and display the text of that object //in the JTextField Statuses statuses = client.getUserTimeline(Statuses.class, null, null, null, "1"); StatusType st = statuses.getStatus().get(0); jTextField1.setText(st.getText().trim());
    //Get a UserType object from the StatusType object, get the URL of that //user's icon, and display that icon in the JLabel UserType user = st.getUser(); String iconSrc = user.getProfileImageUrl(); URL iconUrl = new URL(iconSrc); ImageIcon icon = new ImageIcon(iconUrl, user.getScreenName()); jLabel1.setIcon(icon); }
  11. Open the Fix Imports dialog (Ctrl/⌘-Shift-I, or from context menu). In the dialog, select twitter.twitteroauth.twitterresponse.StatusType and not the default Java StatusType class.
    Fix Imports dialog after completing initUserInfo method
  12. Add a try/catch block to the TwitterJForm constructor to call initUserInfo when the application runs. Fix Imports after adding the try/catch block.
    public TwitterJFrame() {
        initComponents();
    
        try {
            initUserInfo();
        } catch (IOException ex) {
            Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
     }

After you get OAuth keys from Twitter, 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.

Getting OAuth Keys from Twitter

In order for the Java application to access Twitter data, you need to get CUSTOMER and CUSTOMER_SECRET keys, along with a verification string, from Twitter. Twitter uses OAuth authorization, which requires these keys. However, OAuth is set up with the expectation that it will be called by a web application on a server. In order to get the authorization keys, you register a "dummy" web application.

To get the OAuth keys from Twitter:

  1. Open a browser. Go to the Twitter > Applications page and click Register a new application. You need to be logged into a Twitter account. Make sure you are logged into the correct account, if you have multiple accounts.
  2. Type an arbitrary name in the Application Name text field. Application names need to be unique across Twitter.
  3. Type a description into the Description field. This is required. You can type something like "Java application created in NetBeans IDE calling the user_timeline operation."
  4. Type an arbitrary URL into the Application Website field.
  5. In the Application Type option, select the Client radio button.
  6. In the Default Access Type section, select the Read & Write button.

    Caution: Be certain you select Read & Write. Although you can go back and edit your settings later, this does not seem to affect your application's access privileges.

  7. Leave other options default and press Save. A browser page opens with the details of the application you registered. The important details are the Consumer key and Consumer secret.
  8. Copy the Consumer key from the browser. In the IDE, locate the line where CONSUMER_KEY is set. Paste the value of the consumer key between the quotation marks.
    TwitterClient showing CONSUMER_KEY and CONSUMER_SECRET location
  9. Copy and paste the Consumer secret key from the browser into TwitterSwingClient. Save your changes.

Running the Project

Now that you have the Consumer key and Consumer secret key, you can run the project. The application calls Twitter, which opens a browser window for you to allow the application to access data.

To run the project:

  1. Right-click the TwitterSwingClient project node and select Run from the context menu.
  2. A browser window opens asking if you want to allow your registered application to access your Twitter data. Click Allow.
  3. The browser window updates to a new window showing you a PIN. Copy this PIN.
  4. In the IDE, the output window shows a request that you type the oauth_verifier string. Paste the PIN after the colon : and press Enter.
    Output window in IDE asking for verifier string, which has not yet been pasted
  5. The desktop client opens, displaying your latest Twitter status message.
    Running application, showing user icon and status

Calling Multiple Services

The final design of the application requires calls to three Twitter services: user_timeline{format} (already called), update{format}, and friends_timeline{format}. The calls to these services need to share one login. For the calls to share the same login, they must be in the same client class. Calling multiple services from one client requires two steps:

  • Add multiple services to one client class.
  • Modify the resource paths in the client class

Adding services and combining calls to one class

In this section you first add clients for the other services and merge them into one general client.

To add multiple services:

  1. Press Alt-Insert and select Generate REST Client.
    Menu of code to insert in initUserInfo method
  2. Follow the same procedure to generate a REST client that you followed in the section Showing Your User Status, but select the [statuses] > [update.{format}] service. The IDE generates the internal class Twitter_OAuth_update__format_JerseyClient, which is similar to the Twitter_OAuth_user_timeline__format_JerseyClient class.
    The Available REST Resources dialog showing the update format service
  3. Repeat steps 1 and 2 above, but add a client for the [friends_timeline.{format}] service.
  4. Change the name of the original Twitter_OAuth_user_timeline__format_JerseyClient class. You will make this the general client class that calls all 3 services. Select an instance of the name Twitter_OAuth_user_timeline__format_JerseyClient and press Ctrl-R, or right-click and select Refactor > Rename. The Rename Class dialog opens. Type in the new name TwitterClient.
    Rename Class dialog with new name TwitterClient
  5. Click Refactor. The IDE replaces all instances of the class name.
    Class name changed in multiple places
  6. In the Navigator window, locate the Twitter_Oauth_friends_timeline__format_JerseyClient class. In that class, locate and double-click the getFriendsTimeline method.
    Navigator window showing the getPublicTimeline method
  7. The cursor in the Editor moves to the getFriendsTimeline method. Cut that method (reproduced below).
    public <T> T getFriendsTimeline(Class<T> responseType, String since, String since_id, String page, String count) throws UniformInterfaceException {
          String[] queryParamNames = new String[]{"since", "since_id", "page", "count"};
          String[] queryParamValues = new String[]{since, since_id, page, count};
          return webResource.queryParams(getQueryOrFormParams(queryParamNames, queryParamValues)).accept(javax.ws.rs.core.MediaType.TEXT_XML).get(responseType);
    }
  8. Paste the getFriendsTimeline method into the TwitterClient internal class, below the getUserTimeline method.
  9. Cut and paste the updateStatus method from Twitter_OAuth_update__format_JerseyClient into TwitterClient, below the getFriendsTimeline method.

Modifying the resource paths

All the Twitter service calls are now in one client class. However, the resource paths in that client class are not constructed correctly. The IDE generated resource paths specific for the user_timeline service when it originally generated the class. You need to modify the class so that at the class level, the resource path is generic, and specific paths are assigned by the service call methods.

To modify the resource paths:

  1. Locate the TwitterClient constructor and remove the String format parameter.
    Before and after view of removing parameter from constructor
  2. A red error bar appears in the right margin. Click it, and you go to the line in initUserInfo that instantiates the TwitterClient class. This line is client = new TwitterClient("xml");. Delete the parameter "xml", because the TwitterClient constructor no longer takes it. The line now is client = new TwitterClient();. The error icons disappear.
  3. Return to the TwitterClient constructor. (The Navigator window can help you.) Locate the following line:
    String resourcePath = java.text.MessageFormat.format("statuses/user_timeline.{0}", new Object[]{format}); 

    This line sets the resourcePath for the entire class. Change the line so that resourcePath points to the parent statuses directory. The line now reads:

    String resourcePath = "statuses";
  4. Navigate to the getUserTimeline method. Locate the return line:
    return webResource.queryParams(getQueryOrFormParams(queryParamNames, queryParamValues))...;

    Append path information (in boldface, below) to the beginning of the call.

    return webResource.path("user_timeline.xml").queryParams(getQueryOrFormParams(queryParamNames, queryParamValues)).accept(javax.ws.rs.core.MediaType.TEXT_XML).get(responseType);
  5. Navigate to the getFriendsTimeline method. Locate the return line:
    return webResource.queryParams(getQueryOrFormParams(queryParamNames, queryParamValues)).accept(javax.ws.rs.core.MediaType.TEXT_XML).get(responseType);

    Append path information to the beginning of the call.

    return webResource.path("friends_timeline.xml").queryParams(getQueryOrFormParams(queryParamNames, queryParamValues)).accept(javax.ws.rs.core.MediaType.TEXT_XML).get(responseType);
  6. Navigate to the updateStatus method. Locate the return line:
    return webResource.type(javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED)...

    Append path information to the beginning of the call.

    return webResource.path("update.xml").type(javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED).post(responseType, getQueryOrFormParams(formParamNames, formParamValues));
  7. Locate and comment out the TwitterClient's setResourcePath method. It is not ever called, but this is a precaution.
  8. Delete the classes Twitter_OAuth_update__format_JerseyClient and Twitter_Oauth_friends_timeline__format_JerseyClient.

You now have all three services available from the JerseyClient class.

Important: You change three return statements in three methods in the procedure above. Make sure you change all three!

Adding an Update Status Action

  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. Fill in the jButton1ActionPerformed method body as follows:

    Caution: When you update your status, it will appear UTF-8-encoded, with spaces either as + signs or %21 symbols, etc. However, if you do not convert the text field contents to UTF-8, the application will fail with "Invalid signature" if you type any spaces in your status message! If anyone finds a way around this, please use the Feedback link at the bottom of the tutorial to contact us.

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        String rawStatus = jTextField1.getText().trim();
        String status = URLEncoder.encode(rawStatus, "UTF-8");
        client.makeOAuthRequestUnique();
        try {
        client.updateStatus(String.class, status, null);
        } catch(UniformInterfaceException ex) {
            System.out.println("Exception when calling updateStatus = " + ex.getResponse().getEntity(String.class));
        }
    
    }    

This code gets the text from the text field and passes it to the updateStatus class. Note the call to makeOAuthRequestUnique. The code calls this method because the application is already logged in and authenticated by the calls to login and initOAuth from initUserInfo when the application initialized. The makeOAuthRequestUnique method increases existing OAuth nonce and timestamp parameters to make each request unique.

Caution: It is not entirely clear if it is better to call makeOAuthRequestUnique or initOAuth here. If you experience authentication issues, please experiment with both forms.

Also note that the call to updateStatus is wrapped in a try/catch block. This helps you debug any issues that could arise when you call updateStatus.

Displaying Usernames and Statuses in the JFrame

Now you set up the application to display the usernames and statuses of your Twitter friends.

  • To get the usernames and statuses from Twitter, the application calls the Twitter getFriendsTimeline operation when the application runs. To set this up, create a new run method that overrides the run method in main. Insert calls to getFriendsTimeline into this method.
  • To have the display update automatically, wrap the run method containing the getFriendsTimeline operation in a java.util.TimerTask that executes the run method every 75 seconds.
  • The application displays the data as cells in a list. You need to pass the data into GUI components that can be rendered as cells in the list, and you also want to format the display of the data. 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. Tweak the format of the JPanel.
  • In TwitterJFrame, set up the JList to display the Component objects returned by the JPanel.

Creating a TimerTask

To update the display of the Twitter friends 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();
            try {
                initUserInfo();
            } catch (IOException ex) {
                Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
  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();
            try {
                initUserInfo();
            } catch (IOException ex) {
                Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
                        
  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 30 seconds before running the first time and run again every 75 seconds. (The long initial delay is to give you time to log in.) 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() {

    }, 30000, 75000);
    initComponents(); try { initUserInfo(); } catch (IOException ex) { Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE, null, ex); } }

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

Adding a run Method With the getFriendsTimeline Operation

To display usernames and statuses, the application first gets this data from Twitter. Twitter SaaS provides the getFriendsTimeline operation for getting usernames and statuses. To execute the getFriendsTimeline 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 getFriendsTimeline as elements of a DefaultListModel object.

To add a run method with the getFriendsTimeline operation:

  1. Above the TwitterJFrame constructor, create a DefaultListModel object named statusesListModel.
    public class TwitterJFrame extends javax.swing.JFrame {
    
        private DefaultListModel statusesListModel = 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(); try { initUserInfo(); } catch (IOException ex) { Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE, null, ex); }
  4. Insert the following code into the body of the run method.
    @Override
    public void run() {
        System.out.println("Timer Task is running");
        try {
            client.initOAuth();
            Statuses response = client.getFriendsTimeline(Statuses.class, null, null, null, "10");
            // Clear the list model so it does not replicate the contents from the last run
            statusesListModel.clear();
            // Create a Status Type object for every status in the Status list, and add an element
            // to the list model for every status type object
            for (final StatusType st : response.getStatus()) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        statusesListModel.addElement(st);
                    }
                });
            }
        } catch (UniformInterfaceException ex) {
        System.out.println("Exception when calling getFriendsTimeline = " + ex.getResponse().getEntity(String.class));
        }
    }

The code for getting statuses from the Twitter friends 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 Friends 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 (⌘-Shift-I on MacOS). 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 twitteroauth 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 (⌘-Shift-I on MacOS). This adds import statements for the StatusType and Component classes. Select the twitteroauth version of StatusType. 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 statusesListModel 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 timeline messages and a field with your own status.

Running client displaying Twitter messages

Connecting Through a Proxy;

If you are connected to the Internet through a proxy, you need to configure both the IDE and your TwitterSwingClient project to use the proxy settings.

To configure the IDE, open Tools > Options > General. Locate the Proxy Settings section. You have the options of using no proxy settings, using the system proxy settings, or using manual proxy settings. The IDE gets your system proxy settings from your default system web browser.

For the TwitterSwingClient project, you need to specify the proxy that the HTTP protocol handler uses. This is described in Java SE 6 documentation. You specify the proxy in options passed to the virtual machine. With the NetBeans IDE, these options are set in the Properties dialog.

To specify the proxy for the TwitterSwingClient project:

  1. In the Projects window, right-click your TwitterSwingClient project node and select Properties. The Properties dialog opens.
  2. In the Categories tree, select Run. The Run properties display.
  3. In the VM Options field, enter -Dhttp.proxyHost=server -Dhttp.proxyPort=port. Replace "server" and "port" with the host name and port of your proxy server!
    Proxy settings in VM options in Project properties dialog

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.

See Also

For more information about using NetBeans IDE to create and consume web services and to design GUIs, see the following resources:

To send comments and suggestions, get support, and keep informed about the latest developments on the NetBeans IDE Java EE development features, join  the nbj2ee@netbeans.org mailing list.

get support for the NetBeans

Support


By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2013, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo