Creating Slide Show using Java

Today i was doing some search in my personal computer prior to formatting the hard disk and to take backup of important files and I came across a small java source code file. I wrote this code during my collage days and did it as part of the technical exhibition conducted by my college. As part of it I got a chance to prepare some presentation on game development basics and created some slides. All I wanted was to run this slides (images) in an equal interval of time, so it will run continuously in circular fashion without any user intervention. The program will load the predefined images using the file name and display it for three seconds and move it to next image. After reaching the the last image, it will start again from the first image. I would like to share the code here 🙂

Source Code

import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

class JavaSlider extends JPanel implements Runnable {
	
	private Thread sliderThread;
	private boolean active;
	private JFrame parent;
	
	public JavaSlider(JFrame parent) {
		super();
		sliderThread = new Thread(this);
		active = false;
		println("Panel created...");
		this.parent = parent;
	}
	
	public void setActive(boolean status) {
		println("Thread activated/deactivated...");
		active = true;
	}
	
	public Thread getThread() {
		return sliderThread;
	}
	
	public void start() {
		setActive(true);
		println("Thread started...");
		sliderThread.start();
	}
	
	@Override
	public void run() {
		int counter = 1;
		String name = "";
		while (active) {
			try {
				name = "slide" + counter + ".png";
				println("Loading file " + name + "...");
				BufferedImage image = ImageIO.read(getClass().getResource(name));
				println("Loaded file " + name + "...");
				parent.setSize(image.getWidth() + 4, image.getHeight() + 32);
				getGraphics().drawImage(image, 0, 0, image.getWidth(), image.getHeight(), this);
				if (++counter > 23) {
					println("Reseting counter...");
					counter = 1;
				}
				Thread.sleep(3000);
			} catch (IOException | InterruptedException ex) {
				println("Interrupted...");
			}
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		JFrame frame = new JFrame("Java Slider");
		JavaSlider panel = new JavaSlider(frame);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(960, 720);
		frame.setContentPane(panel);
		frame.setResizable(false);
		frame.setVisible(true);
		frame.setLocation(0, 0);
		frame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent we) {
				panel.setActive(false);
			};
		});
		panel.start();
		panel.getThread().join();
	}
	
	public static void println(String message) {
		System.out.println(message);
	}
}
Advertisements