0

This is my full codes here with some explanation.

public class SlideShow extends javax.swing.JFrame {

JPanel      slides;
CardLayout  layoutManager;
    private JButton btnPrev;
    private JButton btnNext;
    private JButton btnHome;
    private JButton btnSound;

public SlideShow() {
super();

setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));

    btnPrev = new javax.swing.JButton();
    btnNext = new javax.swing.JButton();
    btnHome = new javax.swing.JButton();
    btnSound = new javax.swing.JButton();
    btnPrev.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/back+button.png")));
    btnNext.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/next2.png")));
    btnHome.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/home_icons.png")));
    btnSound.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/Media-Controls-Volume-Down-icon.png")));

slides = new JPanel();
slides.setBackground(Color.WHITE);
slides.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    slides.setLayout(layoutManager = new CardLayout(0,0));

    for(int i=2; i<=24; i++){
    slides.add(i+".png", new JLabel(new ImageIcon(getClass().getResource("/resources/"+i+".png"))));
    }
    add(slides);

    add(btnHome);
    add(btnPrev);
    add(btnNext);
    add(btnSound);

    btnPrev.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            layoutManager.previous(slides);
        }
    });

    btnNext.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            layoutManager.next(slides);
        }
    });

    btnHome.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            close();
            Frame fr = new Frame();
            fr.setVisible(true);
        }
    });

    btnSound.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            music("././build/classes/resources/test.wav");
        }
    });

    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(700,530);
}

    public void close(){
    super.dispose();
}

    public static void music(String path) 
{
    AudioStream BGM;
    AudioData MD;
    AudioDataStream audiostream;

    try{
    BGM = new AudioStream (new FileInputStream(path));
    MD = BGM.getData();

    audiostream = new AudioDataStream(MD);
    AudioPlayer.player.start(audiostream);
    }catch(IOException error){}

}

public static void main(String args[]) {
    SlideShow frame =  new SlideShow();
    frame.setVisible(true);
}

}

I have a slideshow with multiple images within my JFrame. Every slide has a button which will output some sounds when it clicked. These slides are called within same JFrame. So, I didn't have to make many JFrame for each slides. I want to make different sounds for every slides. All I have to do is called the path of the slides images to match the sound.

My situation here is, basically, I want to shorten the variable of the ImageIcon so that I can return a specific path like 5.png to insert a sound. However, I can't do that without calling the full path in the ImageIcon and somehow, it doesn't work at all even if I called the full path.

So, if I can get a specific path at slides as a variable or something like that, I can use it to call different sound using same button. How to shorten it? Or, is there a way to get a specific variable from slides? How to call the variable though? There are 24 slides images in this app and how to differentiate it?

I have test this code JOptionPane.showMessageDialog(null, "Test!"); in the for loop and it appears that this codes output 24 times before the actual slides appear. So, it means, that for loop only input the image and I have no idea how to call it back so I can make something like if else statement to put sounds at different slides.

user2781911
  • 79
  • 1
  • 2
  • 9
  • Your code is very short. Could you add a bit more detail, like the construction of the frame and the button. Is `slides` a component similar to a `JTabbedPane` or a custom data structure? When asking a question about a problem caused by your code, you will get much better answers if you provide complete code people can use to reproduce the problem (see http://stackoverflow.com/help/mcve for more information). – Freek de Bruijn Dec 15 '15 at 20:41
  • @FreekdeBruijn I edited my codes – user2781911 Dec 15 '15 at 20:46
  • Can you load all the sounds at stratup or only during runtime? – user1803551 Dec 15 '15 at 21:28
  • @user1803551 I can only load during runtime, which mean during I click the button – user2781911 Dec 15 '15 at 21:38
  • O.K., so what's left for me is to ask you what *exactly* you are having a problem doing, because you refer to many different things in the question. – user1803551 Dec 15 '15 at 22:14
  • @user1803551 worry not. because I have found the solution for my own problem! Probably I gonna delete this post because my problem is too specific and I didn't really know how to explain well about it. – user2781911 Dec 15 '15 at 22:35
  • You can post your own answer for others to use. I've also just added an answer that still might be useful. – Freek de Bruijn Dec 15 '15 at 22:36
  • Perhaps "Shorten the variable to make use of the path" is not very clear as a title for your question. You could change it to something like "Keeping track of sound files for slide show". – Freek de Bruijn Dec 15 '15 at 23:38

2 Answers2

2

You could store the paths to the sound files in a list and use the index of the current slide to pick the right sound path. I did not find a way to use the index from the CardLayout class; it has a currentCard field but it is not accessible.

These changes to your original version are visible in the code below:

Here is the code:

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import javax.sound.sampled.*;
import javax.swing.*;

public class SlideShow extends JFrame {

    private JPanel slides;
    private int slideIndex;
    private java.util.List<String> soundPaths;
    private CardLayout layoutManager;
    private JButton btnPrev;
    private JButton btnNext;
    private JButton btnHome;
    private JButton btnSound;

    public SlideShow() {
        super();

        setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));

        btnPrev = new JButton("Previous");
        btnNext = new JButton("Next");
        btnHome = new JButton("Home");
        btnSound = new JButton("Sound");
        btnPrev.setIcon(createIcon("/resources/back+button.png"));
        btnNext.setIcon(createIcon("/resources/next2.png"));
        btnHome.setIcon(createIcon("/resources/home_icons.png"));
        btnSound.setIcon(createIcon("/resources/Media-Controls-Volume-Down-icon.png"));

        slides = new JPanel();
        slides.setBackground(Color.WHITE);
        slides.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        slides.setLayout(layoutManager = new CardLayout(0,0));

        soundPaths = new ArrayList<>();
        String directory = "resources/images-and-sounds/";
        for(int i=2; i<=24; i++){
            final String name = "/resources/" + i + ".png";
            slides.add(i + ".png", new JLabel(createIcon(name)));
            //slides.add(i+".png", new JLabel(new ImageIcon(directory + i + ".png")));
            soundPaths.add(directory + i + ".wav");
        }
        add(slides);

        add(btnHome);
        add(btnPrev);
        add(btnNext);
        add(btnSound);

        btnPrev.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                layoutManager.previous(slides);
                slideIndex = (slideIndex > 0)
                        ? slideIndex - 1
                        : slides.getComponentCount() - 1;
            }
        });

        btnNext.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                layoutManager.next(slides);
                slideIndex = (slideIndex + 1) % slides.getComponentCount();
            }
        });

        btnHome.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                close();
                Frame fr = new Frame();
                fr.setVisible(true);
                slideIndex = 0;
            }
        });

        btnSound.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //music("././build/classes/resources/test.wav");

                if (Files.exists(Paths.get(soundPaths.get(slideIndex)))) {
                    music(soundPaths.get(slideIndex));
                }
            }
        });

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(700,530);
    }

    private ImageIcon createIcon(String name) {
        return new ImageIcon(getClass().getResource(name));
    }

    public void close(){
        super.dispose();
    }

    public static void music(String path)
    {
        // https://stackoverflow.com/a/30587573/1694043
        try {
            Clip clip = AudioSystem.getClip();
            clip.open(AudioSystem.getAudioInputStream(new File(path)));
            clip.start();
            //clip.loop(Clip.LOOP_CONTINUOUSLY);
        } catch (LineUnavailableException | IOException
                | UnsupportedAudioFileException e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        SlideShow frame = new SlideShow();
        frame.setVisible(true);
    }
}
Community
  • 1
  • 1
Freek de Bruijn
  • 3,552
  • 2
  • 22
  • 28
  • That's what I was looking for before! But my solution is a bit unpractical and not really good, compared to yours. Anyway, might I ask about the sound clip? Is the codes make the sound loop continuously? Because I need it for this eventually. And what about the type supported? Previously my codes only support `.wav` type audio only – user2781911 Dec 15 '15 at 22:45
  • If you call the `clip.loop`, it should be able to loop. According to the documentation, Java Sound supports various audio formats (like .au, .aif, and .wav), but their availability depends on the operating system. See for example http://stackoverflow.com/a/29713583/1694043 or https://docs.oracle.com/javase/7/docs/webnotes/tsg/TSG-Desktop/html/sound.html#gdjzj for more information. You can also convert sound files to a supported format. – Freek de Bruijn Dec 15 '15 at 23:11
  • Ok, now the problem is, when I open a new JFrame, the sound still there unless I close the app. How can I stop the sound after I change to another JFrame from another file in the same package? – user2781911 Dec 15 '15 at 23:20
  • 1
    You can convert the `clip` variable into a field and call the `clip.stop` method, just before you create a new frame (check whether `clip` is not null before calling the method). – Freek de Bruijn Dec 15 '15 at 23:36
  • Great, congratulations! Good luck with the rest of your project. – Freek de Bruijn Dec 15 '15 at 23:39
0

This is my own version, a bit unpractical, but at least I understand it. Basically, I add another variable j to replace the page slides as I can't seem to get to return its path. Due to my slides begin at page 2 so I declare it j=2. After that, I increment/decrement the variable j by each click of Next/Previous button. Hence, I can replace the numbering of the slide by the value of j.

To prevent over clicking more than total of my slides, I put .setVisible(false) at each button and call .setVisible(true) back to return the button.

By declaration of j, I can define any pages and add any sounds according to the pages by the same button by using if else statement.

public class SlideShow extends javax.swing.JFrame {

JPanel      slides;
CardLayout  layoutManager;
    private JButton btnPrev;
    private JButton btnNext;
    private JButton btnHome;
    private JButton btnSound;
    private int j=2;

public SlideShow() {
super();

setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));

    btnPrev = new javax.swing.JButton();
    btnNext = new javax.swing.JButton();
    btnHome = new javax.swing.JButton();
    btnSound = new javax.swing.JButton();
    btnPrev.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/back+button.png")));
    btnNext.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/next2.png")));
    btnHome.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/home_icons.png")));
    btnSound.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/Media-Controls-Volume-Down-icon.png")));

slides = new JPanel();
slides.setBackground(Color.WHITE);
slides.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    slides.setLayout(layoutManager = new CardLayout(0,0));

            if(j==2)
                btnPrev.setVisible(false);

    for(int i=2; i<=24; i++){
    slides.add(i+".png", new JLabel(new ImageIcon(getClass().getResource("/resources/"+i+".png"))));
    }
    add(slides);

    add(btnHome);
    add(btnPrev);
    add(btnNext);
    add(btnSound);

    btnPrev.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            layoutManager.previous(slides);
            j--;
            if(j!=24)
                btnNext.setVisible(true);
            if(j==2)
                btnPrev.setVisible(false);
            //JOptionPane.showMessageDialog(null, "Slide "+j);
        }
    });

    btnNext.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            layoutManager.next(slides);
            j++;
            if(j==24)
                btnNext.setVisible(false);
            if(j!=2)
                btnPrev.setVisible(true);
            //JOptionPane.showMessageDialog(null, "Slide "+j);
        }
    });

    btnHome.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            close();
            Frame fr = new Frame();
            fr.setVisible(true);
        }
    });

    btnSound.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
                if(j==2)
                    music("././build/classes/resources/test1.wav");
                else if(j==3)
                    music("././build/classes/resources/test2.wav");
        }
    });

    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(700,530);
}

    public void close(){
    super.dispose();
}

    public static void music(String path) 
{
    AudioStream BGM;
    AudioData MD;
    AudioDataStream audiostream;

    try{
    BGM = new AudioStream (new FileInputStream(path));
    MD = BGM.getData();

    audiostream = new AudioDataStream(MD);
    AudioPlayer.player.start(audiostream);
    }catch(IOException error){}

}

public static void main(String args[]) {
    SlideShow frame =  new SlideShow();
    frame.setVisible(true);
}

}

user2781911
  • 79
  • 1
  • 2
  • 9