uk.ac.essex.wonderland.modules.twitter.client.TwitterPanel.java Source code

Java tutorial

Introduction

Here is the source code for uk.ac.essex.wonderland.modules.twitter.client.TwitterPanel.java

Source

/*
 *  +Spaces Project, http://www.positivespaces.eu/
 *
 *  Copyright (c) 2010-12, University of Essex, UK, 2010-12, All Rights Reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package uk.ac.essex.wonderland.modules.twitter.client;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JTable;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import uk.ac.essex.wonderland.modules.twitter.client.TweetTableModel.TweetCell;

/**
 * The Twitter Control Panel
 * @author Bernard Horan
 */
public class TwitterPanel extends javax.swing.JPanel {

    private static boolean DEBUG = false;
    private static final ResourceBundle bundle = ResourceBundle
            .getBundle("uk/ac/essex/wonderland/modules/twitter/client/resources/Bundle");
    private TwitterCell cell;

    /** Creates new form TwitterPanel */
    public TwitterPanel() {
        initComponents();
        //Create a new table model for the tweets and set it to be the table's model
        tweetTable.setModel(new TweetTableModel());
        //Set the width of the first column to be the width of an icon
        TableColumn column = tweetTable.getColumnModel().getColumn(0);
        column.setMaxWidth(TweetIconRenderer.ICON_DIM);
        //Set the renderer for tweetcells, this is a workaround because the Tweet implementation class is not visible
        TweetTextRenderer tweetTextRenderer = new TweetTextRenderer();
        tweetTextRenderer.setWrapStyleWord(true);
        tweetTextRenderer.setLineWrap(true);
        tweetTextRenderer.setEditable(false);
        tweetTable.setDefaultRenderer(TweetCell.class, tweetTextRenderer);
        //Set the renderer for ImageIcons, this sets the icon to be at the top of its cell
        tweetTable.setDefaultRenderer(ImageIcon.class, new TweetIconRenderer());
        //Set the gap between columns to 5 pixels
        tweetTable.setIntercellSpacing(new Dimension(5, 0));
        //Show horizontal lines
        tweetTable.setShowHorizontalLines(true);
        //Remove the header from the table
        tweetTable.setTableHeader(null);
        //Search when user hits <CR>
        queryField.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                searchButtonActionPerformed(e);
            }
        });

    }

    public TwitterPanel(TwitterCell cell) {
        this();
        this.cell = cell;
        //Set current query
        setQueryString(cell.getQueryString());
        //Set the current results
        List<Tweet> tweetList = cell.getTweetList();
        if (tweetList != null) {
            TweetTableModel tableModel = (TweetTableModel) tweetTable.getModel();
            for (Tweet tweet : tweetList) {
                tableModel.addTweet(tweet);
            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        searchButton = new javax.swing.JButton();
        queryField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tweetTable = new javax.swing.JTable();

        java.util.ResourceBundle bundle = java.util.ResourceBundle
                .getBundle("uk/ac/essex/wonderland/modules/twitter/client/resources/Bundle"); // NOI18N
        jLabel1.setText(bundle.getString("TwitterPanel.jLabel1.text")); // NOI18N

        searchButton.setText(bundle.getString("TwitterPanel.searchButton.text")); // NOI18N
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        tweetTable
                .setModel(new javax.swing.table.DefaultTableModel(
                        new Object[][] { { null, null, null, null }, { null, null, null, null },
                                { null, null, null, null }, { null, null, null, null } },
                        new String[] { "Title 1", "Title 2", "Title 3", "Title 4" }));
        tweetTable.setRowHeight(88);
        tweetTable.setRowSelectionAllowed(false);
        tweetTable.setShowGrid(true);
        tweetTable.setShowHorizontalLines(false);
        tweetTable.setShowVerticalLines(false);
        jScrollPane1.setViewportView(tweetTable);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(jLabel1)
                .add(layout.createSequentialGroup()
                        .add(queryField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 269,
                                org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(searchButton))
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 363, Short.MAX_VALUE));
        layout.setVerticalGroup(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                                .add(queryField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
                                        org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
                                        org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .add(searchButton))
                        .add(12, 12, 12).add(jLabel1)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED,
                                org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 406,
                                org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)));
    }// </editor-fold>//GEN-END:initComponents

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed

        if (DEBUG) {
            String queryString = queryField.getText().trim();
            if (queryString.isEmpty()) {
                return;
            }
            Query query = new Query(queryString);
            query.setLang("en");

            Twitter twitter = new TwitterFactory().getInstance();
            try {
                QueryResult result = twitter.search(query);
                String warning = result.getWarning();
                if (warning != null) {
                    System.err.println(warning);
                }
                @SuppressWarnings("unchecked")
                List<Tweet> tweets = result.getTweets();
                for (Tweet tweet : tweets) {
                    addTweet(tweet);
                }
            } catch (TwitterException ex) {
                Logger.getLogger(TwitterPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            String query = queryField.getText().trim();
            if (!query.isEmpty()) {
                cell.performQuery(query);
            }
        }

    }//GEN-LAST:event_searchButtonActionPerformed
     // Variables declaration - do not modify//GEN-BEGIN:variables

    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField queryField;
    private javax.swing.JButton searchButton;
    private javax.swing.JTable tweetTable;
    // End of variables declaration//GEN-END:variables

    /**
     * Testing only
     * @param args
     */
    public static void main(String args[]) {
        DEBUG = true;
        JFrame j = new JFrame("Test");
        j.add(new TwitterPanel());
        j.pack();
        j.setVisible(true);
    }

    void addTweet(final Tweet aTweet) {
        final TweetTableModel tweetModel = (TweetTableModel) tweetTable.getModel();
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                tweetModel.addTweet(aTweet);
            }
        });

    }

    final void setQueryString(final String query) {
        if (query != null) {
            SwingUtilities.invokeLater(new Runnable() {

                public void run() {
                    queryField.setText(query);
                }
            });
        }
    }

    class TweetTextRenderer extends JTextArea implements TableCellRenderer {
        // This is the only method defined by TableCellRenderer.
        // We just reconfigure the JTextArea each time we're called.

        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            TweetCell tweetCell = (TweetCell) value;
            setCellText(tweetCell);
            if (isSelected) {
                setBackground(table.getSelectionBackground());
                setForeground(table.getSelectionForeground());
            } else {
                setBackground(table.getBackground());
                setForeground(table.getForeground());
            }
            setFont(table.getFont());
            setOpaque(true);
            return this;
        }

        private void setCellText(TweetCell tweetCell) {
            StringBuilder labelText = new StringBuilder();

            //Add the author
            labelText.append(tweetCell.getFromUser());
            labelText.append("\n");
            //Add the text
            labelText.append(tweetCell.getText());

            setText(labelText.toString());
        }
    }

    class TweetIconRenderer extends JLabel implements TableCellRenderer {
        static final int ICON_DIM = 48;
        // This is the only method defined by TableCellRenderer.
        // We just reconfigure the JLabel each time we're called.

        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            //System.out.println("In icon renderer");
            Icon icon = (Icon) value;
            this.setIcon(icon);
            this.setVerticalAlignment(SwingConstants.TOP);
            return this;
        }
    }
}