Results 1 to 2 of 2
  1. #1
    Abhi_vk is offline Member
    Join Date
    Jun 2008
    Posts
    1
    Rep Power
    0

    Post How to display scrolling text and image on a JFrame

    Hi All,

    Its my first post here :). I've searched a lot in google for a solution for the problem, mentioned below, but didn't have a luck :confused:. Hope I get an answer here.

    I have this requirement to display some messages on a JFrame (not necessarily a JFrame but any component which can do this job) with
    a scrolling effect where in each message is follwed by an image which scrolls along the text and followed by this there is another text message again followed by an image and so on but the width is fixed to the screen width.

    In short, it should look something similar to the news headlines that scrolls on most of news channels on the bottom of on the TV screens.

    The following is the class where in I've tried to get the above requirement:

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.font.FontRenderContext;
    import java.awt.font.TextLayout;
    import java.awt.geom.Rectangle2D;
    import java.awt.image.BufferedImage;

    import javax.swing.BorderFactory;
    import javax.swing.ImageIcon;
    import javax.swing.JComponent;
    import javax.swing.JDesktopPane;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JRootPane;
    import javax.swing.JScrollPane;
    import javax.swing.JWindow;
    import javax.swing.SwingConstants;
    import javax.swing.WindowConstants;

    import com.seagate.desktop.util.RoundedBorder;


    public class ScrollImageAndText extends JPanel{
    private BufferedImage image;

    private Dimension imageSize;

    private volatile int currOffset;

    private Thread internalThread;

    private volatile boolean noStopRequested;

    static String text = " ";

    static JPanel p = new JPanel(new FlowLayout());

    public ScrollImageAndText(String argText) {
    text = argText;
    currOffset = 0;
    buildImage();
    setMinimumSize(imageSize);
    setPreferredSize(imageSize);
    setMaximumSize(imageSize);
    setSize(imageSize);

    noStopRequested = true;
    Runnable r = new Runnable() {
    public void run() {
    try{
    runWork();
    } catch (Exception x) {
    x.printStackTrace();
    }
    }
    };
    internalThread = new Thread(r, "ScrollText");
    internalThread.start();
    }

    private void buildImage() {
    RenderingHints renderHints = new

    RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    renderHints.put(RenderingHints.KEY_RENDERING,

    RenderingHints.VALUE_RENDER_QUALITY);

    BufferedImage scratchImage = new BufferedImage(1, 1,

    BufferedImage.TYPE_INT_RGB);

    Graphics2D scratchG2 = scratchImage.createGraphics();
    scratchG2.setRenderingHints(renderHints);

    Font font = new Font("ARIAL",Font.PLAIN,10);
    FontRenderContext frc = scratchG2.getFontRenderContext();
    TextLayout tl = new TextLayout(text, font, frc);
    Rectangle2D textBounds = tl.getBounds();
    int textWidth = (int) Math.ceil(textBounds.getWidth());
    int textHeight = (int) Math.ceil(textBounds.getHeight());

    int horizontalPad = 10;
    int verticalPad = 5;

    imageSize = new Dimension(textWidth + horizontalPad, textHeight +

    verticalPad);
    //image = new BufferedImage(imageSize.width, imageSize.height,

    BufferedImage.TYPE_INT_RGB);
    image = new BufferedImage(950, 50, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    g2.setRenderingHints(renderHints);
    //int baselineOffset = (verticalPad / 2) - ((int) textBounds.getY());
    int baselineOffset = 10;
    g2.setColor(Color.BLUE);
    g2.fillRect(0, 0, imageSize.width, imageSize.height);
    g2.setColor(Color.white);
    tl.draw(g2, 0, baselineOffset);
    scratchG2.dispose();
    scratchImage.flush();
    g2.dispose();
    }

    public void paint(Graphics g) {
    // Make sure to clip the edges, regardless of curr size
    g.setClip(0, 0, imageSize.width, imageSize.height);
    int localOffset = currOffset; // in case it changes
    g.drawImage(image, -localOffset, 0, this);
    g.drawImage(image, imageSize.width - localOffset, 0, this);
    // draw outline
    g.setColor(Color.black);
    }

    private void runWork() {

    while (noStopRequested) {
    try {
    Thread.sleep(20); // 20 frames per second

    // adjust the scroll position
    currOffset = (currOffset + 1) % imageSize.width;

    // signal the event thread to call paint()
    repaint();
    }
    catch (InterruptedException x) {
    Thread.currentThread().interrupt();
    }
    }
    }

    public void stopRequest() {
    noStopRequested = false;
    internalThread.interrupt();
    }

    public boolean isAlive() {
    return internalThread.isAlive();
    }

    public static void main(String[] args) {

    final JWindow f = new JWindow();

    p.setFont(new Font("ARIAL",Font.PLAIN,10));
    p.setBackground(Color.blue);
    p.setForeground(Color.white);

    p.add(new ScrollImageAndText("Message 1"));
    p.add(new JLabel(new ImageIcon("images/delimeter.gif")));
    p.add(new ScrollImageAndText("Message 2"));
    p.add(new JLabel(new ImageIcon("images/delimeter.gif")));
    p.add(new ScrollImageAndText("Message 3"));

    f.add(p, BorderLayout.CENTER);
    f.setLocation(30,600);
    f.pack();
    f.setBackground(Color.blue);
    f.setVisible(true);

    }
    }


    Now following are the problems with the above code is:

    1) The image doesn't scroll and its just the text that is scrolling.
    2) The text doesn't scroll thru the entire frame but within in just a fixed location.

    Any solution or a link to the solution would be of great help.

    Thanks In Advance.
    Abhi

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    Java Code:
    import java.awt.*;
    import java.awt.font.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    
    public class DynamicScrolling extends JPanel implements Runnable {
        Font font = new Font("Serif", Font.PLAIN, 22);
        BufferedImage image;
        int pad = 15;
        int x = 0;
    
        public DynamicScrolling(BufferedImage[] images) {
            makeImage(images);
            // Call start method on background thread so
            // event dispatch thread can go on with gui
            // initialization/realization.
            new Thread(new Runnable() {
                public void run() {
                    start();
                }
            }).start();
        }
    
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image, x, 0, this);
            int w = getWidth();
            int iw = image.getWidth();
            if(x + iw < w) {
                g.drawImage(image, x+iw, 0, this);
            }
        }
    
        public void run() {
            while(true) {
                try {
                    Thread.sleep(40);
                } catch(InterruptedException e) {
                    System.out.println("animation interrupted");
                    break;
                }
                x -= 1;
                if(x + image.getWidth() <= 0)
                    x = 0;
                repaint();
            }
        }
    
        private void start() {
            // wait till we're up and running/realized
            do {
                try {
                    Thread.sleep(25);
                } catch(InterruptedException e) {
                    System.out.println("startup interrupted");
                    break;
                }
            } while(!isVisible());
            // start image animation
            Thread thread = new Thread(this);
            thread.setPriority(Thread.NORM_PRIORITY);
            thread.start();
        }
    
        private void makeImage(BufferedImage[] images) {
            String[] strs = { "hello world", "geeks are here" };
            Dimension size = getImageSize(images, strs);
            System.out.printf("size = [%d, %d]%n", size.width, size.height);
            setPreferredSize(size);
            int type = BufferedImage.TYPE_INT_RGB;
            image = new BufferedImage(size.width, size.height, type);
            Graphics2D g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setBackground(getBackground());
            g2.clearRect(0,0,size.width,size.height);
            g2.setPaint(Color.blue);
            g2.setFont(font);
            FontRenderContext frc = g2.getFontRenderContext();
            LineMetrics lm = font.getLineMetrics("0", frc);
            int ascent  = (int)Math.ceil(lm.getAscent());
            int descent = (int)Math.ceil(lm.getDescent());
            int x = 0;
            for(int i = 0; i < strs.length; i++) {
                int y = (size.height + ascent+descent)/2 - descent;
                g2.drawString(strs[i], x, y);
                double w = font.getStringBounds(strs[i], frc).getWidth();
                x += (int)Math.ceil(w) + pad;
                y = 0;
                g2.drawImage(images[i], x, y, this);
                x += images[i].getWidth() + pad;
            }
            System.out.printf("x = %d%n", x);
            g2.dispose();
            //JOptionPane.showMessageDialog(null, new ImageIcon(image), "", -1);
        }
    
        private Dimension getImageSize(BufferedImage[] images, String[] strs) {
            Dimension d = new Dimension();
            FontRenderContext frc = new FontRenderContext(null, true, false);
            for(int i = 0; i < images.length; i++) {
                int h = images[i].getHeight();
                d.width += images[i].getWidth() + pad;
                if(h > d.height)
                    d.height = h;
            }
            LineMetrics lm = font.getLineMetrics("0", frc);
            int height = (int)Math.ceil(lm.getAscent() + lm.getDescent());
            if(height > d.height)
                d.height = height;
            for(int i = 0; i < strs.length; i++) {
                double w = font.getStringBounds(strs[i], frc).getWidth();
                d.width += (int)Math.ceil(w) + pad;
            }
            return d;
        }
    
        public static void main(String[] args) throws IOException {
            String[] ids = { "---h-", "--g--" };
            BufferedImage[] images = new BufferedImage[ids.length];
            for(int i = 0; i < images.length; i++) {
                String path = "images/geek/geek" + ids[i] + ".gif";
                images[i] = ImageIO.read(new File(path));
            }
            DynamicScrolling test = new DynamicScrolling(images);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(test, "Last");
            f.setSize(200,100);
            f.setLocation(200,200);
            f.setVisible(true);
        }
    }
    Images from Using Swing Components Examples, down low.

Similar Threads

  1. Add an image to JFrame
    By Eranga in forum AWT / Swing
    Replies: 4
    Last Post: 02-01-2010, 03:09 PM
  2. can display image in JFrame?
    By xCLARAx in forum AWT / Swing
    Replies: 14
    Last Post: 04-03-2009, 07:02 PM
  3. How to display image ?
    By Birkoff in forum AWT / Swing
    Replies: 7
    Last Post: 06-09-2008, 07:58 AM
  4. Replies: 2
    Last Post: 03-24-2008, 05:29 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •