Sep 24, 2012

Auto-Scrolling Texts with Image Background in Java

ImageIO
This is an example of how to program an animated texts, that automatically scrolls up slowly with an image as its background. In this Java program I used threading, the IO and math APIs to bring everything together. First, the texts are loaded into the stream, pull every line of it and then draw it on to the screen. A top and bottom offset is used to nicely cut the starting as well as the ending points of the texts, as they scrolls in a given time interval.

 
 In this example you need to create a project with two folders, the first folder which is created by default in NetBeans or Eclipse IDEs is where the two project classes goes. The second folder which I named resource is where I put the background image and the bunch of info texts. The texts are saved as Java property file, having the name about .properties in order to be loaded conveniently into the stream.
package codecypherprojects;

import java.awt.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.border.MatteBorder;

/**
 *
 * @author Khamis
 */

public class AnimatedIOText extends JPanel{
    
    private AnimatedIOText me;
    private  AnimationThread thread;
    private FontMetrics fm;
    private final Image image = new ImageIcon(getClass().getResource(
                "/resource/cypher.png")).getImage();
    private String CypherString = "Code Cypher";
    private String copyright = "(c)2012";
    
    private int TOP = 20; 
    private int BOTTOM = 10; 
    private int scrollPos;
    private int maxWidth;
    private final List&ltString> text = new ArrayList&ltString>();   
    private Color textColor = Color.RED;
    
    
 public AnimatedIOText() {            
            fm = getFontMetrics(getFont());
            setBorder(new MatteBorder(1, 1, 1, 1, Color.gray));
            text.add("Auto-Scroll text with image background");
            loadAutoscrollText();
            scrollPos = -250;
            
            //We make sure image is there before using it
            if(image != null){
            setPreferredSize(new Dimension(image.getWidth(me), image
                    .getHeight(me)));
            }else{
                setPreferredSize(getPreferredSize());
            }
            

            thread = new AnimationThread();
            thread.start();
        }
    
 private void loadAutoscrollText() {

            try {
                //Load the text as stream from resource
                BufferedReader textBuffer = new BufferedReader(
                        new InputStreamReader(getClass()
                        .getResourceAsStream("/resource/about.properties")));
                //Wait for the text to get prepared
                while (textBuffer.ready()) {
                    String line = textBuffer.readLine();
                    maxWidth = Math.max(maxWidth, fm.stringWidth(line) + 10);
                    text.add(line);
                }
                textBuffer.close();

            } catch (Exception e) {
                 
                System.out.println("Erro loading text properties: " 
                 + e.getMessage());
       }

   }
   
 //Our paintComponent callback method
 public void paintComponent(Graphics g) {
            
            Color stringColor = Color.orange;

            g.setColor(stringColor);
            
            if(image != null){
               g.drawImage(image, 0, 0, this);
            }
            
            fm = g.getFontMetrics();

            g.drawString(CypherString,
                    (getWidth() - fm.stringWidth(CypherString)) / 2,
                    getHeight() - 30);

            g.drawString(copyright, (getWidth() - fm.stringWidth(copyright)) / 2,
                    getHeight() - 15);
            
            //Bootstrap the graphics painter for more painting
            g = g.create((getWidth() - maxWidth) / 2, TOP, maxWidth,
                    getHeight() - TOP - BOTTOM);

            int f_height = fm.getHeight();
            int first_Line = scrollPos / f_height;
            int first_Line_Offset = f_height - scrollPos % f_height;
            int lines = (getHeight() - TOP - BOTTOM) / f_height;
            int y = first_Line_Offset;

            for (int i = 0; i <= lines; i++) {
                if (i + first_Line >= 0 && i + first_Line < text.size()) {
                    String line = text.get(i + first_Line);
                    g.setColor(textColor);
                    g.drawString(line,(maxWidth - fm.stringWidth(line)) / 2, y);
                }
            y += fm.getHeight();
        }
   }
        
  //Our threaded text scrolling inna class
  class AnimationThread extends Thread {
            private boolean running = true;

            AnimationThread() {
                super("Animated Text Thread");
                setPriority(Thread.MIN_PRIORITY);
            }

        @Override
        public void run() {
                FontMetrics fm = getFontMetrics(getFont());
                int max = (text.size() * fm.getHeight());

                while (running) {
                    scrollPos += 3;

                    if (scrollPos > max)
                        scrollPos = -250;

                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }

                    repaint(getWidth() / 2 - maxWidth, TOP, maxWidth * 2,
                            getHeight() - TOP - BOTTOM);
                }
            }
      }
 }

The main entry class builds the panel as well as the frame, set the size and put everything together for the showing on the screen. 
public class AutoscrollTextMain {
    
    public static void main(String args[]){
    JFrame frame = new JFrame("Animated Autoscroll Text");
    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout());
    
    AnimatedIOText textAnimator = new AnimatedIOText();
    panel.add(textAnimator);
    frame.add(panel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500, 280);
    frame.setLocation(400, 300);
    frame.setVisible(true);
    
   }
}

This is the screenshot of the program












Download the code and the resource files here

Related Posts 

 

How To Load And Display Image From File In Java

How To Make a Copy of File in Java

No comments:

Post a Comment