Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Multiple newbie issues

  1. #1
    Junior Member
    Join Date
    May 2012
    Location
    Sweden
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Multiple newbie issues

    I am new to java and I am currently trying to write an application to stream tweets using twitter4j. I have made some progress and am able to get the streams to a textbox. I am struggling with a few things though:
    I want to be able to start the stream using a "Go"-button. I am sorta able to do this at the moment by placing the listening code inside the button class(?!).
    But the thing is that I also want to be able to stop the streaming by removing the listener and to this is need to place the declaration of the listener outside the "Go"-button. Where should I place it?

    I am also getting some compilation error on the line with "RateLimitStatus rateLimitStatus= twitter.getRateLimitStatus();" I can't understand why because when I used jCreatorLE this worked fine. Now I am using Netbeans and it isn't happy with something. The errorlightbulb is saying something like this "unreported exception twitter4.TwitterException; must be caught or declared to be thrown... Surround with... Introduce..." I take it has something to do with error catching? But how and where do I catch it?

    I am grateful for any help at all! I hope I have provided enough info if not please let me know.

    The code in its entirety:
     
    /**
     *
     * @author Patricks
     */
     
     
    import twitter4j.Status;
    import twitter4j.StatusDeletionNotice;
    import twitter4j.StatusListener;
    import twitter4j.TwitterException;
    import twitter4j.TwitterStream;
    import twitter4j.TwitterStreamFactory;
    import twitter4j.conf.ConfigurationBuilder;
    import twitter4j.Twitter;
    import twitter4j.RateLimitStatus;
    import twitter4j.TwitterFactory;
    public class TwitterAppGUI extends javax.swing.JFrame {
     
        /**
         * Creates new form TwitterAppGUI
         */
        long noTweets =0;
     
        public TwitterAppGUI() {
            initComponents();
        }
        /**
         * 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.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
     
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextAreaOutput = new javax.swing.JTextArea();
            jLabelNoTweets = new javax.swing.JLabel();
            jButtonGo = new javax.swing.JButton();
            jCheckBoxStoreTweets = new javax.swing.JCheckBox();
            jButtonStop = new javax.swing.JButton();
            jCheckBoxShowTweets = new javax.swing.JCheckBox();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
     
            jTextAreaOutput.setColumns(20);
            jTextAreaOutput.setEditable(false);
            jTextAreaOutput.setRows(10);
            jScrollPane1.setViewportView(jTextAreaOutput);
     
            jLabelNoTweets.setText("No. tweets:");
     
            jButtonGo.setText("Go");
            jButtonGo.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButtonGoActionPerformed(evt);
                }
            });
     
            jCheckBoxStoreTweets.setText("Store tweets in file");
     
            jButtonStop.setText("Stop");
            jButtonStop.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButtonStopActionPerformed(evt);
                }
            });
     
            jCheckBoxShowTweets.setText("Show tweets");
            jCheckBoxShowTweets.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jCheckBoxShowTweetsActionPerformed(evt);
                }
            });
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabelNoTweets)
                            .addContainerGap())
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jCheckBoxStoreTweets)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jButtonGo)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jButtonStop))
                                .addComponent(jCheckBoxShowTweets))
                            .addGap(51, 51, 51)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 777, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(0, 38, Short.MAX_VALUE))))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabelNoTweets)
                    .addGap(26, 26, 26)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(78, 78, 78)
                            .addComponent(jCheckBoxStoreTweets)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jCheckBoxShowTweets)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jButtonGo)
                                .addComponent(jButtonStop)))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 424, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(0, 8, Short.MAX_VALUE)))
                    .addContainerGap())
            );
     
            pack();
        }// </editor-fold>
     
        private void jButtonGoActionPerformed(java.awt.event.ActionEvent evt) {                                          
            ListenTwitter();
        }                                         
     
        private void jButtonStopActionPerformed(java.awt.event.ActionEvent evt) {                                            
    jTextAreaOutput.setText("testing");        // TODO add your handling code here:
    //this is where I would like to be able to stop the streaming
        }                                           
     
        private void jCheckBoxShowTweetsActionPerformed(java.awt.event.ActionEvent evt) {                                                    
            // TODO add your handling code here:
        }                                                   
     
        public void ListenTwitter(){
            ConfigurationBuilder cb = new ConfigurationBuilder();
            cb.setDebugEnabled(true);
            cb.setOAuthConsumerKey("bbb");
            cb.setOAuthConsumerSecret("bbb");
            cb.setOAuthAccessToken("bbb");
            cb.setOAuthAccessTokenSecret("bbb");
     
            TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
            StatusListener listener = new StatusListener() {
            Twitter twitter= new TwitterFactory().getInstance();
            RateLimitStatus rateLimitStatus= twitter.getRateLimitStatus();
            public void onStatus(Status status) {
    //            jTextAreaOutput.setText();
                noTweets=noTweets+1;
                jLabelNoTweets.setText("No. tweets: " + noTweets);
                if(jCheckBoxShowTweets.isSelected()){
                jTextAreaOutput.setText(jTextAreaOutput.getText() +  "Tweetrelated:" +"\n");
                jTextAreaOutput.setText(jTextAreaOutput.getText() +"....................."+"\n")	;
                jTextAreaOutput.setText(jTextAreaOutput.getText() +"Time: " + status.getCreatedAt()+"\n");
                jTextAreaOutput.setText(jTextAreaOutput.getText() +"User: "+ status.getUser().getScreenName()+"\n");
                jTextAreaOutput.setText(jTextAreaOutput.getText() +"Tweet: " + status.getText()+"\n");
    //        	System.out.println("Geolocation: " + status.getGeoLocation());
    //        	System.out.println("Place: " + status.getPlace());
                jTextAreaOutput.setText(jTextAreaOutput.getText() +"\n");
                jTextAreaOutput.setText("Twitter API related:");
                jTextAreaOutput.setText("Hourly limit[RatelimitStatus]: " +  rateLimitStatus.getHourlyLimit() );
                jTextAreaOutput.setText("Remaininghits [RatelimitStatus]: " +  rateLimitStatus.getRemainingHits() );
                jTextAreaOutput.setText("ResetTime [RatelimitStatus]: " +  rateLimitStatus.getResetTime());
                jTextAreaOutput.setText("ResetTimeSeconds [Ratelimitstatus] : " + rateLimitStatus.getResetTimeInSeconds());
                jTextAreaOutput.setText("SecondsUntilReset: [Ratelimitstatus] : " + rateLimitStatus.getSecondsUntilReset());
                }//end if
            }//end onstatus
     
            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
                 if(jCheckBoxShowTweets.isSelected()){
                    jTextAreaOutput.setText(jTextAreaOutput.getText() +"Got a status deletion notice id:" + statusDeletionNotice.getStatusId()+"\n");
                }//end if
            }
     
            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
                 if(jCheckBoxShowTweets.isSelected()){
                jTextAreaOutput.setText(jTextAreaOutput.getText() +"Got track limitation notice:" + numberOfLimitedStatuses+"\n");
                 }//emd if
            }
     
            public void onScrubGeo(long userId, long upToStatusId) {
                 if(jCheckBoxShowTweets.isSelected()){
                jTextAreaOutput.setText(jTextAreaOutput.getText() +"Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId+"\n");
                 }//endif
            }
     
            public void onException(Exception ex) {
                ex.printStackTrace();
            }
        };
     
        twitterStream.addListener(listener);
        twitterStream.sample();
        }
     
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /*
             * Set the Nimbus look and feel
             */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /*
             * If Nimbus (introduced in Java SE 6) is not available, stay with the
             * default look and feel. For details see
             * [url=http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html]How to Set the Look and Feel (The Java™ Tutorials > Creating a GUI With JFC/Swing > Modifying the Look and Feel)[/url]
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(TwitterAppGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(TwitterAppGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(TwitterAppGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(TwitterAppGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
     
            /*
             * Create and display the form
             */
            java.awt.EventQueue.invokeLater(new Runnable() {
     
                public void run() {
                    new TwitterAppGUI().setVisible(true);
                }
            });
     
        }
        // Variables declaration - do not modify
        private javax.swing.JButton jButtonGo;
        private javax.swing.JButton jButtonStop;
        private javax.swing.JCheckBox jCheckBoxShowTweets;
        private javax.swing.JCheckBox jCheckBoxStoreTweets;
        private javax.swing.JLabel jLabelNoTweets;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextArea jTextAreaOutput;
        // End of variables declaration
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,094
    Thanks
    48
    Thanked 2,152 Times in 2,125 Posts

    Default Re: Multiple newbie issues

    getting some compilation error
    Please post the full text of the error message.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    May 2012
    Location
    Sweden
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Multiple newbie issues

    Here is the fulltext that I get when using the clean and build function:


    It doesn't seem to like the RateLimitStatus-bit..

    init:
    deps-clean:
    Updating property file: D:\My documents\Documents\NetBeansProjects\Twitter4jAppI nterface\build\built-clean.properties
    Deleting directory D:\My documents\Documents\NetBeansProjects\Twitter4jAppI nterface\build
    clean:
    init:
    deps-jar:
    Created dir: D:\My documents\Documents\NetBeansProjects\Twitter4jAppI nterface\build
    Updating property file: D:\My documents\Documents\NetBeansProjects\Twitter4jAppI nterface\build\built-jar.properties
    Created dir: D:\My documents\Documents\NetBeansProjects\Twitter4jAppI nterface\build\classes
    Created dir: D:\My documents\Documents\NetBeansProjects\Twitter4jAppI nterface\build\empty
    Created dir: D:\My documents\Documents\NetBeansProjects\Twitter4jAppI nterface\build\generated-sources\ap-source-output
    Compiling 2 source files to D:\My documents\Documents\NetBeansProjects\Twitter4jAppI nterface\build\classes
    D:\My documents\Documents\NetBeansProjects\Twitter4jAppI nterface\src\TwitterAppGUI.java:148: error: unreported exception TwitterException; must be caught or declared to be thrown
    RateLimitStatus rateLimitStatus= twitter.getRateLimitStatus();
    1 error
    D:\My documents\Documents\NetBeansProjects\Twitter4jAppI nterface\nbproject\build-impl.xml:605: The following error occurred while executing this line:
    D:\My documents\Documents\NetBeansProjects\Twitter4jAppI nterface\nbproject\build-impl.xml:246: Compile failed; see the compiler error output for details.
    BUILD FAILED (total time: 1 second)

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,094
    Thanks
    48
    Thanked 2,152 Times in 2,125 Posts

    Default Re: Multiple newbie issues

    unreported exception TwitterException; must be caught or declared to be thrown
    One of the methods you call is defined to throw that exception. Your code must handle that exception. Either put the call to the method in a try/catch block to handle the possible exception or define your method to declare that it throws that same exception to pass its handling to the caller of your method.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    May 2012
    Location
    Sweden
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Multiple newbie issues

    Quote Originally Posted by Norm View Post
    One of the methods you call is defined to throw that exception. Your code must handle that exception. Either put the call to the method in a try/catch block to handle the possible exception or define your method to declare that it throws that same exception to pass its handling to the caller of your method.
    I am not entirely sure on how to do that. I tried the following approach and I realize that it is wrong but I don't know the proper way to address this.


     
            RateLimitStatus rateLimitStatus= twitter.getRateLimitStatus();
            catch (TwitterException e)
             { /* handle exception or just continue? */ };


    This just throws the following error when compiling:

    D:\My documents\Documents\NetBeansProjects\Twitter4jAppI nterface\src\TwitterAppGUI.java:153: error: illegal start of type
    catch (TwitterException e)
    1 error

    Thank you for your patience Norm! Much appreciated!

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,094
    Thanks
    48
    Thanked 2,152 Times in 2,125 Posts

    Default Re: Multiple newbie issues

    where is the try that pairs with the catch?
    Look at the tutorial:
    Catching and Handling Exceptions (The Java™ Tutorials > Essential Classes > Exceptions)
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    May 2012
    Location
    Sweden
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Multiple newbie issues

    Thanks for the link, I will read up on error handling!

    I guess I have to learn how to walk before I run

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,094
    Thanks
    48
    Thanked 2,152 Times in 2,125 Posts

    Default Re: Multiple newbie issues

    Save the link to the tutorials. You can go from there to many other places in the tutorial.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Jar Issues
    By DMinton in forum What's Wrong With My Code?
    Replies: 4
    Last Post: May 6th, 2012, 02:32 PM
  2. Replies: 1
    Last Post: April 26th, 2012, 10:06 AM
  3. Replies: 6
    Last Post: December 9th, 2011, 04:53 PM
  4. [SOLVED] Image issues
    By Toll in forum Java Theory & Questions
    Replies: 7
    Last Post: May 19th, 2011, 09:43 PM
  5. Triangle issues
    By FrEaK in forum What's Wrong With My Code?
    Replies: 0
    Last Post: February 24th, 2010, 07:49 AM

Tags for this Thread