5 Replies - 1849 Views - Last Post: 12 May 2011 - 02:59 PM Rate Topic: -----

#1 jja123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 12-May 11

Java Applet Slideshow Problem

Posted 12 May 2011 - 08:17 AM

I'm trying to make a slideshow applet and my images will not show up when I try to run it in a web browser. Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;

public class GridDemo extends JApplet
{
  int slideNumber = 0;     // The slide currently on the screen
  int numSlides = 0;       // Number of slides
  ArrayList slides = new ArrayList();
  Timer timer;
  static int TICKS_PER_SEC = 8;
  int ticksToGo;
  int delaySecs;
  float busyVal = 0.0f;
  boolean autoAdvance;
  SlidePanel slidePanel;
  JPanel statusPanel;       // The entire status line at the bottom
  JLabel captionPanel;      // The slide caption in the middle of the status

  class Slide
  {
    private Image image;
    private String name;
    private String caption;
    private MediaTracker mt;
    private JApplet comp;

    //public Slide(String name, String caption, JApplet comp)
    //{
    //  this.name = name;
    //  this.caption = caption;
    //  this.image = null;
    //  this.comp = comp;
    //  this.mt = new MediaTracker(comp);
    //}

    // Start loading the image associated with the slide
    public void startLoading()
    {
      if (name.length() > 0 && image == null)
      {
        image = comp.getImage(getDocumentBase(), name);
        if (image == null)
        {
          /* Some browsers tell us immediately if the file was not found */
          unload();
          slidePanel.setMessage("Slide missing!");
        }
        else
        {
          mt.addImage(image, 0);
          mt.checkID(0, true); // Start loading this image right away
        }
      }
    }
    
    public boolean isLoaded()
    {
      return mt.checkID(0);
    }
    
    public void unload()
    {
      if (image != null)
      {
        mt.removeImage(image);
        image = null; // Delete the image
      }
    }

    // Display the slide, waiting if necessary for it to fully load
    // first. If it fails to load, display a message.
    public void display()
    {
      // Make sure image is fully loaded, waiting if necessary.
      try { mt.waitForID(0); }
      catch (InterruptedException ex) { }

      if (mt.isErrorID(0))
      {
        unload();
        slidePanel.setMessage("Slide missing!");
      }

      // Display the slide
      slidePanel.setImage(image);

      // Update the caption at the bottom of the screen
      captionPanel.setText(caption);
    }
  }
  
  public String[][] getParameterInfo()
  {
    String[][] info = {
      // Parameter Name     Kind of Value   Description
        {"autoadvance",     "yes/no",       "Auto-advance the slide show"},
        {"time",            "int",          "Time between slides in seconds"},
        {"dir",             "string",       "Subdirectory containing the slides"},
        {"1",               "string",       "Slide 1 filename,Caption"},
        {"2",               "string",       "Slide 2 filename,Caption"},
        {"3",               "string",       "Slide 3 filename,Caption"},
        {"...",             "...",          "... etc"},
    };
    return info;
  }
  
  public String getAppletInfo()
  {
    return "JustSlides";
  }

  public void init()
  {
    String str;

    // Set seconds between slides
    str = getParameter("time");
    delaySecs = 10; 
    try
    {
      if (str != null)
        delaySecs = Integer.parseInt(str);
    }
    catch (Exception e) { }
    
    // Start with autoadvance on?
    str = getParameter("autoadvance");
    autoAdvance = false;
    if (str != null)
    {
      if (str.equalsIgnoreCase("yes"))
        autoAdvance = true;
    }
    
    // Subdirectory for slides
    String dir = getParameter("dir");
    if (dir == null)
      dir = "";

    // Slide 0 is always the Loading... slide. It has no associated image
    //slides.add(new Slide("", "Just Slides (c) 2003 Ian Goldby", this));

    // Read in list of slides
    numSlides = 1;
    String file;
    //String caption;
    int comma;
    while ((str = getParameter(String.valueOf(numSlides))) != null)
    {
      comma = str.indexOf(',');
      if (comma == -1)
        comma = str.length();
      file = str.substring(0, comma);
      if (comma < (str.length()-1))
       caption = str.substring(comma+1);
      else
        caption = "";
     s slides.add(new Slide(dir + "/" + file, caption, this));
      numSlides++;
    }

    // Create the slide area
    slidePanel = new SlidePanel();
    slidePanel.setBackground(Color.black);
    slidePanel.setForeground(Color.yellow);
    slidePanel.setOpaque(true);

    // Create the status panel
    statusPanel = new JPanel();
    statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.X_AXIS));
    statusPanel.setBorder(BorderFactory.createEmptyBorder());
    statusPanel.setBackground(Color.black);
    statusPanel.setOpaque(true);

    // (The ContentPane's default layout is BorderLayout.)
    getContentPane().add(slidePanel, BorderLayout.CENTER);
    getContentPane().add(statusPanel, BorderLayout.SOUTH);

    // Create the slide caption next
    captionPanel = new JLabel(" ", JLabel.CENTER);
    captionPanel.setBackground(Color.black);
    captionPanel.setForeground(Color.white);
    captionPanel.setOpaque(true);
    captionPanel.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 0));
    // If there is not enough width, allow caption to be truncated
    captionPanel.setMinimumSize(new Dimension(0, captionPanel.getMinimumSize().height*5/4));
    // Buttons size themselves to the minimum size of the status panel
    statusPanel.setMinimumSize(new Dimension(0, captionPanel.getMinimumSize().height));

    // Add the caption, and transport buttons to the status bar
    statusPanel.add(captionPanel);
    // Add the stretchy glue to take up the free space
    statusPanel.add(Box.createHorizontalGlue());
    ActionListener buttonListener = new ButtonListener();
    Dimension d = new Dimension(captionPanel.getMinimumSize().height, captionPanel.getMinimumSize().height);

    // Start loading the first slide
    firstSlide();
  }

  public void start()
  {
    if (numSlides > 1)
      startTimer();
  }

  // Can be invoked from any thread.
  public synchronized void startTimer()
  {
    // Start animating!
    if (!timer.isRunning())
    {
      timer.setInitialDelay(0);
      timer.start();
    }
  }

  // Goes to the next slide.
  private void nextSlide()
  {
    if (slideNumber < numSlides-1)
    {
      // Unload the previous slide (if any)
      if (slideNumber > 1)
        ((Slide)slides.get(slideNumber-1)).unload();
      // Display next slide
      slideNumber++;
      ((Slide)slides.get(slideNumber)).display();
      // Start loading the next slide after this (if any)
      if (slideNumber < numSlides-1)
      {
        ((Slide)slides.get(slideNumber+1)).startLoading();
      // If the slide is not already loaded, start the timer to enable
      // the animation effect.
        if (!((Slide)slides.get(slideNumber+1)).isLoaded())
          startTimer();
      }
    }
  }

  // Goes to the previous slide.
  private void previousSlide()
  {
    if (slideNumber > 1) // 1 is the first real slide.
    {
       // Unload the next slide (if any)
       if (slideNumber < numSlides-1)
         ((Slide)slides.get(slideNumber+1)).unload();
       // Display previous slide
       slideNumber--;
       ((Slide)slides.get(slideNumber)).display();
       // Start loading the previous slide before this (if any)
       if (slideNumber > 1)
         ((Slide)slides.get(slideNumber-1)).startLoading();
       // If the slide is not already loaded, start the timer to enable
       // the animation effect.
      if (!((Slide)slides.get(slideNumber-1)).isLoaded())
        startTimer();
    }
  }
  
  // Goes to the first slide.
  private void firstSlide()
  {
    // Unload the old next cached slide (if any)
    if (slideNumber > 2 && slideNumber < numSlides-1)
      ((Slide)slides.get(slideNumber+1)).unload();
    // Unload the old current slide (if any)
    if (slideNumber > 3)
      ((Slide)slides.get(slideNumber)).unload();
    // Unload the old previous cached slide (if any)
    if (slideNumber > 4)
      ((Slide)slides.get(slideNumber-1)).unload();

    slideNumber = 0;
    if (numSlides > 1)
    {
      slidePanel.setMessage("Loading...");
      ((Slide)slides.get(0)).display();
      ((Slide)slides.get(1)).startLoading();
    }
    else
      slidePanel.setMessage("No slides");
    ticksToGo = 0;
    startTimer();
  }

  // The action listener that responds to button presses
  class ButtonListener implements ActionListener
  {
    public void actionPerformed(ActionEvent e)
    {
      String actionCommand = e.getActionCommand();   
    }
  }
}

class SlidePanel extends JPanel
{
  Image image;
  String message;

  public SlidePanel()
  {
    image = null;
    message = "Loading...";
  }

  public void setImage(Image image)
  {
    this.image = image;
    repaint();
  }

  public void setMessage(String message)
  {
    this.message = message;
    repaint();
  }
  
  public void paintComponent(Graphics g)
  {
    // Draw the background
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g; // So we can antialias text

    // Get the available drawing area
    int cw, ch, cx, cy;
    Insets insets = getInsets();
    cx = insets.left;
    cy = insets.top;
    cw = getWidth() - cx - insets.right;
    ch = getHeight() - cy - insets.bottom;

    if (image == null)
    {
      int x, y;
      RenderingHints hints =
        new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                           RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
      g2.addRenderingHints(hints);
      Font font = getFont();
      font = font.deriveFont(font.BOLD, 24.0f);
      g2.setFont(font);
      g2.setColor(Color.yellow);
      FontMetrics metrics = g2.getFontMetrics();
      int w = metrics.stringWidth(message);
      int h = metrics.getHeight();
      g2.drawString(message, (cw-w)/2, (ch-h)/2);
    }
    else
    {
      double scale;
      int width, height, x, y;
      
      RenderingHints hints =
        new RenderingHints(RenderingHints.KEY_INTERPOLATION,
                           RenderingHints.VALUE_INTERPOLATION_BICUBIC);
      g2.addRenderingHints(hints);

      // Calculate optimum image size
      scale = (double)cw/(double)image.getWidth(this);
      if ((double)image.getHeight(this) * scale > (double)ch)
        scale = (double)ch/(double)image.getHeight(this);
      width = (int)(scale * image.getWidth(this));
      height = (int)(scale * image.getHeight(this));
      x = cx + (cw - width)/2;
      y = cy + (ch - height)/2;
      // Draw the image
      g2.drawImage(image, x, y, x + width, y + height,
                   0, 0, image.getWidth(this), image.getHeight(this), this);
    }
  }
}




Here is the my HTML code:
<html>
<head>
<title>My Slide Show</title>
</head>
<body>
<applet code="GridDemo.class" width="500" height="500">
<param name="autoadvance" value="yes">
<param name="time" value="10">
<param name="dir" value="slides">
<param name="1" value="summer1.jpg">
<param name="2" value="summer2.jpg">
<param name="3" value="summer3.jpg">
<param name="4" value="summer4.jpg">
<param name="5" value="summer5.jpg">
<param name="6" value="summer6.jpg">
<param name="7" value="summer7.jpg">
<param name="8" value="summer8.jpg">
<param name="9" value="summer9.jpg">
<param name="10" value="SummerSun.gif">

</applet>
</body>
</html>



When I try to bring it up in the web browser, nothing appears. I do have all my images named correctly.

Is This A Good Question/Topic? 0
  • +

Replies To: Java Applet Slideshow Problem

#2 Luckless  Icon User is offline

  • </luck>
  • member icon

Reputation: 293
  • View blog
  • Posts: 1,146
  • Joined: 31-August 09

Re: Java Applet Slideshow Problem

Posted 12 May 2011 - 08:30 AM

I think it's because your Slide class needs to extend JApplet instead of using the global variable JApplet comp. You have an init() and start() method in Slide that will never be called because Slide isn't a JApplet. You'll have to alter your code to deal with this. Basically, wherever you are using comp, adapt it to add it to this(instance of slide)

my bad, missed a few parenthesis. let me go through it again.

This post has been edited by Luckless: 12 May 2011 - 08:31 AM

Was This Post Helpful? 0
  • +
  • -

#3 Luckless  Icon User is offline

  • </luck>
  • member icon

Reputation: 293
  • View blog
  • Posts: 1,146
  • Joined: 31-August 09

Re: Java Applet Slideshow Problem

Posted 12 May 2011 - 08:43 AM

ok, here we go again :bigsmile: If I were the problem, I would be in lines 178 and 179. You don't want to add the panels to the content pane until you are done setting their parameters. My next step would be to move those two lines down to line 199, towards the end of your init() method. You shouldn't add content until you are done altering it's settings. Give it a shot and we'll go from there. Sorry about the earlier post!
Was This Post Helpful? 0
  • +
  • -

#4 jja123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 12-May 11

Re: Java Applet Slideshow Problem

Posted 12 May 2011 - 09:37 AM

Ok, when I do that and try to run it in the browser it shows a box, but says there were errors. When I click on it to view the errors, here is what I get:

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.RangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at GridDemo.firstSlide(GridDemo.java:281)
at GridDemo.init(GridDemo.java:200)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Exception: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
java.lang.NullPointerException
at GridDemo.startTimer(GridDemo.java:213)
at GridDemo.start(GridDemo.java:206)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Exception: java.lang.NullPointerException
Garbage collect ... completed.
Memory: 16,000K Free: 11,458K (71%) ... completed.
Garbage collect ... completed.
Memory: 16,000K Free: 11,495K (71%) ... completed.
Garbage collect ... completed.
Memory: 16,000K Free: 12,022K (75%) ... completed.
Garbage collect ... completed.
Memory: 16,000K Free: 11,999K (74%) ... completed.
load: class SlideShow.class not found.
java.lang.ClassNotFoundException: SlideShow.class
at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Unknown Source)
at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.io.FileNotFoundException: C:\Users\Josh\Desktop\slideshow1\SlideShow\class.class (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at sun.net.www.protocol.file.FileURLConnection.connect(Unknown Source)
at sun.net.www.protocol.file.FileURLConnection.getInputStream(Unknown Source)
at sun.plugin2.applet.Applet2ClassLoader.getBytes(Unknown Source)
at sun.plugin2.applet.Applet2ClassLoader.access$000(Unknown Source)
at sun.plugin2.applet.Applet2ClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
... 9 more
Exception: java.lang.ClassNotFoundException: SlideShow.class
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.RangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at GridDemo.firstSlide(GridDemo.java:281)
at GridDemo.init(GridDemo.java:200)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Exception: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
java.lang.NullPointerException
at GridDemo.startTimer(GridDemo.java:213)
at GridDemo.start(GridDemo.java:206)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Exception: java.lang.NullPointerException
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.RangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at GridDemo.firstSlide(GridDemo.java:281)
at GridDemo.init(GridDemo.java:200)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Exception: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
java.lang.NullPointerException
at GridDemo.startTimer(GridDemo.java:213)
at GridDemo.start(GridDemo.java:206)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Exception: java.lang.NullPointerException

Please understand that I am a complete beginner at Java, but from what I am looking at I don't understand why I am getting and out of bounds exception.
Was This Post Helpful? 0
  • +
  • -

#5 Luckless  Icon User is offline

  • </luck>
  • member icon

Reputation: 293
  • View blog
  • Posts: 1,146
  • Joined: 31-August 09

Re: Java Applet Slideshow Problem

Posted 12 May 2011 - 12:58 PM

It has to do with your slides array in your firstSlide() method. It looks like line 160 is where you are adding new slides to it. I don't see in your code where you have that Array(List?) initialized, but you're going to want to use an ArrayList<Slide> slides. This does a few things.

1.) you won't have to cast to (Slide) in your firstSlide() method (This is where your error is coming from, btw. It's saying that you are trying to grab an index in slides that is non-existent. My bet would be that all that unloading that you have going on is messing up your indexes. Maybe try to just set the currentIndex to 0 and let the start() method take care of the rest)

2.) It's much cleaner than using regular arrays because they dynamically change size.

If you're a beginner in Java and came up with the code on your own, you're doing just fine. You'll get it to work--keep at it. Debugging is half of the game.
Was This Post Helpful? 0
  • +
  • -

#6 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2775
  • View blog
  • Posts: 11,736
  • Joined: 20-September 08

Re: Java Applet Slideshow Problem

Posted 12 May 2011 - 02:59 PM

I played about a bit. This should get you a bit closer:


import java.awt.*;
import java.awt.event.*;

import java.util.ArrayList;

import javax.swing.*;


public class GridDemo extends JApplet implements ActionListener {
    static int TICKS_PER_SEC = 8;
    int slideNumber = 0; // The slide currently on the screen
    int numSlides = 0; // Number of slides
    ArrayList slides = new ArrayList();
    Timer timer;
    int ticksToGo;
    int delaySecs;
    float busyVal = 0.0f;
    boolean autoAdvance;
    SlidePanel slidePanel;
    JPanel statusPanel; // The entire status line at the bottom
    JLabel captionPanel; // The slide caption in the middle of the status

    public String[][] getParameterInfo() {
        String[][] info = {
                // Parameter Name     Kind of Value   Description
                {"autoadvance", "yes/no", "Auto-advance the slide show" },
                

                { "time", "int", "Time between slides in seconds" },
                

                { "dir", "string", "Subdirectory containing the slides" },
                

                { "1", "string", "Slide 1 filename,Caption" },
                

                { "2", "string", "Slide 2 filename,Caption" },
                

                { "3", "string", "Slide 3 filename,Caption" },
                

                { "...", "...", "... etc" },
            };

        return info;
    }

    public String getAppletInfo() {
        return "JustSlides";
    }

    public void init() {
        String str;

        // Set seconds between slides
        str = getParameter("time");

        delaySecs = 10;

        try {
            if (str != null) {
                delaySecs = Integer.parseInt(str);
            }
        } catch (Exception e) {
        }

        // Start with autoadvance on?
        str = getParameter("autoadvance");

        autoAdvance = false;

        if (str != null) {
            if (str.equalsIgnoreCase("yes")) {
                autoAdvance = true;
            }
        }

        // Subdirectory for slides
        String dir = getParameter("dir");

        if (dir == null) {
            dir = "";
        }

        // Slide 0 is always the Loading... slide. It has no associated image
        slides.add(new Slide("", "Just Slides (c) 2003 Ian Goldby", this));

        // Read in list of slides
        numSlides = 1;

        String file;

        //String caption;
        int comma;
        String caption = "";

        while ((str = getParameter(String.valueOf(numSlides))) != null) {
            comma = str.indexOf(',');

            if (comma == -1) {
                comma = str.length();
            }

            file = str.substring(0, comma);

            if (comma < (str.length() - 1)) {
                caption = str.substring(comma + 1);
            } else {
                caption = "";
            }

            slides.add(new Slide(dir + "/" + file, caption, this));

            numSlides++;
        }

        // Create the slide area
        slidePanel = new SlidePanel();

        slidePanel.setBackground(Color.black);

        slidePanel.setForeground(Color.yellow);

        slidePanel.setOpaque(true);

        // Create the status panel
        statusPanel = new JPanel();

        statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.X_AXIS));

        statusPanel.setBorder(BorderFactory.createEmptyBorder());

        statusPanel.setBackground(Color.black);

        statusPanel.setOpaque(true);

        // (The ContentPane's default layout is BorderLayout.)
        getContentPane().add(slidePanel, BorderLayout.CENTER);

        getContentPane().add(statusPanel, BorderLayout.SOUTH);

        // Create the slide caption next
        captionPanel = new JLabel(" ", JLabel.CENTER);

        captionPanel.setBackground(Color.black);

        captionPanel.setForeground(Color.white);

        captionPanel.setOpaque(true);

        captionPanel.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 0));

        // If there is not enough width, allow caption to be truncated
        captionPanel.setMinimumSize(new Dimension(0,
                (captionPanel.getMinimumSize().height * 5) / 4));

        // Buttons size themselves to the minimum size of the status panel
        statusPanel.setMinimumSize(new Dimension(0,
                captionPanel.getMinimumSize().height));

        // Add the caption, and transport buttons to the status bar
        statusPanel.add(captionPanel);

        // Add the stretchy glue to take up the free space
        statusPanel.add(Box.createHorizontalGlue());

        ActionListener buttonListener = new ButtonListener();

        Dimension d = new Dimension(captionPanel.getMinimumSize().height,
                captionPanel.getMinimumSize().height);

        // Start loading the first slide
        firstSlide();
    }

    public void start() {
        if (numSlides > 1) {
            startTimer();
        }
    }

    // Can be invoked from any thread.
    public synchronized void startTimer() {
        // Start animating!
        timer = new Timer(2000, this);
        timer.start();
    }

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

    // Goes to the next slide.
    private void nextSlide() {
        System.out.println("Asking for next...");

        if (slideNumber < (numSlides - 1)) {
            // Unload the previous slide (if any)
            if (slideNumber > 1) {
                ((Slide) slides.get(slideNumber - 1)).unload();
            }

            // Display next slide
            slideNumber++;

            ((Slide) slides.get(slideNumber)).display();

            // Start loading the next slide after this (if any)
            if (slideNumber < (numSlides - 1)) {
                //DEBUG
                System.out.printf("slideNumber=%d,numSlides=%d\n", slideNumber,
                    numSlides);
                ((Slide) slides.get(slideNumber + 1)).startLoading();

                // If the slide is not already loaded, start the timer to enable

                // the animation effect.
                if (!((Slide) slides.get(slideNumber + 1)).isLoaded()) {
                    startTimer();
                }
            }
        }
    }

    // Goes to the previous slide.
    private void previousSlide() {
        if (slideNumber > 1) // 1 is the first real slide.
         {
            // Unload the next slide (if any)
            if (slideNumber < (numSlides - 1)) {
                ((Slide) slides.get(slideNumber + 1)).unload();
            }

            // Display previous slide
            slideNumber--;

            ((Slide) slides.get(slideNumber)).display();

            // Start loading the previous slide before this (if any)
            if (slideNumber > 1) {
                ((Slide) slides.get(slideNumber - 1)).startLoading();
            }

            // If the slide is not already loaded, start the timer to enable

            // the animation effect.
            if (!((Slide) slides.get(slideNumber - 1)).isLoaded()) {
                startTimer();
            }
        }
    }

    // Goes to the first slide.
    private void firstSlide() {
        // Unload the old next cached slide (if any)
        if ((slideNumber > 2) && (slideNumber < (numSlides - 1))) {
            ((Slide) slides.get(slideNumber + 1)).unload();
        }

        // Unload the old current slide (if any)
        if (slideNumber > 3) {
            ((Slide) slides.get(slideNumber)).unload();
        }

        // Unload the old previous cached slide (if any)
        if (slideNumber > 4) {
            ((Slide) slides.get(slideNumber - 1)).unload();
        }

        slideNumber = 0;

        if (numSlides > 1) {
            slidePanel.setMessage("Loading...");

            ((Slide) slides.get(0)).display();

            ((Slide) slides.get(1)).startLoading();
        } else {
            slidePanel.setMessage("No slides");
        }

        ticksToGo = 0;

        startTimer();
    }

    class Slide {
        private Image image;
        private String name;
        private String caption;
        private MediaTracker mt;
        private JApplet comp;

        public Slide(String name, String caption, JApplet comp) {
            this.name = name;

            this.caption = caption;

            this.image = null;

            this.comp = comp;

            this.mt = new MediaTracker(comp);
        }

        // Start loading the image associated with the slide
        public void startLoading() {
            if ((name.length() > 0) && (image == null)) {
                image = comp.getImage(getDocumentBase(), name);

                if (image == null) {
                    /* Some browsers tell us immediately if the file was not found */
                    unload();

                    slidePanel.setMessage("Slide missing!");
                } else {
                    mt.addImage(image, 0);

                    mt.checkID(0, true); // Start loading this image right away
                }
            }
        }

        public boolean isLoaded() {
            return mt.checkID(0);
        }

        public void unload() {
            if (image != null) {
                mt.removeImage(image);

                image = null; // Delete the image
            }
        }

        // Display the slide, waiting if necessary for it to fully load

        // first. If it fails to load, display a message.
        public void display() {
            // Make sure image is fully loaded, waiting if necessary.
            try {
                mt.waitForID(0);
            } catch (InterruptedException ex) {
            }

            if (mt.isErrorID(0)) {
                unload();

                slidePanel.setMessage("Slide missing!");
            }

            // Display the slide
            slidePanel.setImage(image);

            // Update the caption at the bottom of the screen
            captionPanel.setText(caption);
        }
    }

    // The action listener that responds to button presses
    class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String actionCommand = e.getActionCommand();
        }
    }
}


class SlidePanel extends JPanel {
    Image image;
    String message;

    public SlidePanel() {
        image = null;

        message = "Loading...";
    }

    public void setImage(Image image) {
        this.image = image;

        repaint();
    }

    public void setMessage(String message) {
        this.message = message;

        repaint();
    }

    public void paintComponent(Graphics g) {
        // Draw the background
        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D) g; // So we can antialias text

        // Get the available drawing area
        int cw;

        // Get the available drawing area
        int ch;

        // Get the available drawing area
        int cx;

        // Get the available drawing area
        int cy;

        Insets insets = getInsets();

        cx = insets.left;

        cy = insets.top;

        cw = getWidth() - cx - insets.right;

        ch = getHeight() - cy - insets.bottom;

        if (image == null) {
            int x;
            int y;

            RenderingHints hints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

            g2.addRenderingHints(hints);

            Font font = getFont();

            font = font.deriveFont(font.BOLD, 24.0f);

            g2.setFont(font);

            g2.setColor(Color.yellow);

            FontMetrics metrics = g2.getFontMetrics();

            int w = metrics.stringWidth(message);

            int h = metrics.getHeight();

            g2.drawString(message, (cw - w) / 2, (ch - h) / 2);
        } else {
            double scale;

            int width;
            int height;
            int x;
            int y;

            RenderingHints hints = new RenderingHints(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_BICUBIC);

            g2.addRenderingHints(hints);

            // Calculate optimum image size
            scale = (double) cw / (double) image.getWidth(this);

            if (((double) image.getHeight(this) * scale) > (double) ch) {
                scale = (double) ch / (double) image.getHeight(this);
            }

            width = (int) (scale * image.getWidth(this));

            height = (int) (scale * image.getHeight(this));

            x = cx + ((cw - width) / 2);

            y = cy + ((ch - height) / 2);

            // Draw the image
            //g2.drawImage(image, x, y, x + width, y + height, 0, image.getWidth(this), image.getHeight(this), this);
            g2.drawImage(image, x, y, x + width, y + height, this);
        }
    }
}


Was This Post Helpful? 1
  • +
  • -

Page 1 of 1