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);
	}
}

Developing a Mini Calculator Part-2

Hello, this is a continuation of article on Developing a Mini Calculator Part-1. In the first part I have explained about the components required for this application. Today we will see the implementation of Calculation Logic.

Note: I will be using Java programming language to demonstrate the examples

Calculation Logic

Since our calculator only support four operations and each of them take two operands and one operator it will be easy for us to write one single procedure or method which do all the necessary operation and return the result

public static double doCalculate(double operand1, char operator, double operand2) {
    double result = 0.0;
    switch (operator) {
        case '+': result = operand1 + operand2; break;
        case '-': result = operand1 - operand2; break;
        case '/': result = operand1 / opernad2; break;
        case '*': result = operand1 * operand2; break;
    }
    return result;
}

The above given method is seems good but what will happen if you divide a number with zero. Yes of course division by zero is not possible. In that case what we will do. One way is to insert an error handling code that do the required when such and error comes. Again think of other scenario where the result is infinity or not a number. What we will do again insert some logic to handle that scenario.

Instead of keeping all calculations in one method we can separate them, like one method for addition, one four subtraction etc. Each of them will take three arguments and return the expected result.

public static double doCalculate(double operand1, char operator, double operand2) {
    double result = 0.0;
    switch (operator) {
       case '+': result = doAddition(operand1, operand2); break;
       case '-': result = doSubtraction(operand1, operand2); break;
       case '/': result = doDivision(operand1, operand2); break;
       case '*': result = doMultiplication(operand1 * operand2); break;
    }
    return result;
}

private static double doAddition(double operand1, double operand2) {
    return (operand1) + (operand2);
}

private static double doSubtraction(double operand1, double operand2) {
    return (operand1) - (operand2);
}

private static double doDivision(double operand1, double operand2) {
    return (operand1) / (operand2);
}

private static double doMultiplication(double operand1, double operand2) {
    return (operand1) * (operand2);
}

Now we can manage each operation logic separately, say for division we can add extra error handling code

private static double doDivision(double operand1, double operand2) {
    double result = 0.0;
    try {
        result = operand1 / operand2;
    catch (ArithmeticException ex) {
        // set some flag to indicate this error
    }
    if (new Double(result).isNaN()) {
        // set some flag to indicate this
        result = 0.0;
    } else if (!Double.isFinite(result)) {
        // set some flag to indicate this
        result = 0.0;
    }
    return result;
}

If we look at the above program we will see two things. If the division leads to error we will set some flag and return zero. If the result is not a number or infinite we do the same. The flag might be some where else in the program. We have to introduce a state change some where out side the calculation logic. This is okay! because it doesn’t harm anything.

Instead of changing the state out side the calculation logic we can simply return the entire result out side the calculation logic. Say, the result, is it valid?, is it infinite?, is it an error. How we will do this?

public class Result {
    private double value;
    private boolean error;
    private boolean finite;
    private boolean nan;
    
    public Result() {
        // initialize to default
    }
    // get and set methods will come here
}

We can create a new Result object to do this. This object will keep all the information related to the operation carried out. The Calculation Logic simply return the final result with necessary information to process the result. So an external module say Core can process the result as required without worrying about the calculations 🙂

Calculation Logic: Do the required calculations and return the result
Core: Process the result and take the necessary actions

private static Result doDivision(double operand1, double operand2) {
    Result result = new Result();
    double value = 0.0;
    try {
        value = operand1 / operand2;
    catch (ArithmeticException ex) {
        result.setError(true);
    }
    result.setValue(value);
    if (new Double(value).isNaN()) {
        result.setNaN(true);
    } else if (!Double.isFinite(result)) {
        result.setFinite(false);
    }
    return result;
}

Here ends the second part. Hope you like it 🙂

In the next part we will see the implementation of other modules.