August 21, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

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

  • August 12, 2009
  • By Cesar Otero
  • Send Email »
  • More Articles »

Sending a Direct Message

Remember, in order to send a direct message in Twitter, it is necessary for the other person to follow you, as well as for you to follow them.

The next component we'll be adding is a button on the right side panel that calls the SendDirectMessageDialog. Again, we use an anonymous inner class to implement the action.

  import twitter4j.Twitter;
  
  import javax.swing.*;
  import java.awt.event.ActionEvent;
  import java.awt.event.ActionListener;
  import java.awt.*;
  
  public class DirectMessagePanel extends JPanel {
  
      int componentsWidth = 180;
  
      public DirectMessagePanel(final Twitter twitter) {
          JButton sendDirectMessageButton = new JButton("Send Direct Message");
          sendDirectMessageButton.setSize(new Dimension(componentsWidth, 20));
          sendDirectMessageButton.setPreferredSize(new Dimension(componentsWidth, 20));
          sendDirectMessageButton.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  SendDirectMessageDialog dialog = new SendDirectMessageDialog(twitter);
                  dialog.setVisible(true);
              }
          });
  
          this.add(sendDirectMessageButton);
      }

The definition of the SendDirectMessageDialog is a little bit longer.

  import twitter4j.Twitter;
  import twitter4j.TwitterException;
  
  import javax.swing.*;
  import java.awt.event.ActionListener;
  import java.awt.event.ActionEvent;
  import java.awt.*;
  
  public class SendDirectMessageDialog extends JFrame implements ActionListener {
  
      int componentsWidth = 180;
      Twitter twitter;
      JComboBox followersComboBox;
      JTextField messageTextField;
      JButton sendButton;
  
      public SendDirectMessageDialog(Twitter twitter) {
          super("Direct Message Dialog");
  
          this.twitter = twitter;
  
          setLayout(new FlowLayout());
          setSize(new Dimension(620, 100));
          setPreferredSize(new Dimension(620, 100));
          setLocationRelativeTo(null);
  
          messageTextField = new JTextField();
          messageTextField.setSize(new Dimension(600, 20));
          messageTextField.setPreferredSize(new Dimension(600, 20));
          sendButton = new JButton("Send");
          sendButton.addActionListener(this);
  
          followersComboBox = new JComboBox();
          try {
              String[] followerArr = new String[twitter.getFollowers().size()];
              for (int i = 0; i < twitter.getFollowers().size(); i++) {
                  followerArr[i] = twitter.getFollowers().get(i).getScreenName();
              }
              followersComboBox = new JComboBox(followerArr);
          } catch (TwitterException e1) {
              e1.printStackTrace();
              JOptionPane.showMessageDialog(this, "Error loading followers list.");
          }
  
          add(messageTextField);
          add(followersComboBox);
          add(sendButton);
      }
  
      public void actionPerformed(ActionEvent e) {
          try {
              twitter.sendDirectMessage(followersComboBox.getSelectedItem().toString(), 
                   messageTextField.getText());
              JOptionPane.showMessageDialog(this, "Message Sent Successfully");
              messageTextField.setText("");
          } catch (TwitterException e1) {
              e1.printStackTrace();
              JOptionPane.showMessageDialog(this, "Error sending direct messsage.");
          }
      }
  }

the first thing to notice is that we inherit from JFrame this time. The SendDirectMessageDialog consists of a JTextField, where the user inputs the message, a JComboBox which displays the people we can send direct messages to, and the all important send JButton.



Click here for larger image

Figure 7 - Direct message dialog

To get the list of your followers, use the Twitter object's method getFollowers() which returns a List of User objects. Using a for loop, we iterate through this list, and insert each user name into a string array, as done previously. The follower string array, is then passed into the constructor of the JComboBox upon instantiation. To actually send the message, use the method sendDirectMessage() of the Twitter object, which requires two arguments; the user name, and the message to be sent. The user name is taken from the selected item of the JComboBox, and the message string from the JTextField. If everything is a-ok, a pop-up confirming the message appears. If any exception is raised, it is caught and another pop up appears displaying an error message.


Figure 8 - Direct message success pop up

Displaying Current Trends

Finally, the last part of our sample application is a component that displays the current trends on Twitter. This component contains a JLabel with the text Trends, and a JList which displays the trends.

import twitter4j.Trends; 
import twitter4j.Twitter;
import twitter4j.TwitterException;
import javax.swing.*; 
import java.awt.*; 

public class TrendsPanel extends JPanel {
   Twitter twitter;
   int componentsWidth = 180;
   public TrendsPanel(Twitter twitter) throws TwitterException 
   { 
      super(new FlowLayout());
      this.setSize(new Dimension(componentsWidth, 220));
      this.setPreferredSize(new Dimension(componentsWidth, 220));
      JLabel trendsLabel = new JLabel("Trends");
      trendsLabel.setSize(new Dimension(componentsWidth, 20));
      trendsLabel.setPreferredSize(new Dimension(componentsWidth, 20));
      Trends trends = twitter.getTrends();
      String trendsArr[] = new String[trends.getTrends().length];
      for (int i = 0; i < trends.getTrends().length; i++) {
          trendsArr[i] = trends.getTrends()[i].getName();
      } 
      JList trendsList = new JList(trendsArr);
      trendsList.setSize(new Dimension(componentsWidth, 200));
      trendsList.setPreferredSize(new Dimension(componentsWidth, 200));
      this.add(trendsLabel);
      this.add(trendsList); 
   } 
}

The TrendsPanel, again, inherits from JPanel, uses a flow layout, and throws a TwitterException if there are any problems when the method twitter.getTrends() is called. The getTrends returns a single Trends object (notice it's in plural form). The method getTrends() of class Trend, returns an array of Trend objects (notice it's in singular form). In a similar fashion to how we extracted the searched tweets earlier, we create a string array called trendsArr and populate it with a for loop that gets each trend by calling trends.getTrends()[i].getName(), where it is the index value from the loop. The trends array is then passed in to the JList. You should see something like the following:


Figure 9 - The current trends JPanel.

Putting it All Together

Now that all of our classes are defined, it's just a matter of creating a main, and putting all of the components together.

  import twitter4j.*;
  
  import javax.swing.*;
  import java.awt.*;
  import java.net.MalformedURLException;
  
  public class Application extends JFrame {
      public Application() throws MalformedURLException, TwitterException {
          super("Simple Twitter App");
          getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS));
  
          LoginDialog login = new LoginDialog();
          String userName = login.getUserName();
          String password = login.getPassword();
  
          Twitter twitter = new Twitter(userName, password);
  
          add(new FollowerPanel(twitter));
          add((new StatusTimeLine(twitter)).getTimeLinePanel());
          add(new RightSideBar(twitter));
      }
  
      public static void main(String[] args) throws MalformedURLException, TwitterException {
          Application application = new Application();
          application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          application.setSize(Toolkit.getDefaultToolkit().getScreenSize());
          application.setVisible(true);
  
      }
  }

We create a class, Application, which extends from JFrame, and throws both MalformedURLException and TwitterException. This time, we use a box layout to place our three main components, the FollowerPanel, StatusTimeLine, and RightSideBar. In following with the originally prescribed requirements, the LoginDialog is first created, from that we get the user name and password which are passed in to the instantiation of our top level Twitter object.

In the main, we create the Application instance, set the default close operation to exit on close, and make it so the window is maximized. If everything is good with the world, when you compile and run, you should see the login dialog.

Conclusion

You've probably noticed that this program can't do half the things that the Twitter website can do. It's not meant as a replacement, but rather a foundation for your creativity. You could create a desktop application that shows recent updates, automatically, or use the twitter4j api to get statistics and then save it to an SQL database or even, write a web application that adds your twitter information to a small sidebar.

There are already dozens of Twitter applications out there, not just on the web, but also on mobile platforms like the iPhone. One of the more interesting applications I found while researching for this article, is http://asktwitr.com which searches for tweets. But different from other twitter search applications, this one shows the location of the person who sent the tweet on a Google map.

Who knows, maybe you'll come up with the next killer app.

References

1. Java Swing
by Marc Loy, Robert Eckstein, Dave Wood, James Elliot, and Brian Cole
2003 O'Reilly Media, Inc.
2. Twitter tips, tricks, and tweets
by Paul McFredries
2009 Wiley Publishing, Inc.
3. Libraries has a list of api's
4. The twitter4j repository




Page 4 of 4



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel