This site requires JavaScript, please enable it in your browser!
Greenfoot back
hkrhässleholm
hkrhässleholm wrote ...

2013/3/3

Hi all friends how are you? I am really uncertain if I can get help about java code what I am writting in NetBeans. Hopefully you will appreciate me.

hkrhässleholm hkrhässleholm

2013/3/3

#
I am about to finish a memory or card game in java where the half of the codes (Or solution) are given by my school itself. So my task is to finish the rest and build the game in netbeans. Here I will present the codes theat I got from my school which I don't really understand specially the "try" and "catch" statement. If anyone pls can explain the all codes from the begining in "MemoryCard" class (off course I also have three other classes), I will be very grateful to you. Thankx
package memory;

import java.awt.Image;
import java.awt.image.BufferedImage;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

/**
 * Class to handle one single meory card
 * (Each card is supposed to be placed at two positions on the board)
 * @author Sandra Nilsson
 */
public class MemoryCard {

    private Image img;
    private Image backImg;
    private Clip sound;

    /**
     * Creates a new memory card object and reads the given files from disc into
     * memory.
     * Use this constructor when you want to have sounds associated with each card!
     * @param imgName the name of the file where to find the image file that shall represent this card
     * @param backImgName  the name of the file where to find the back side file that shall represent this card
     * @param audioFileName  the name of the file where to find the sound file that shall represent this card
     */
    public MemoryCard(String imgName, String backImgName, String audioFileName) {
        initImages(imgName, backImgName);
        initSound(audioFileName);
    }

    /**
     * Creates a new memory card object and reads the given files from disc into
     * memory and saves the data in this object
     * @param imgName the name of the file where to find the image file that shall represent this card
     * @param backImgName the name of the file where to find the back side file that shall represent this card
     */
    public MemoryCard(String imgName, String backImgName) {
        initImages(imgName, backImgName);
    }

    /**
     * Reads the images from file
     * @param imgName the name of the file where to find the image that shall represent this card
     * @param backImgName the name of the file where to find the back side image that shall represent this card
     */
    private void initImages(String imgName, String backImgName) {
        try {
            File f = new File(imgName);
            System.out.println("Reading " + f.getAbsolutePath());
            this.img = ImageIO.read(f);
        } catch (IOException ex) {
            System.out.println("Error when reading image for " + imgName);
            ex.printStackTrace();
        }

        try {
            File f = new File(backImgName);
            BufferedImage bi = ImageIO.read(f);
            backImg = ImageIO.read(f);
        } catch (IOException ex) {
            System.out.println("Error when reading back image " + backImgName);
            ex.printStackTrace();
        }
    }

    /**
     * Reads the given sound file and saves it for later use.
     * @param soundFile the path to the sound file.
     */
    private void initSound(String soundFile) {
        // Open an input stream to the audio file.
        InputStream in = null;
        AudioInputStream stream = null;
        try {
            stream = AudioSystem.getAudioInputStream(new File(soundFile));
            AudioFormat format = stream.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat());
            sound = (Clip) AudioSystem.getLine(info);
            sound.open(stream);
        } catch (LineUnavailableException ex) {
            System.out.println("Error when creating sound from file " + soundFile);
            ex.printStackTrace();
        } catch (UnsupportedAudioFileException ex) {
            System.out.println("Error when creating sound from file " + soundFile);
            ex.printStackTrace();
        } catch (FileNotFoundException ex) {
            System.out.println("Error when creating sound from file " + soundFile);
            ex.printStackTrace();
        } catch (IOException ex) {
            System.out.println("Error when creating sound from file " + soundFile);
            ex.printStackTrace();
        } finally {
            try {
                stream.close();
            } catch (IOException ex) {
                //Do not bother about this
            }
        }
    }

    /**
     * Method to get the image object that represent the back of this card
     * @return the back image object
     */
    public Image getBackImg() {
        return backImg;
    }

    /**
     * Method to get the image object that represents the front of this card
     * @return
     */
    public Image getImg() {
        return img;
    }

    /**
     * Plays the sound file of this card (if any)
     */
    public void play() {
        if (sound != null) {
            sound.flush();
            //Restart the sound every time
            sound.setFramePosition(0);
            System.out.println("Playing");
            sound.start();

        } else {
            // System.out.println("No sound available");
        }
    }
}
Gevater_Tod4711 Gevater_Tod4711

2013/3/3

#
The try catch (finally) blocks have to catch exceptions concerning the reading of a file in your case. If you try to read the values of a file there might be exceptions because the file doesn't exist (FileNotFoundException) or because of the loading has been interrupted (InterruptedIOException). If you don't catch this exceptions the execution of the programm will stop. To protect your programm from crashing the execution this way you use the try catch block (you can also add a finally block if necessary). The explenation of the whole other code would take very long. Have you got any specific questions? That would make it easyer to help you.
hkrhässleholm hkrhässleholm

2013/3/4

#
Thank you very much. Ya sure, now I will ask some specific questions. 1. Why do we need to import the line buffered image (at the line 4) 2. Why the io.file is used ( at the line 6)? 3. What is the difference between these two import line- import java.io.FileNotFoundException; and import java.io.IOException; 4. What does line 63 do? 5. ex.printStackTrace();- what does it do? 6. What is InputStream at the line 87? 7. And can u please give me a very simple and short overview of the class. What is main purpose of the class? May be I know the answer, but still now need to be cleared.
mjrb4 mjrb4

2013/3/4

#
Regarding 1-4, you need to import any class which you use which isn't in the same package as your code (declared in the first line of your file.) So you need to import java.io.File because you use it in line 6, FileNotFoundException because you use it in line 100, and so on. Line 63:
System.out.println("Reading " + f.getAbsolutePath());
...prints out "Reading " then the absolute path of the file referred to by `f`.
ex.printStackTrace();
...prints out a "stack trace" for the exception. If something goes wrong with your code (like if the file doesn't exist) that can't be determined at compile time, an exception will be thrown instead. This exception in this line is denoted by `ex`, and the printStackTrace() method will print out the message given by the exception, as well as the call chain up to that point (what called what to get to the point of that exception being thrown.) The AutioInputStream at line 87 is a special InputStream designed to read data from audio files, so that the sound can then be played. An InputStream in general is a class that takes some source (such as a file, web page, etc.) and then provides a stream of bytes read from that source. With that information, you should hopefully be able to work out what the class is doing yourself, so I'll leave the last point to you!
danpost danpost

2013/3/4

#
For more details on 'try'/'catch'/'finally', refer to the Java tutorial pages on exceptions.
hkrhässleholm hkrhässleholm

2013/3/4

#
Hi Thanks for ur answer mjrb4& danpost! Well, as I understand this class is for showing exception or error messege. Now, I will put the codes for another class "MemoryFrame". My code demonstartion is below.
package memory;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;

/**
 * Class to handle the frame.
 * 
 * No need to change anything here!!
 * @author Sandra Nilsson
 */
public class MemoryFrame extends JFrame implements WindowListener {

    MemoryPanel mem;

    /** Creates and initializes a new instance of DrawerFrame */
    public MemoryFrame(String title) {
        super(title);

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.addWindowListener(this);
        this.setIgnoreRepaint(true);
        this.setResizable(false);
        //Set the desired size of the frame
        setSize(800, 800);
        init();
    }

    /**Initializes the frame*/
    private void init() {
        mem = new MemoryPanel();
        this.getContentPane().add(mem);
    }

    /**
     * Set this frame visible (showing) and make sure that the board is drawn at the same time.
     * @param visible
     * @Override setVisible method in JFrame
     */
    public void setVisible(boolean visible) {
        super.setVisible(visible);
        mem.draw();
    }

    /**
     * Mehtod that is called when the window is opened
     * @param e the event
     */
    public void windowOpened(WindowEvent e) {
        mem.draw();
    }

    /**
     * Mehtod that is called when the window is back from beeing iconified
     * @param e the event
     */
    public void windowDeiconified(WindowEvent e) {
        mem.draw();
    }

    /**
     * Mehtod that is called when the window is activiated
     * @param e the event
     */
    public void windowActivated(WindowEvent e) {
        mem.draw();
    }

    /**
     * Mehtod that is called when the window is on its way to be closed (before it clises)
     * @param e the event
     */
    public void windowClosing(WindowEvent e) {
        try {
            mem.save();
        } catch (IOException ex) {
           System.err.println("Failed to save highscore");
           ex.printStackTrace();
        }
    }

    /**
     * Mehtod that is called when the window is closed
     * @param e the event
     */
    public void windowClosed(WindowEvent e) {
    }

    /**
     * Mehtod that is called when the window is iconified
     * @param e the event
     */
    public void windowIconified(WindowEvent e) {
    }

    /**
     * Mehtod that is called when the window is deactivated
     * @param e the event
     */
    public void windowDeactivated(WindowEvent e) {

    }
}
In order to understand and capture easily I will ask my questions in my next post.
hkrhässleholm hkrhässleholm

2013/3/4

#
Some specific questions: 1. At the line 22, what does super do? 2. line 24-27, what they do? and why the "this" are used repeatedly? 3. What does line 36 do? 4. 61& 69 explain these lines.
Oxy Oxy

2013/3/5

#
1) super is a keyword that calls the superclass, your currently in the subclass of JFrame. in this stance they are passing along a paramater of a String. (the title) it will set the title of your window to that variable. perhaps search on google for class hierarchy for a better understanding of superclasses. 2) the this. keyword is used to indicate THIS class. so they write THIS classes default close operation is blah blah blah. and so on. its often used for readability as well. for example.
private int MELLONS;
private String STATEMENT;

public EXAMPLE(int MELLONS, STRING STATEMENT)
{
        this.MELLONS = MELLONS;
        this.STATEMENT = STATEMENT;
}
That allowed me to name my private variables the same thing as those paramaters so i dont have to waste any time thinking of a new similiar name. 3) that just adds a memory panel to the Content Pane. probelly to store memory, might have to google that one. 4) Those are inherited methods from Window Listener that you implemented in line 16. you need to incorperate methods from a inherited class in order for the class not to have a syntax error. The WindowOpened method Invokes the first time a window is made visible. and the WindowDeIconified method Invokes when a window is changed from a minimized to a normal state. see http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/event/WindowListener.html for more information on the WindowListener class you inherited
hkrhässleholm hkrhässleholm

2013/3/6

#
Hi nice explanation. I would like to show my MemoryMain class and want to have more explanation. 1. what does UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); this line do? 2. Explain the line SwingUtilities.invokeLater(new Runnable().
package memory;


import javax.swing.SwingUtilities;
import javax.swing.UIManager;

/**
 *
 * @author Sandra Nilsson
 */
public class MemoryMain {

    /**
     * Main method, to run the memory game
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            // Set System L&F
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
        }
        
        //Creates the MemoryFrame and let it run asyncroniosly to the event dispatch thread
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MemoryFrame("DA5180 Memory Game").setVisible(true);
            }
        });
    }
}
Hi nice explanation. I would like to show my MemoryMain class and want to have more explanation. 1. what does UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); this line do? 2. Explain the line SwingUtilities.invokeLater(new Runnable().
You need to login to post a reply.