Solved

Add hyperlinks to my news ticker (Url to correct segment)

Posted on 2004-10-09
5
240 Views
Last Modified: 2012-08-13
Hey,

I am creating a news ticker. It's not the most advanced out there but I felt that I wanted to create on of my own. Everything has gone fine except for now, when I wanted to assign URL's to my scrolling news segments and make them clickable. I don't know what's best, for me to explain my code and ask for what to do or to just paste my code and ask for a solution. Let's try with the latter one.

My JollyTicker below. What I want is to either make each news segment clickable or to be able to add a short string "read more.." and make it clickable. I have no idea how to achvieve that and I have been searching like a madman for a good solution. Any help would be highly appreciated.

What it does is that it gets news from a MS Access database, it gets Headline(Caption), content(Main text) and URL from 3 separate fields, and then it scrolls them up, having each segment pause when it hits the applet top, for about 1,5 secs and then it continues to scroll. I have written plenty of comments so it should be understandable.

Code:

package jollyticker;

import java.applet.*;
import java.awt.*;
import java.sql.*;
import java.lang.*;
import java.util.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;

public class JollyTicker extends Applet implements Runnable, MouseListener, MouseMotionListener  {  // implementing the Runnable interface to be able to use the Thread object and the run() method

        String currentThread = "imageThread"; // declaring and setting a variable to hold which the current thread is
        Thread mainThread = null;  // setting the main Thread
        Thread imageThread = null; // setting the image Thread
        int width = 150;        // declaring and setting the width variable
        int height = 150;       // declaring and setting the height variable
        int x, y;               // declaring the x and y coordinates as integers
        String text;            // declaring a variable to hold our text
        String urltext;            // declaring a variable to hold our urls
        String toptext;         // declaring a variable to hold our headline text
        String fontFamily;      // declaring a variable to hold the font family
        int fontSize;           // declaring a variable to hold the font size
        Color backgroundColor;  // declaring a variable to hold the background color
        Color textColor;        // declaring a variable to hold the text color
        int pause = 2000;       // declaring and setting the pausvariable (milliseconds)
        int speed = 20;         // declaring a variable for the speed and giving it a value (milliseconds)
        String lines[];         // creating an array that will hold the text
        String headlines[];     // creating an array that will hold the headlines  
        int num_lines;          // declaring a variable to hold the number of lines of text
        int num_lines_total;
        int line_height;                   // declaring a variable to hold the text line height
        int flexibleHeight = height;       // declaring and setting a variable to hold the current height of the scrolling text
        Vector newsContent = new Vector(); // creating a vector for holding our news segments (content)
        Vector newsCaption = new Vector(); // creating a vector for holding our news segments (headlines)
        Vector newsURL = new Vector();     // creating a vector for holding our news segments (URL)
        int flexibleVectorHeight;          // declaring a variable to hold the news segment heights
        int newsGap = 40;                  // declaring and setting a variable to hold the gap between news articles
        ArrayList pauseTracker = new ArrayList(); // creating an ArrayList to hold the pause values
        int pauseValues = 30;                     // declaring a variable to hold the news segment pause values
        Image JT_logo = Toolkit.getDefaultToolkit().getImage("jtlogo.gif");
        boolean scrollingPause = false;    // variable that holds values wether the scrolling is paused of not
        Image offlineImage;                // creating an offline image for placing our text on ( for dubblebuffering )
        Graphics offlineCanvas;            // creating an offline canvas for putting our offline image and it's content
       
        public JollyTicker(){   // constructor for our JollyTicker class, leaving it emtpy
        }

        public void init() {  // method for setting all crucial values
        addMouseListener(this);        // adding mouselister to pick up mouse events
          addMouseMotionListener(this);  // adding mousemotionlistener to pick upp mouse movement events
          resize(width, height);         // setting the width and height of the applet
         
          try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Calling the JDBC:ODBC bridge to be able to connect to our MS Access database
            Connection con = DriverManager.getConnection("jdbc:odbc:JollyTickerDatabase");  // creating a connection and reading the database via an ODBC connection made by the installer
            Statement s = con.createStatement(); // creating a java.sql.Statement
            s.execute("SELECT news_caption, news_text FROM JT_content"); // getting the our text from the database
            ResultSet rs = s.getResultSet(); // get any ResultSet that came from our query
            while ( rs.next() ) { // stepping through our data row-by-row
              newsContent.addElement(rs.getString("news_text"));  // adding all rows of textcontent into the newsContent vector
              newsCaption.addElement(rs.getString("news_caption"));  // adding all rows of textcontent into the newsContent vector
              //newsURL.addElement(rs.getString("news_URL"));  // adding all rows of textcontent into the newsContent vector
            }
            s.close(); // closing the Statement
            con.close(); // closing the Connection
          }
          catch (Exception e) {
            System.out.println("Error: " + e);
          }
        }

        public void paint(Graphics g){             // method for setting the textcolor and writing our text
          if (offlineImage != null) {              // checks if there is an instance of our offlineImage with content
          g.drawImage(offlineImage, 0, 0, null); // draws our image with it's content
          }
        }


        public void update(Graphics g) {
       
          if (offlineCanvas == null){ // first time running, creating our offline graphics canvas
            offlineImage = createImage(width, height);     // creating an offline image
            offlineCanvas = offlineImage.getGraphics();    // adding our offline image to our offline canvas
            fontFamily = "Trebuchet MS";                   // setting the font family
            fontSize = 10;                                 // setting the font size
            textColor = Color.BLACK;                       // assigning a color to the fontColor variable
            backgroundColor = Color.WHITE;                 // assigning a color to the backgroundColor variable
            offlineCanvas.setColor(backgroundColor);       // setting the background color
          }
          this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));  // changing the cursor when mouse is over the applet
          offlineCanvas.setColor(backgroundColor);      // setting the background color
          offlineCanvas.fillRect(0, 0, width, height);  // filling the screen with our canvas
          paintFrame(offlineCanvas);                    // drawing the offline frame canvas on to the screen
          g.drawImage(offlineImage, 0, 0, null);        // drawing our offline image to the screen
      }
     
      public void paintFrame(Graphics g) { // this lovely thing will paint it all
       
        if(currentThread=="imageThread"){ // checks to see if our imageThread is running
          JTMediaTracker();                           // Calls our mediatracker to draw the image faster
          g.drawImage(JT_logo, 0, 0, 150, 150, null); // draws the logo to the screen
        } else if(currentThread=="mainThread"){ // checks to see if our mainThread is running      

          g.setColor(textColor);      // setting the text color
          flexibleVectorHeight = 0;   // giving the flexibleVectorHeight an initial value

          for(int k=0; k < newsContent.size(); k++){  // looping through the vector where we added our news content from the database
            //urltext = newsURL.elementAt(k).toString(); // assigning the values from the database->vector to my text-variable            
            toptext = newsCaption.elementAt(k).toString(); // assigning the values from the database->vector to my text-variable            
            text = newsContent.elementAt(k).toString(); // assigning the values from the database->vector to my text-variable
            String lines[] = text.split("\\u005cn");    // \u005c is the hex code for the backslash (92 decimal) Splitting up the text and entering the parts into an array
            if(pauseTracker.size()<newsContent.size()){ // everything in this if condition only needs to be run as many times as there are entrys in the newsContent vector
              pauseTracker.add(new Integer(pauseValues)); // adds a value to the pauseTracker that will be used later when we want to pause the news scrolling
             
              Font f = getFont();                 // getting our font context
              FontMetrics fm = getFontMetrics(f); // getting out FontMetrics
              line_height = fm.getHeight();       // setting the line_height variable to the our font lineheight
              num_lines = lines.length;           // setting the number of rows to the num_lines variable
              num_lines_total += num_lines;       // setting number of rows total to be able to check when all news has been displayed
            }
            g.setFont(new Font(fontFamily, Font.BOLD + Font.PLAIN, fontSize));             // setting the font for the headline
            g.drawString(toptext, x, flexibleHeight + flexibleVectorHeight - line_height); // drawing one line from the lines-array              
            int i;
            for (i = 0; i < lines.length; i++) { // creating a loop for drawing all of our lines
              g.setFont(new Font(fontFamily, Font.PLAIN + Font.PLAIN, fontSize));                   // setting the font for the headline
              g.drawString(lines[i], x, flexibleHeight + (i * line_height) + flexibleVectorHeight); // drawing one line from the lines-array  

            }
            flexibleVectorHeight += i * line_height + newsGap;  // calculating where to enter the next news segment (below)
            pauseValues -= (num_lines * line_height + newsGap); // calculating where each news segment should pause scrolling
          }
           }
      }
     
        public void start(){

          if(currentThread=="mainThread"){
            if (mainThread == null) { // checks if mainThread is an instance of Thread
              mainThread = new Thread(this); // creating an instance of Thread
            }
            mainThread.start(); // starting mainThread
          } else if(currentThread=="imageThread"){
            if (imageThread == null) { // checks if mainThread is an instance of Thread
              imageThread = new Thread(this); // creating an instance of Thread
            }
            imageThread.start(); // starting mainThread
          }
 
             
        }
       
        public void stop() {  // when the applet is no longer visible the Thread is set to null
            mainThread = null;
            imageThread = null;
            offlineImage = null;
            offlineCanvas = null;
        }

        public void run() { // method that places our string, writes it to the front and moves it upwards
         
          Thread.currentThread().setPriority(Thread.MIN_PRIORITY); // lowering the priority of the thread for less interfearence

          while (Thread.currentThread() == mainThread) {  // creating a unlimited loop
            x = 5;     // setting the distance of the text from the left "wall"
            repaint(); // calls the paint-mehod
     
            flexibleHeight--; // decreasing the placement of our graphical object by 1 in the y-axle
            if ( (flexibleHeight + (num_lines_total * line_height)) < 0) { // checking so that the the text haven't reached the top of the applet
              try {
                Thread.sleep(pause); // pausing the news segment (halting the Thread for a certain amount of time)
              }
              catch (InterruptedException e) {
              }
              flexibleHeight = height + line_height; // resetting the vertical placement
            }

            for (int i = 0; i < pauseTracker.size(); i++) { // looping through the pauseTracker giving the "pauser" it's values
              Object pauseTrackerObj = pauseTracker.get(i); // getting the values from the pauseTracker as objects
              int pauseTrackerInt = Integer.parseInt(pauseTrackerObj.toString()); // creating a variable and converting the pauseTracker objects into integers
               if (flexibleHeight == pauseTrackerInt) { // checks if the news segments has reached the top of the applet
              try {
                Thread.sleep(1500); // pausing the news segment (halting the Thread for a certain amount of time)
              }
              catch (InterruptedException e) {
              }
              }
            }
              try {
                Thread.sleep(speed); // setting the time between repaints, which will be the speed of our scrolling text
              }
              catch (InterruptedException e) {
              }
          }
         
          while (Thread.currentThread() == imageThread) {  // creating a unlimited loop
           
            repaint();  // calling the paint-method
            try {
              Thread.sleep(1500); // setting the time between repaints, which will be the speed of our scrolling text
            }
            catch (InterruptedException e) {
            }
            stop();                       // stopping the thread
            currentThread = "mainThread"; // setting the new thread
            start();                      // starting the new thread
          }
      }
     
      // ************************************************************************** //
      //                           MEDIATRACKER FUNCTION                            //
      //  ------------------------------------------------------------------------- //
      //  When the image is drawn in the imageThread this MediaTracker makes sure   //
      //  the image is loaded and will be displayed imediately on the loaded and    //
      //  will be displayed imediately on the screen.                               //
      // ************************************************************************** //
     
      public void JTMediaTracker(){
        MediaTracker t = new MediaTracker(this);  // calling the MediaTracker method
        t.addImage(JT_logo, 0);                   // adding our image to the tracker
        try {
          t.waitForAll(); // waiting for images to load before init.
        }catch(Exception e) {}
      }
     
      // ************************************************************************** //
      //               MOUSELISTENER AND MOUSEMOTION LISTENER EVENTS                //
      //  ------------------------------------------------------------------------- //
      //  When the user interacts with the applet using the mouse, following events //
      //  will initialize and act as follows.                                       //
      // ************************************************************************** //
     
      public void mouseReleased(MouseEvent e){
          scrollingPause = false; start();  // when the mouse is released the scrolling starts
      }
      public void mousePressed(MouseEvent e){
          scrollingPause = true; stop();    // when the mouse is pressed the scrolling pauses
      }
      public void mouseExited(MouseEvent e){
      }
      public void mouseEntered(MouseEvent e){
      }
      public void mouseClicked(MouseEvent e){
      }
      public void mouseDragged(MouseEvent e){
      }
      public void mouseMoved(MouseEvent e){
      }
}
0
Comment
Question by:mindweaver
  • 3
  • 2
5 Comments
 

Author Comment

by:mindweaver
Comment Utility
An alternative is to read out the URLs from the database and when a news segment hits the top of the applet it loads the appropriate URL and makes the whole applet clickabe with that URL as destination. and maybe notifying the user in the statusbar of the browser  "click on news ticker to read more..."

Only thing left is to create it, and I can't figure out how. Points will be assigned to whoever solve my problem  with solution 1, 2 or 3.

0
 

Author Comment

by:mindweaver
Comment Utility
Me again, and if anyone can figure out why I can't view it in a browser please let me know. Sometimes it doesn't get inited, and sometimes it gets started but stays blank, nothing happens.
0
 
LVL 13

Accepted Solution

by:
Webstorm earned 500 total points
Comment Utility
Hi mindweaver,

To show an url when the user click, just add this in your code :

      URL url=new URL("http://www.server.domain/abspath");

      public void mouseReleased(MouseEvent e){
          scrollingPause = false; start();  // when the mouse is released the scrolling starts
          getAppletContext().showDocument(url);
      }

0
 
LVL 13

Expert Comment

by:Webstorm
Comment Utility
Or you can do it in the mouseClick method instead :

      public void mouseClicked(MouseEvent e){
          getAppletContext().showDocument(url);
      }
0
 

Author Comment

by:mindweaver
Comment Utility
Yes I came to the same conclusion as you Webstorm, thanks.. And I have got my Applet working in a browser somewhat. I had to make a phony certificate and sign my applet with jarsigner.

Now I't the problem of making my news segments clickable left!
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now