February 26, 2021
Hot Topics:

Writing Your own Twitter Application Using Java, Swing, and Twitter4j

  • By Cesar Otero
  • Send Email »
  • More Articles »

Again, as with the follower panel, an instance of the Twitter object is passed in to the constructor. In order to retrieve the list of updates, which we want to use to populate the status JList upon loading the program, we get the list of tweets using the method getUserTimeline() of object twitter. This returns a List of type Status. The time line area, will display both the time of the tweet, and the message. The time of the tweet is retrieved with the method getCreatedAt() of object Status, which returns a Date object. A SimpleDateFormat object is used to return the date as a string in format dd-MMM-yy HH:mm for clarity. Each tweet message is retrieved by a call to method getText(). The date and message are concatenated together and inserted into a string array. The status JList is then populated with the status string array, statusArr. Since, you almost certainly have hundreds of tweets :-) we'll place our JList in a scrollbar for easy viewing.

In short, when the update button is pressed, the method actionPerformed, sends a tweet, clears the text area, updates the time panel, and redraws the interface with the updated information. If anything goes wrong with the update process, a pop up appears warning the user of an error.

Click here for larger image

Figure 4 - The status time line

Searching For Tweets

For this part of the application we'll place the last three pieces of functionality, searching for tweets, sending a direct message, and displaying current trends, on a panel which we will generically refer to as the right side bar.

  import twitter4j.*;
  import javax.swing.*;
  import java.awt.*;
  public class RightSideBar extends JPanel{
      int componentsWidth = 180;
      int panelHeight = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
      public RightSideBar(Twitter twitter) throws TwitterException {
          super(new FlowLayout());
          this.setSize(componentsWidth, panelHeight);
          this.setPreferredSize(new Dimension(componentsWidth, panelHeight));
          this.setMaximumSize(new Dimension(componentsWidth, panelHeight));
          this.add(new SearchTweetsPanel(twitter));
          this.add(new DirectMessagePanel(twitter));
          this.add(new TrendsPanel(twitter));

The previous code listing shows the setup for the RightSideBar class. It inherits from JPanel, uses a flow layout, and contains instances of SearchTweetsPanel, DirectMessagePanel, and TrendsPanel. The class definition of SearchTweetsPanel is as follows:

  import twitter4j.*;
  import javax.swing.*;
  import java.awt.*;
  import java.awt.event.ActionListener;
  import java.awt.event.ActionEvent;
  public class SearchTweetsPanel extends JPanel {
      Twitter twitter;
      JButton searchTweetsButton;
      JTextField searchTweetsTextField;
      int componentsWidth = 180;
      int panelHeight = 50;
      public SearchTweetsPanel(final Twitter twitter) {
          super(new FlowLayout());
          this.twitter = twitter;
          this.setSize(componentsWidth, panelHeight);
          this.setPreferredSize(new Dimension(componentsWidth, panelHeight));
          this.setMaximumSize(new Dimension(componentsWidth, panelHeight));
          searchTweetsButton = new JButton("Search Tweets");
          searchTweetsButton.setSize(new Dimension(componentsWidth, 20));
          searchTweetsButton.setPreferredSize(new Dimension(componentsWidth, 20));
          searchTweetsTextField = new JTextField();
          searchTweetsTextField.setSize(componentsWidth, 20);
          searchTweetsTextField.setPreferredSize(new Dimension(componentsWidth, 20));
          searchTweetsTextField.setMinimumSize(new Dimension(componentsWidth, 20));
          searchTweetsButton.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  QueryResult q = null;
                  java.util.List<Tweet> tweets = null;
                  try {
                      q = twitter.search(new Query(searchTweetsTextField.getText()));
                      tweets = q.getTweets();
                      String[] tweetArr = new String[tweets.size()];
                      for (int i = 0; i < tweets.size(); i++) {
                          tweetArr[i] = tweets.get(i).getFromUser() + "-" + tweets.get(i).getText();
                      // open a dialog box and show result
                      JFrame resultDialog = new JFrame();
                      JList list = new JList(tweetArr);
                      JScrollPane scrollPane = new JScrollPane(list,
                              JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, // vertical bar
                      resultDialog.setSize(new Dimension(1100, 320));
                      resultDialog.setPreferredSize(new Dimension(1100, 320));
                  } catch (TwitterException e1) {
                      JOptionPane.showMessageDialog(null, "Error occurred during search, try again.");

This class contains a JButton(searchTweetsButton), a JTextField, a dialog window defined inside of the constructor, and a JOptionPane which displays on error if there are any problems querying the tweets. Just to keep things compact, we use an anonymous inner class defined inside of the addActionListener method of the searchTweetsButton. This is where all the tweeting magic goes on. The method twitter.search() expects a twitter4j.Query object, which itself expects a string as input. This string contains the tokens that we're searching for in tweets. For example,

  Query q = new Query(terminator);

This creates a Query object that's to search for tweets that contain the string terminator. In order to actually get some searching done, we call the method twitter.search(new Query(my query string)). In our application, we get our string from the JTextField, searchTweetsTextField by calling it's getText() method.

The call to search returns a QueryResult object. To actually get the tweet strings is a little bit more involved. First, we need a java.util.List collection which contains the type Tweet. In order to populate the list, call the QueryResult objects getTweets() method. Easy enough. Now, we create an array of strings, tweetArr, that will hold each tweet text. We iterate through the list of tweets, and insert into tweetArr the user name, and that tweet. The result of the search is displayed in resultDialog which is of type JFrame.

Click here for larger image

Figure 5 - Search results dialog

If anything goes wrong, network connection error, or an empty query string is sent, an exception is thrown. In which case we get the following error pop up.

Figure 6 - Error pop up

Page 3 of 4

This article was originally published on August 12, 2009

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date