Jack-in-the-Box


1. Create a user interface (GUI) that has a single button labeled "Surprise".
     If you need help, take a look at the instructions for the Fortune Cookie recipe.


2. When the user presses the button 5 times, show them a jack-in-the-box using the methods below.
(A sample jackInTheBox.png file is provided in the recipe package(_2_jack_in_the_box))

private void showPicture(String fileName) {
    try {
        JLabel imageLabel = createLabelImage(fileName);
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(imageLabel);
        frame.setVisible(true);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
private JLabel createLabelImage(String fileName) {
	try {
            URL imageURL = getClass().getResource(fileName);
            if (imageURL == null) {
	       System.err.println("Could not find image " + fileName);
	       return new JLabel();
            } else {
                Icon icon = new ImageIcon(imageURL);
                JLabel imageLabel = new JLabel(icon);
                return imageLabel;
            }
        } catch (Exception e) {
            System.err.println("Could not find image " + fileName);
            return new JLabel();
        }
}

3. Also play a sound when the jack-in-the-box pops up using this method.
(A sample sound homer-woohoo.wav is provided in the recipe package(_2_jack_in_the_box))

private void playSound(String soundFile) { 
        String path = "src/_03_gui_from_scratch/_2_jack_in_the_box/";
        File sound = new File(path+soundFile);
        if (sound.exists()) {
            new Thread(() -> {
            try {
                Clip clip = AudioSystem.getClip();
                clip.open(AudioSystem.getAudioInputStream(sound));
                clip.start();
                Thread.sleep(clip.getMicrosecondLength()/1000);
            }
            catch (Exception e) {
                System.out.println("Could not play this sound");
            }}).start();
        }
        else {
            System.out.println("File does not exist");
        }
}