Archive

Archives pour la catégorie ‘Java’

Reflect Helper class

24/03/2010
Commentaires fermés

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Utility class for reflect purpose.
 */
public final class ReflectHelper {
    /**
     * Empty private constructor for util class.
     */
    private ReflectHelper() {
        // Empty private constructor for util class.
    }

    /** Constant meaning accessor type setter. */
    public static final String SETTER = "set";

    /** Constant meaning accessor type getter. */
    public static final String GETTER = "get";

    /** Constant meaning accessor type getter for boolean. */
    public static final String BOOLEAN_GETTER = "is";

    /**
     * Instantiate a Class using its name.
     * @param className The class name.
     * @param arguments The arguments to be passed to constructor.
     * @param types The types of arguments.
     * @return The instance
     * @throws ClassNotFoundException Thrown if you try to instanciate a class that does not exist.
     * @throws NoSuchMethodException Thrown if you try to retreive a method that does not exist.
     * @throws InvocationTargetException Can occure during invocation
     * @throws IllegalAccessException Thrown while trying to access illagaly the instance
     * @throws InstantiationException Any other case
     */
    public static Object newInstance(final String className, final Object[] arguments, final Class[] types) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        // Retrieve class to be load
        Class clazz = Class.forName(className);

        // R??cup??ration du constructeur correspondant ????????? la liste des parametres donn??e
        Constructor constructor = clazz.getConstructor(types);

        // Cr??ation d'une instance avec le constructeur r??cup??r??s
        return constructor.newInstance(arguments);
    }

    /**
     * Instantiate a Class using its name.
     * @param className The class name.
     * @param arguments The parameters to be passed to constructor.
     * @return The instance
     * @throws ClassNotFoundException Thrown if you try to instanciate a class that does not exist.
     * @throws NoSuchMethodException Thrown if you try to retreive a method that does not exist.
     * @throws InvocationTargetException Can occure during invocation
     * @throws IllegalAccessException Thrown while trying to access illagaly the instance
     * @throws InstantiationException Any other case
     */
    public static Object newInstance(final String className, final Object[] arguments) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        // Construct the types array
        Class[] types = new Class[arguments.length];
        for (int i = 0; i <= arguments.length; ++i) {
            types[i] = arguments[i].getClass();
        }
        // Instantiate class
        return newInstance(className, arguments, types);
    }

    /**
     * Instantiate a Class using its name.
     * @param className The class name
     * @return The instance
     * @throws ClassNotFoundException Thrown if you try to instanciate a class that does not exist.
     * @throws InstantiationException Any other case
     * @throws NoSuchMethodException Thrown if you try to retreive a method that does not exist.
     * @throws InvocationTargetException Can occure during invocation
     * @throws IllegalAccessException Thrown while trying to access illagaly the instance
     */
    public static Object newInstance(final String className) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        return newInstance(className, new Object[] {});
    }

    /**
     * Invoke a methods (<code>methodName</code>) from an <code>object</code> with <code>arguments</code> of <code>types</code>.
     * @param object     The object from which you want to invoke a methods.
     * @param methodName The method name to invoke.
     * @param arguments  The arguments to pass to the methods.
     * @param types      The types of arguments.
     * @return the result of the invoked method.
     * @throws NoSuchMethodException Thrown if you try to retreive a method that does not exist.
     * @throws InvocationTargetException Can occure during invocation
     * @throws IllegalAccessException Thrown while trying to access illagaly the instance
     */
    public static Object invokeMethod(final Object object, final String methodName, final Object[] arguments, final Class[] types) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        try {
            // If simple getter is not found ... try boolean one
            return getMethod(object.getClass(), methodName, types).invoke(object, arguments);
        } catch (NoSuchMethodException ex) {
            NoSuchMethodException thrown = new NoSuchMethodException(formatInvokeGetterException(ex, object, methodName, arguments));
            thrown.setStackTrace(ex.getStackTrace());
            throw thrown;
        } catch (InvocationTargetException ex) {
            throw new InvocationTargetException(ex.getTargetException(), formatInvokeGetterException(ex.getTargetException(), object, methodName, arguments));
        } catch (IllegalAccessException ex) {
            IllegalAccessException thrown = new IllegalAccessException(formatInvokeGetterException(ex, object, methodName, arguments));
            thrown.setStackTrace(ex.getStackTrace());
            throw thrown;
        }
    }

    /**
     * Invoke a methods (<code>methodName</code>) from an <code>object</code> with <code>arguments</code> of <code>types</code>.
     * @param object     The object from which you want to invoke a methods.
     * @param method     The method to invoke.
     * @param arguments  The arguments to pass to the methods.
     * @return the result of the invoked method.
     * @throws InvocationTargetException Can occure during invocation
     * @throws IllegalAccessException Thrown while trying to access illagaly the instance
     */
    public static Object invokeMethod(final Object object, final Method method, final Object[] arguments) throws IllegalAccessException, InvocationTargetException {
        return method.invoke(object, arguments);
    }

    /**
     * Invoke a methods (<code>methodName</code>) from an <code>object</code> with <code>arguments</code> of <code>types</code>.
     * @param clazz      The <code>clazz</code> on which to retreive the method.
     * @param methodName The method name to invoke.
     * @param arguments  The arguments to pass to the methods.
     * @param types      The types of arguments.
     * @return the result of the invoked method.
     * @throws NoSuchMethodException Thrown if you try to retreive a method that does not exist.
     * @throws InvocationTargetException Can occure during invocation
     * @throws IllegalAccessException Thrown while trying to access illagaly the instance
     */
    public static Object invokeStaticMethod(final Class clazz, final String methodName, final Object[] arguments, final Class[] types) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        return getMethod(clazz, methodName, types).invoke(null, arguments);
    }

    /**
     * Invoke a methods (<code>methodName</code>) from an <code>object</code> with <code>arguments</code>.
     * @param object The object from which you want to invoke a methods.
     * @param methodName The method name to invoke.
     * @param arguments The arguments to pass to the methods.
     * @return the result of the invoked method.
     * @throws NoSuchMethodException Thrown if you try to retreive a method that does not exist.
     * @throws InvocationTargetException Can occure during invocation
     * @throws IllegalAccessException Thrown while trying to access illagaly the instance
     */
    public static Object invokeMethod(final Object object, final String methodName, final Object[] arguments) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        // Construct the types array
        Class[] types = new Class[arguments.length];
        for (int i = 0; i < arguments.length; ++i) {
            types[i] = arguments[i].getClass();
        }
        return invokeMethod(object, methodName, arguments, types);
    }

    /**
     * This method invoke the setter according to the <code>fieldName</code> on the <code>toFill</code> object with as argument.
     * <code>valueToSet</code> of type <code>valueToSetType</code>
     * @param toFill the object to fill.
     * @param fieldName the field name.
     * @param valueToSet the value to set.
     * @param valueToSetType the type of the value to set.
     * @throws NoSuchMethodException Thrown if you try to retreive a method that does not exist.
     * @throws InvocationTargetException Can occure during invocation
     * @throws IllegalAccessException Thrown while trying to access illagaly the instance
     */
    public static void invokeSetter(final Object toFill, final String fieldName, final Object valueToSet, final Class valueToSetType) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        invokeMethod(toFill, computeAccessorMethodName(SETTER, fieldName), new Object[] {valueToSet}, new Class[] {valueToSetType});
    }

    /**
     * This method invoke the getter according to the <code>fieldName</code> on the <code>toFill</code> object with as argument.
     * <code>valueToSet</code> of type <code>valueToSetType</code>
     * @param bean the JavaBean object.
     * @param fieldName the field name.
     * @return The value returned by the getter.
     * @throws NoSuchMethodException Thrown if you try to retreive a method that does not exist.
     * @throws InvocationTargetException Can occure during invocation
     * @throws IllegalAccessException Thrown while trying to access illagaly the instance
     */
    public static Object invokeGetter(final Object bean, final String fieldName) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        String field = fieldName;
        Object instance = bean;
        while (field.indexOf('[') > -1) {
            // Invoke getter to retreive the child element
            instance = invokeGetter(instance, field.substring(0, field.indexOf('[')));
            // If result is null no need to continue
            if (instance == null) {
                return null;
            }
            // Re route field name to retreive the field of the child instance
            int index = Integer.parseInt(field.substring(field.indexOf('[') + 1, field.indexOf(']')));
            instance = Array.get(instance, index);
            field = field.substring(field.indexOf(']') + 1);
        }
        // In the case that you want to retrieve in one time the field of a child object
        while (field.indexOf('.') > 0) {
            // Invoke getter to retreive the child element
            instance = invokeGetter(instance, field.substring(0, field.indexOf('.')));
            // If result is null no need to continue
            if (instance == null) {
                return null;
            }
            // Re route field name to retreive the field of the child instance
            field = field.substring(field.indexOf('.') + 1);
        }
        if (field.length() == 0) {
            return instance;
        }
        try {
            return invokeMethod(instance, computeAccessorMethodName(GETTER, field), new Object[] {});
        } catch (NoSuchMethodException noSuchMethod) {
            String accessor = computeAccessorMethodName(BOOLEAN_GETTER, field);
            try {
                // If simple getter is not found ... try boolean one
                return invokeMethod(instance, accessor, new Object[] {});
            } catch (NoSuchMethodException ex) {
                // If it's still not found or return an error ... than throw the original error.
                throw noSuchMethod;
            }
        }
    }

    /**
     * Format a more detailed message when an exception occured during invocation.
     * @param ex        The exception
     * @param object    The object on which the given method is invoked
     * @param method    The invoked method
     * @param arguments The method arguments
     * @return The detailed message
     */
    private static String formatInvokeGetterException(final Throwable ex, final Object object, final String method, final Object[] arguments) {
        String message = ex.getMessage();
        if (message == null) {
            message = "";
        } else {
            message += " - ";
        }
        String args = "";
        for (int i = 0; i < arguments.length; ++i) {
            args += arguments[i].getClass().getName();
            // Concat each element
            args += arguments[i];
            // Add separator if necessary
            if ((i < arguments.length - 1)) {
                args += ", ";
            }
        }
        return message + "Error occured while tyring to invoke " + object.getClass().getName() + "." + method + "(" + args + ") method.";
    }

    /**
     * Get the field (<code>filedName</code>) value of an <code>object</code>.
     * @param object The <code>object</code> on which to retreive the field value.
     * @param fieldName The <code>fieldName</code> to retreive.
     * @return The value of the field.
     * @throws NoSuchFieldException Thrown if you try to retreive a field that does not exist.
     * @throws InvocationTargetException Can occure during invocation
     * @throws IllegalAccessException Thrown while trying to access illagaly the instance
     */
    public static Object getFieldValue(final Object object, final String fieldName) throws NoSuchFieldException, IllegalAccessException, InvocationTargetException {
        try {
            return getField(object.getClass(), fieldName).get(object);
        } catch (NoSuchFieldException ex) {
            try {
                return invokeGetter(object, fieldName);
            } catch (NoSuchMethodException x) {
                throw ex;
            }
        }
    }

    /**
     * Get the field (<code>filedName</code>) of a class (<code>clazz</code>).
     * @param clazz The <code>clazz</code> on which to retreive the field.
     * @param fieldName The <code>fieldName</code> to retreive.
     * @return The Field object of the given class.
     * @throws NoSuchFieldException Thrown if you try to retreive a field that does not exist.
     */
    public static Field getField(final Class clazz, final String fieldName) throws NoSuchFieldException {
        try {
            Field f = clazz.getDeclaredField(fieldName);
            f.setAccessible(true);
            return f;
        } catch (SecurityException e) {
            throw new RuntimeException(e);
        } catch (NoSuchFieldException e) {
            if (clazz == Object.class) {
                throw e;
            }
            // Get the one from parent super class recursivly
            return getField(clazz.getSuperclass(), fieldName);
        }
    }

    /**
     * Return all declared fields of a class (and all its super class).
     * @see {@link Class#getDeclaredFields()}
     * @param clazz The class on which to retreive the fields.
     * @return All the fields.
     */
    public static List getDeclaredFields(final Class clazz) {
        List fields = new ArrayList();
        Class current = clazz;
        while (!current.getName().equals(Object.class.getName())) {
            fields.addAll(Arrays.asList(current.getDeclaredFields()));
            current = current.getSuperclass();
        }
        return fields;
    }

    /**
     * Return all getter of a class (but not the ones from parent).
     * @param clazz The class on which to retreive the getters.
     * @return All the methods.
     */
    public static List getGetters(final Class clazz) {
        List getters = new ArrayList();
        if (clazz != null) {
            Method[] methods = clazz.getMethods();
            for (int i = 0; i < methods.length; i++) {
                if (methods[i].getDeclaringClass().equals(clazz)) {
                    if ((methods[i].getName().startsWith(GETTER) || methods[i].getName().startsWith(BOOLEAN_GETTER)) &amp;&amp; methods[i].getParameterTypes().length == 0) {
                        getters.add(methods[i]);
                    }
                }
            }
        }
        return getters;
    }

    /**
     * Return all getter of a class (even parent's ones).
     * @param clazz The class on which to retreive the getters.
     * @return All the methods.
     */
    public static List getGettersRecursivly(final Class clazz) {
        List getters = new ArrayList();
        if (clazz != null) {
            Class current = clazz;
            while (!current.getName().equals(Object.class.getName())) {
                Method[] methods = current.getMethods();
                for (int i = 0; i < methods.length; i++) {
                    if (methods[i].getDeclaringClass().equals(current)) {
                        if ((methods[i].getName().startsWith(GETTER) || methods[i].getName().startsWith(BOOLEAN_GETTER)) &amp;&amp; methods[i].getParameterTypes().length == 0) {
                            getters.add(methods[i]);
                        }
                    }
                }
                current = current.getSuperclass();
            }
        }
        return getters;
    }

    /**
     * Return all getter of a class (but not the ones from parent).
     * @param clazz The class on which to retreive the getters.
     * @return All the methods.
     */
    public static List getSetters(final Class clazz) {
        List getters = new ArrayList();
        if (clazz != null) {
            Method[] methods = clazz.getMethods();
            for (int i = 0; i < methods.length; i++) {
                if (methods[i].getDeclaringClass().equals(clazz)) {
                    if (methods[i].getName().startsWith(SETTER) &amp;&amp; methods[i].getName().length() > SETTER.length() &amp;&amp; methods[i].getParameterTypes().length == 1) {
                        getters.add(methods[i]);
                    }
                }
            }
        }
        return getters;
    }

    /**
     * Return all getter of a class (even parent's ones).
     * @param clazz The class on which to retreive the getters.
     * @return All the methods.
     */
    public static List getSettersRecursivly(final Class clazz) {
        List getters = new ArrayList();
        if (clazz != null) {
            Class current = clazz;
            while (!current.getName().equals(Object.class.getName())) {
                Method[] methods = current.getMethods();
                for (int i = 0; i < methods.length; i++) {
                    if (methods[i].getDeclaringClass().equals(current)) {
                        if (methods[i].getName().startsWith(SETTER) &amp;&amp; methods[i].getName().length() > SETTER.length() &amp;&amp; methods[i].getParameterTypes().length == 1) {
                            getters.add(methods[i]);
                        }
                    }
                }
                current = current.getSuperclass();
            }
        }
        return getters;
    }

    /**
     * Retreive the method (<code>methodName</code>) of a class (<code>clazz</code>) using parameters <code>types</code>.
     * @param clazz The <code>clazz</code> on which to retreive the method.
     * @param methodName The method name to retreive.
     * @param types The types of the method's arguments.
     * @return A Method objec.
     * @throws NoSuchMethodException Thrown if you try to retreive a method that does not exist.
     */
    public static Method getMethod(final Class clazz, final String methodName, final Class[] types) throws NoSuchMethodException {
        try {
            Method m = clazz.getDeclaredMethod(methodName, types);
            m.setAccessible(true);
            return m;
        } catch (NoSuchMethodException x) {
            try {
                if (clazz == Object.class) {
                    throw x;
                }
                return getMethod(clazz.getSuperclass(), methodName, types);
            } catch (Exception ex) {
                throw x;
            }
        }
    }

    /**
     * This method compute the accessor method name according to the <code>accessorType</code> and <code>fieldName</code>.
     * @param accessorType the accessor type.
     * @param fieldName the field name.
     * @return the accessor method name.
     * @throw IllegalArgumentException If the arguments type is not valid.
     */
    private static String computeAccessorMethodName(final String accessorType, final String fieldName) {
        if (!accessorType.equals(SETTER) &amp;&amp; !accessorType.equals(GETTER) &amp;&amp; !accessorType.equals(BOOLEAN_GETTER)) {
            throw new IllegalArgumentException("Accessor Type : " + accessorType + " isn't correct");
        }
        if (null == fieldName || "".equals(fieldName)) {
            throw new IllegalArgumentException("fieldName migth not be null or empty");
        }
        return accessorType + fieldName.replaceFirst("" + fieldName.charAt(0), ("" + fieldName.charAt(0)).toUpperCase());
    }

    /**
     * If you want to map a getter/setter with its fied name.
     * Use this method to convert getter or setter into fieldname
     * @param method The method to be converted
     * @return The field name or method name if the method is neither a getter neither a setter
     */
    public static String getFieldName(final Method method) {
        String prefix = null;
        if (method.getName().startsWith(GETTER)) {
            prefix = GETTER;
        } else if (method.getName().startsWith(SETTER)) {
            prefix = SETTER;
        } else if (method.getName().startsWith(BOOLEAN_GETTER)) {
            prefix = BOOLEAN_GETTER;
        } else {
            return method.getName();
        }
        if (method.getName().length() == prefix.length()) {
            return method.getName();
        }
        return ("" + method.getName().charAt(prefix.length())).toLowerCase() + method.getName().substring(prefix.length() + 1);
    }
}

Java

Audio snippet code in Java

24/03/2010
Commentaires fermés

Here is an example of two simple Java classes that deals with audio streams ! One for retrieving Info, the other for playing sound …

Voici deux petits exemples de classe Java pour gérer des flux audio. L’une affichant les informations, l’autre implémentant un lecteur très minimaliste !


import java.io.File;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.Port;
import javax.sound.sampled.SourceDataLine;

public class AudioInfo {

    public static void main(final String[] args) {
        try {
            AudioFileFormat format = AudioSystem.getAudioFileFormat(new File("Recharger.wav"));
            System.out.println("format: " + format);

            Mixer.Info[] infos = AudioSystem.getMixerInfo();
            Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
            Line.Info lineInfo = null;
            for (int i = 0; i < infos.length; ++i) {
                Mixer mixer = AudioSystem.getMixer(mixerInfo[i]);
                System.out.println("Target lines infos");
                Line.Info[] lineInfos = mixer.getTargetLineInfo(Port.Info.SPEAKER);
                for (int l = 0; l < lineInfos.length; ++l) {
                    System.out.println("Line Info " + l + " - " + lineInfos[l]);
                    lineInfo = lineInfos[l];
                }
            }

            SourceDataLine sourceLine;
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, format.getFormat()); // format is an AudioFormat object
            if (AudioSystem.isLineSupported(info)) {
                // Obtain and open the line.
                try {
                    sourceLine = (SourceDataLine) AudioSystem.getLine(info);
                    sourceLine.open(format.getFormat());
                } catch (LineUnavailableException ex) {
                    // Handle the error.
                    ex.printStackTrace();
                }
            } else {
                // Handle the error.
                System.out.println("Line is not supported");
            }

            Port targetLine;
            if (AudioSystem.isLineSupported(Port.Info.SPEAKER)) {
                try {
                    targetLine = (Port) AudioSystem.getLine(Port.Info.SPEAKER);
                    targetLine.open();
                } catch (LineUnavailableException ex) {
                    // Handle the error.
                    ex.printStackTrace();
                }
            } else {
                // Handle the error.
                System.out.println("SPEAKER Line is not supported");
            }

        } catch (Exception ex) {
            //UnsupportedAudioFile... &amp; IO...
            ex.printStackTrace();
        }
    }
}

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class SoundPlayer extends JFrame implements Runnable {

    private final File currentDir; // Current directory
    private String oldFilename; // Last selected file name
    private final JComboBox soundChoice; // Dropdown list of files
    private final JButton play; // PLAY button
    private AudioInputStream source; // Stream for the sound file
    private SourceDataLine sourceLine; // The speaker output line
    private byte[] soundData; // Buffer to hold samples
    private int bufferSize; // Buffer size in bytes
    private Thread thread; // Playing thread
    private boolean playing = false; // Thread control

    public SoundPlayer() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setTitle("Sound File Player");
        setSize(250, 100);

        // Get the sounds file names from current directory
        currentDir = new File(System.getProperty("user.dir"));
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(final File directory, final String filename) {
                String name = filename.toLowerCase();
                return name.endsWith(".au") || name.endsWith(".aif") || name.endsWith(".wav");
            }
        };
        String soundFiles[] = currentDir.list(filter);
        if (soundFiles == null || soundFiles.length == 0) {
            JOptionPane.showMessageDialog(this, "No sound files .:. terminating...", "Sound Files Error", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
        soundChoice = new JComboBox(soundFiles);
        soundChoice.setSelectedIndex(0);
        newSound(soundFiles[0]);
        oldFilename = soundFiles[0];

        soundChoice.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                newSound((String) soundChoice.getSelectedItem());
            }
        });

        // Set up the PLAY button to play the current sound file
        play = new JButton("PLAY");
        play.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                if (e.getActionCommand().equals("PLAY")) {
                    startPlay();
                    play.setText("STOP");
                } else {
                    stopPlay();
                    play.setText("PLAY");
                }
            }
        });
        Container content = getContentPane();
        content.add(soundChoice);
        content.add(play, BorderLayout.SOUTH);
        setVisible(true);
    }

    public static void main(final String[] args) {
        new SoundPlayer();
    }

    public void newSound(final String filename) {
        File soundFile = new File(currentDir, filename);

        // We may have played a file already
        if (sourceLine != null) {// If we have a line
            if (sourceLine.isActive()) {
                sourceLine.stop(); // ...stop it
            }
            play.setText("PLAY"); // Ensure button is PLAY
        }

        // Now try for a stream and a line
        try {
            AudioInputStream newSource = AudioSystem.getAudioInputStream(soundFile);

            if (newSource.markSupported()) {
                newSource.mark(Integer.MAX_VALUE); // mark the start for later reset
            }

            AudioFormat format = newSource.getFormat(); // Get the audio format
            DataLine.Info sourceInfo = new DataLine.Info(SourceDataLine.class, format);
            if (AudioSystem.isLineSupported(sourceInfo)) { // If the line type is supported
                // Get a new line
                sourceLine = (SourceDataLine) AudioSystem.getLine(sourceInfo);
                bufferSize = (int) (format.getFrameSize() * format.getFrameRate() / 2.0f);
                sourceLine.open(format, bufferSize); // Open the line
                source = newSource; // New line is OK so save it
                soundData = new byte[bufferSize]; // Create the buffer for read
                oldFilename = filename; // Save the current file name
            } else {
                JOptionPane.showMessageDialog(null, "Line not supported", "Line NotSupported", JOptionPane.WARNING_MESSAGE);
                soundChoice.setSelectedItem(oldFilename); // Restore the old selection
            }
        } catch (UnsupportedAudioFileException e) {
            JOptionPane.showMessageDialog(null, "File not supported", "Unsupported File Type", JOptionPane.WARNING_MESSAGE);
            soundChoice.setSelectedItem(oldFilename);
        } catch (LineUnavailableException e) {
            JOptionPane.showMessageDialog(null, "Line not available", "Line Error", JOptionPane.WARNING_MESSAGE);
            soundChoice.setSelectedItem(oldFilename);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "I/O Error creating stream", "I/O Error", JOptionPane.WARNING_MESSAGE);
            soundChoice.setSelectedItem(oldFilename);
        }
    }

    // Start playing the current file
    public void startPlay() {
        if (sourceLine == null) {// Verify we have a line
            JOptionPane.showMessageDialog(null, "No line available", "Play Problem", JOptionPane.WARNING_MESSAGE);
            return;
        }
        thread = new Thread(this); // Create the playing thread
        playing = true; // Set the control to true
        thread.start(); // Start the thread
    }

    // Stop playing the current file
    public void stopPlay() {
        playing = false;
    }

    // The playing thread
    public void run() {
        sourceLine.start(); // Start the line
        int byteCount = 0; // Bytes read
        try {
            while (playing) { // Continue while true
                byteCount = source.read(soundData, 0, soundData.length); // Read the stream

                if (byteCount == -1) { // If it's the end of input
                    if (source.markSupported()) {
                        source.reset(); // ...put it back to the start
                        sourceLine.drain(); // Play what is left in the buffer
                        playing = false; // Reset the thread control
                    } else {
                        sourceLine.drain(); // Play what is left in the buffer
                        playing = false; // Reset the thread control
                        source.close();
                        newSound((String) soundChoice.getSelectedItem());
                    }
                    break; // then stop playing
                }
                sourceLine.write(soundData, 0, byteCount); // Write the array to the line
            }
        } catch (IOException e) { // For the stream read operation
            System.err.println(e);
        }
        sourceLine.stop(); // Stop the line
        play.setText("PLAY"); // Reset the button text
    }
}

Java , ,

Get classes contained in a package

24/03/2010
Commentaires fermés

En Anglais: This is a java code snipplet that retrieve the package’s classes.

In French: Un petit exemple de code java permettant de récupérer les classes contenues dans un package.


public static Class[] getClasses(Package pckg) throws IOException, ClassNotFoundException {
    // Translate the package name into an absolute path
    String name = "/" + pckg.getName().replace('.','/');

    // Get a File object for the package
    URL url = Launcher.class.getResource(name);
    File directory = new File(url.getFile());

    if (directory.exists()) {
        // Get the list of the files contained in the package
        String[] files = directory.list();
        ArrayList vClasses = new ArrayList();
        for (int i=0; i<files.length;++i) {

            // we are only interested in .class files
            if (files[i].endsWith(".class")) {
                // removes the .class extension
                String classname = files[i].substring(0,files[i].length()-6);
                vClasses.add(Class.forName(pckg.getName()+"."+classname));
            }
        }
        Class[] classes = new Class[vClasses.size()];
        for (int i=0; i<vClasses.size();++i) classes[i] = (Class)vClasses.get(i);
        return classes;
    } else {
        throw new IOException("Invalid directory: "+url);
    }
}

Java

Digester Factory

22/09/2009
Commentaires fermés

This is a DigesterFactory class that load a XML file into an object using an other XML rule file.

I like this way of loading java object from a XML file, because it’s not intrusive, you just have to give it a rule file that define the way of loading object.



import java.io.File;
import java.io.IOException;
import java.net.URL;

import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.DigesterLoader;
import org.xml.sax.SAXException;

/**
 * Digester Factory
 * This load a Java object from a XML file using Digester framework
 *
 * @author Gabriel Dromard
 */
public class DigesterFactory {
	/*
	public static Root loadRoot(File input) throws SAXException, Exception {
		// Create the digester instance
		Digester digester = new Digester();

		// Activate or not the DTD checking
		digester.setValidating( false );

		// This is needed because digester is sending errors directly to output without raising exceptions othervise
		//digester.setErrorHandler(new DefaultSAXErrorHandler());
		digester.setErrorHandler(new ErrorHandler() {
			public void error(SAXParseException exception) throws SAXException { throw exception; }
			public void fatalError(SAXParseException exception) throws SAXException { throw exception; }
			public void warning(SAXParseException exception) throws SAXException { throw exception; }
		});

		// Parsing rules
		digester.addObjectCreate( "myxml", Root.class );
		//digester.addSetProperties( "descriptor", "type", "type" );
		//digester.addSetProperties( "myxml/a/b", new String [] {"type", "target", "header"} , new String [] {"outputType", "outputTarget", "header"} );

		digester.addObjectCreate( "myxml/a", A.class );
		digester.addSetProperties( "myxml/a", "name", "name" );
		digester.addSetProperties( "myxml/a/b", "name" , "bname" );
		digester.addSetNext( "myxml/a", "setA");

		digester.addObjectCreate( "myxml/a/c", C.class );
		digester.addSetProperties( "myxml/a/c", new String [] {"name", "value"} , new String [] {"name", "value"} );
		digester.addBeanPropertySetter("myxml/a/c", "description");
		digester.addSetNext( "myxml/a/c", "addC");

		return (Root)digester.parse( input );
	}
*/

	/**
	 * Load an object from a XML file unsing digester framwork
	 * @param input The data input file defining the Java Object
	 * @param rules The rules input file defininf the digester rules for loading this Java Object
	 * @return Return an instance of the a Java Object (defined in rule file)
	 * @throws SAXException Can be thrown while parsing files.
	 * @throws Exception Can be MalformedURLException or IOException for the input or rules files.
	 * @see DigesterFactory#load(File, URL)
	 * @see DigesterFactory#load(URL, URL)
	 */
	public static Object load(File input, File rules) throws SAXException, IOException {
		Digester digester = DigesterLoader.createDigester(rules.toURI().toURL());
		return digester.parse(input);
	}

	/**
	 * Load an object from a XML file unsing digester framwork
	 * @param input The data input URL defining the Java Object
	 * @param rules The rules input URL defining the digester rules for loading this Java Object
	 * @return Return an instance of the a Java Object (defined in rule file)
	 * @throws SAXException Can be thrown while parsing files.
	 * @throws Exception Can be MalformedURLException or IOException for the input or rules files.
	 * @see DigesterFactory#load(File, URL)
	 * @see DigesterFactory#load(File, File)
	 */
	public static Object load(URL input, URL rules) throws SAXException, IOException {
		Digester digester = DigesterLoader.createDigester(rules);
		return digester.parse(input.openStream());
	}

	/**
	 * Load an object from a XML file unsing digester framwork
	 * @param input The data input file defining the Java Object
	 * @param rules The rules input URL defining the digester rules for loading this Java Object
	 * @return Return an instance of the a Java Object (defined in rule file)
	 * @throws SAXException Can be thrown while parsing files.
	 * @throws Exception Can be MalformedURLException or IOException for the input or rules files.
	 * @see DigesterFactory#load(URL, URL)
	 * @see DigesterFactory#load(File, File)
	 */
	public static Object load(File input, URL rules) throws SAXException, IOException {
		Digester digester = DigesterLoader.createDigester(rules);
		return digester.parse(input);
	}

	public static void main(String[] args) {
		if (args.length == 2) {
			try {
				//Root o = loadRoot(new File( "input.xml" ));
				//Object o = load(new File("input.xml"), new File("digester-input-rules.xml"));
				Object o = load(new File(args[0]), new File(args[1]));
				/*Display resulting beans*/
				System.out.println("=================================");
				System.out.println(o.toString());
				System.out.println("=================================");
			} catch( SAXException saxEx) {
				System.err.println("Error in XML parsing: "+saxEx.getMessage());
			} catch( Exception exc ) {
				exc.printStackTrace(System.err);
			}
		} else {
			System.out.println("Usage: java "+DigesterFactory.class.getName()+" [XML input file] [XML rule]");
		}
	}
}

Java , ,

Write and read to a samba shared directory using java (JCIFS)

11/09/2009
Commentaires fermés

This is a little example of a code that write to a file that is on a SMB folder.

Do not forget to add jcifs-1.2.25.jar to your classpath, see http://jcifs.samba.org.


import jcifs.smb.*;
public class SMBClient {
  public static void main(String[] args) {
    try{
      // jcifs.Config.setProperty( "jcifs.netbios.wins", "192.168.1.220" );
      //smb://[[[domain;]username[:password]@]server[:port]/[[share/[dir/]file]][?[param=value[param2=value2[...]]]
      String url="smb://domain;user_name:user_password@server_name/directory/test_file.txt";
      String content="hello !";
      SmbFileOutputStream out = new SmbFileOutputStream(url);
      out.write(content.getBytes());

      System.out.println("File written, now trying to re-read it:");
      SmbFileInputStream in = new SmbFileInputStream(url);
      byte[] b = new byte[10000];
      int n;
      while(( n = in.read( b )) > 0 ) {
        System.out.write( b, 0, n );
      }
    }catch(Exception e){
  System.out.println(e);
  }
 }
}

Java , ,

A Text Wrapper Class

18/05/2009
Commentaires fermés

This is a code snipplet which aim is to wrap text.

There’s two methods, one that wrap text simply, keeping existing wrapped lines into account, and the other that wrap words.

Lire la suite…

Java

JForm

28/01/2009
Commentaires fermés

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 * This is a swing class that handle Forms by managing lines.
 * In one line you can put a label (left), a component (auto resize - middle) and an other component (rigth)
 * @author Gabriel Dromard
 */
public class JForm extends JPanel {
    public static final long serialVersionUID = 364635478;
    private ArrayList leftComponents = new ArrayList();
    private ArrayList rightComponents = new ArrayList();
    private JPanel lastLine = null;
    private int hgap, vgap;

    private int rightWidth;
    private int leftWidth;

    /**
    * Initialization of the component
    * @param hgap the horizontal gap of the layout.
    * @param vgap the vertical gap of the layout.
    */
    public JForm(int hgap, int vgap) {
        super();
        this.hgap = hgap;
        this.vgap = vgap;
        this.setLayout(new BorderLayout(hgap, vgap));
        lastLine = this;
    }

    /**
    * Centralize creation of panels
    * @return A new instance of panel (with border layout and opaque false)
    */
    public JPanel buildPanel() {
        JPanel panel = new JPanel(new BorderLayout(hgap, vgap));
        panel.setOpaque(this.isOpaque());
        panel.setBackground(this.getBackground());
        return panel;
    }

    /**
    * Add a line to the form
    * @param label  The label (WEST)
    * @param middle A component (middle)
    * @param right  A component (EAST)
    */
    public void addLine(JLabel label, JComponent middle, JComponent right) {
        JPanel line = buildPanel();
        if(label != null) {
            leftWidth = addComponent(leftComponents, label, leftWidth);
            line.add(label, BorderLayout.WEST);
        }
        if(right != null) {
            rightWidth = addComponent(rightComponents, right, rightWidth);
            line.add(right, BorderLayout.EAST);
        }
        if(middle != null) {
            line.add(middle, BorderLayout.CENTER);
        }
        lastLine.add(line, BorderLayout.NORTH);
        JPanel nextLine = buildPanel();
        lastLine.add(nextLine, BorderLayout.CENTER);
        lastLine = nextLine;
    }

    /**
     * This methods is used to set width of left or rigth component. All the component on left must have the same width !
     * And it is the same for rigth ones.
     *
     * @param components The ArrayList of components.
     * @param component The component to add into the ArrayList.
     * @param maxSize The current max size of the components.
     * @return The new max size of the components
     */
    private int addComponent(ArrayList components, JComponent component, int maxSize) {
        int size = (int)component.getPreferredSize().getWidth();

        System.out.println("size="+size);
        System.out.println("maxSize="+maxSize);
        if (size > maxSize) {
            maxSize = size;
            adaptWidth(components, maxSize);
        } else {
            component.setPreferredSize(new Dimension(maxSize, (int)component.getPreferredSize().getHeight()));
        }

        components.add(component);

        return maxSize;
    }

    /**
     * This methods is used to adapt the prefered size of components of an array.
     *
     * @param components The components.
     * @param size The new prefered size.
     */
    private void adaptWidth(ArrayList components, int size) {
        JComponent cmp;
        // Set preferred size for left components
        for (int i=0; i<components.size(); i++) {
            cmp = ((JComponent)components.get(i));
            cmp.setPreferredSize(new Dimension(size, (int)cmp.getPreferredSize().getHeight()));
        }
    }

    /**
     * This is a way of testing this class.
     *
     * @param args Not used.
     */
    public static void main(String[] args) {
        JForm form = new JForm(5, 5);
        form.setBackground(Color.WHITE);
        form.setOpaque(true);

        for (int i = 0; i < 10; ++i) {
            if (i == 1) {
                form.addLine(new JLabel("JLabel n°" + i), new JTextField(), null);
            } else if (i == 2) {
                form.addLine(null, new JTextField(), new JButton("JButton n°" + i));
            } else if (i == 3) {
                form.addLine(null, new JTextField(), null);
            } else if (i == 4) {
                form.addLine(new JLabel("JLabel n°" + i), null, null);
            } else if (i == 5) {
                form.addLine(null, null, new JButton("JButton n°" + i));
            } else {
                form.addLine(new JLabel("JLabel n°" + i), new JTextField(), new JButton("JButton n°" + i));
            }
        }
        SwingHelper.openInFrame(form);
    }
}

Java

JTaskPane

28/01/2009
Commentaires fermés

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Paint;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;

/**
 * This is a J2LProd's JTaskPane like component <a href="http://www.L2FProd.com" onclick="javascript:pageTracker._trackPageview ('/outbound/www.L2FProd.com');">see L2FProd</a>.
 * Building task oriented applications
 * Lot of recent applications bring contextual item lists from which you can pick tasks related to
 * the current selection or context.
 * The JTaskPane <!--and JTaskPaneGroup--> deliver this feature to java applications.
 *
 * @author Gabriel Dromard
 */
public class JTaskPane extends JPanel {
    protected static int BUTTON_WIDTH = 18;
    protected Color borderColor = Color.GRAY;
    protected Color buttonBorderColor = Color.DARK_GRAY.brighter();
    protected Color titleGradientBeginColor = Color.WHITE;
    protected Color titleGradientEndColor = Color.LIGHT_GRAY;
    protected JPanel content;
    protected MyJLabel label;

    public JTaskPane(final String title, final JComponent component) {
        super(new BorderLayout());
        this.setOpaque(false);
        // Title
        label = new MyJLabel(title);
        label.setBorder(BorderFactory.createLineBorder(borderColor));
        add(label, BorderLayout.NORTH);
        // Content Panel
        content = new JPanel(new BorderLayout()) {
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.setColor(borderColor);
                g.drawRect(0, -1, getWidth()-1, getHeight());
            }
        };
        content.setBorder(new LineBorder(borderColor) {
            public Insets getBorderInsets(Component c) {
                Insets insets = super.getBorderInsets(c);
                insets.top = insets.top-1;
                return insets;
            }
        });
        content.add(component, BorderLayout.CENTER);
        add(content, BorderLayout.CENTER);
        // Hide/show content
        label.setButtonActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                content.setVisible(!content.isVisible());
            }
        });
    }

    public void paintComponent(final Graphics g) {
        // Set the background color of the content panel
        content.setBackground(JTaskPane.this.getBackground());
        super.paintComponent(g);
    }

    /**
    * Set the JTaskPane opened or closed
    */
    public void setOpened(boolean opened)
    {
        label.button.up = opened;
        content.setVisible(opened);
    }

    /**
    * Is the JTaskPane opened ?
    * @return True if it is opened
    */
    public boolean isOpened()
    {
        return content.isVisible();
    }

    /**
    * @return the titleGradientBeginColor
    */
    public Color getTitleGradientBeginColor() {
        return titleGradientBeginColor;
    }

    /**
    * @param titleGradientBeginColor the titleGradientBeginColor to set
    */
    public void setTitleGradientBeginColor(Color titleGradientBeginColor) {
        this.titleGradientBeginColor = titleGradientBeginColor;
    }

    /**
    * @return the titleGradientEndColor
    */
    public Color getTitleGradientEndColor() {
        return titleGradientEndColor;
    }

    /**
    * @param titleGradientEndColor the titleGradientEndColor to set
    */
    public void setTitleGradientEndColor(Color titleGradientEndColor) {
        this.titleGradientEndColor = titleGradientEndColor;
    }

    /**
    * Title of JTaskPane
    */
    class MyJLabel extends JLabel {
        protected MyJButton button;
        protected ActionListener currentActionListener;

        public MyJLabel(final String title) {
            super("  "+title);
            setPreferredSize(new Dimension(getWidth(), 30));
            button = new MyJButton();
            int yPos = (getHeight() - BUTTON_WIDTH)/2;
            int xPos = getWidth() - yPos - BUTTON_WIDTH;
            button.setBounds(xPos, yPos, BUTTON_WIDTH, BUTTON_WIDTH);
            add(button);
        }

        public void setButtonActionListener(final ActionListener action) {
            // Remove action listeners
            button.removeActionListener(currentActionListener);
            button.addActionListener(action);
            currentActionListener = action;
        }

        public void paintComponent(final Graphics g) {
            // Re set position of button
            int yPos = (getHeight() - BUTTON_WIDTH)/2;
            int xPos = getWidth() - yPos - BUTTON_WIDTH;
            button.setBounds(xPos, yPos, BUTTON_WIDTH, BUTTON_WIDTH);

            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING , RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
            Paint oldPainter = g2.getPaint();
            g2.setPaint(new GradientPaint(0, 0, titleGradientBeginColor, (float)getSize().getWidth(), (float)getSize().getHeight(), titleGradientEndColor));
            //g2.fill(new RoundRectangle2D.Double(0, 0, (double)getWidth(), (double)getHeight(), 12, 12));
            g2.fill(new Rectangle2D.Double(0, 0, getWidth(), getHeight()));
            g2.setPaint(oldPainter);
            super.paintComponent(g);
        }
    }

    /**
    * Button on left of JTaskPane title
    */
    class MyJButton extends JButton {
        protected boolean up = true;

        public MyJButton() {
            super();
            setOpaque(false);
            setBorderPainted(false);
            setFocusPainted(false);
            setContentAreaFilled(false);
            setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    up = !up;
                }
            });
        }

        public void paintComponent(final Graphics g) {
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
            Paint oldPainter = g2.getPaint();
            g2.setPaint(new GradientPaint(0, 0, titleGradientEndColor.brighter(), getWidth()/2, getHeight()/2, titleGradientEndColor, true));
            g2.fillOval(0, 0, getWidth()-1, getHeight()-1);
            g2.setColor(buttonBorderColor);
            g2.drawOval(0, 0, getWidth()-1, getHeight()-1);
            g2.setColor(Color.DARK_GRAY);
            if(up) paintUpArrows(g2);
            else paintDownArrows(g2);
            g2.setPaint(oldPainter);
        }

        public void paintUpArrows(Graphics2D g2) {
            g2.translate(0, -1);
            g2.drawLine(5, getHeight()/2, getWidth()/2, 5);
            g2.drawLine(6, getHeight()/2, getWidth()/2, 6);
            g2.drawLine(getWidth()/2, 5, getWidth() - 5, getHeight()/2);
            g2.drawLine(getWidth()/2, 6, getWidth() - 6, getHeight()/2);
            g2.translate(0, +1);

            g2.translate(0, getHeight()/4-1);
            g2.drawLine(5, getHeight()/2, getWidth()/2, 5);
            g2.drawLine(6, getHeight()/2, getWidth()/2, 6);
            g2.drawLine(getWidth()/2, 5, getWidth() - 5, getHeight()/2);
            g2.drawLine(getWidth()/2, 6, getWidth() - 6, getHeight()/2);
            g2.translate(0, -getHeight()/4+1);
        }

        public void paintDownArrows(Graphics2D g2) {
            g2.drawLine(5, getHeight()/2, getWidth()/2, getHeight() - 5);
            g2.drawLine(6, getHeight()/2, getWidth()/2, getHeight() - 6);
            g2.drawLine(getWidth()/2, getHeight() - 5, getWidth() - 5, getHeight()/2);
            g2.drawLine(getWidth()/2, getHeight() - 6, getWidth() - 6, getHeight()/2);

            g2.translate(0, -getHeight()/4);
            g2.drawLine(5, getHeight()/2, getWidth()/2, getHeight() - 5);
            g2.drawLine(6, getHeight()/2, getWidth()/2, getHeight() - 6);
            g2.drawLine(getWidth()/2, getHeight() - 5, getWidth() - 5, getHeight()/2);
            g2.drawLine(getWidth()/2, getHeight() - 6, getWidth() - 6, getHeight()/2);
            g2.translate(0, +getHeight()/4);
        }
    }

    /**
    * Demo main methods that display JTaskPane, JForm, ShadowBorder
    */
    public static void main(String[] args) {
        //
        JForm root = new JForm(10, 10);
        root.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        //root.setBackground(Color.WHITE);
        // Initialize JForm
        JForm form1 = new JForm(5, 5);
        form1.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        form1.setBackground(Color.WHITE);

        //form.setOpaque(false);
        for(int i=0; i<10; ++i) {
           JTextField txt = new JTextField();
           txt.setPreferredSize(new Dimension(150, (int)txt.getPreferredSize().getHeight()));
            if(i == 3) form1.addLine(new JLabel("label plus long"+i), txt, new JButton("Select"+i));
            else form1.addLine(new JLabel("label"+i), txt, new JButton("Select"+i));
        }
        JForm form2 = new JForm(5, 5);
        form2.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        form2.setBackground(Color.WHITE);
        for(int i=0; i<5; ++i) {
           JTextField txt = new JTextField();
           txt.setPreferredSize(new Dimension(150, (int)txt.getPreferredSize().getHeight()));
            if(i >= 3) form2.addLine(new JLabel("label plus long"+i), txt, null);
            else form2.addLine(new JLabel("label"+i), txt, new JButton("Select"+i));
        }
        // Add form in panel
        JPanel myPanel1 = new JTaskPane("JTaskPane containing a JForm", form1);
        ShadowBorder shadowBorder = new ShadowBorder(Color.GRAY);
        myPanel1.setBorder(shadowBorder);

        // Add form in panel
        JTaskPane myPanel2 = new JTaskPane("Same with different options", form2);
        myPanel2.titleGradientBeginColor = Color.LIGHT_GRAY;
        myPanel2.titleGradientEndColor = Color.WHITE;
        shadowBorder = new ShadowBorder(Color.GRAY);
        shadowBorder.setType(ShadowBorder.TOP_LEFT);
        myPanel2.setBorder(shadowBorder);
        //myPanel.setBackground(Color.WHITE);
        root.addLine(null, myPanel1, null);
        root.addLine(null, myPanel2, null);
        JMemoryMonitor mem = new JMemoryMonitor();
        mem.setPreferredSize(new Dimension(200, 200));
        root.addLine(null, mem, null);
        // Show frame
        JFrame frame = SwingHelper.openInFrame(root);
        frame.setSize(frame.getWidth()+300, frame.getHeight());
        myPanel2.setOpened(false);
        SwingUtilities.updateComponentTreeUI(frame);
    }
} 

Java

JMemoryMonitor

28/01/2009
Commentaires fermés

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.util.Date;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;

/**
 * Tracks Memory allocated & used, displayed in graph form.
 */
public class JMemoryMonitor extends JPanel {

    private static final long serialVersionUID = -347102535481575324L;
    private static JCheckBox dateStampCB = new JCheckBox("Output Date Stamp");
    private Surface surf;
    private JPanel controls;
    private boolean doControls;
    private JTextField tf;

    public JMemoryMonitor() {
        setLayout(new BorderLayout());
        setBorder(new TitledBorder(new EtchedBorder(), "Memory Monitor"));
        add(surf = new Surface());
        controls = new JPanel();
        controls.setPreferredSize(new Dimension(135,80));
        Font font = new Font("serif", Font.PLAIN, 10);
        JLabel label = new JLabel("Sample Rate");
        label.setFont(font);
        label.setForeground(Color.black);
        controls.add(label);
        tf = new JTextField("1000");
        tf.setPreferredSize(new Dimension(45,20));
        controls.add(tf);
        controls.add(label = new JLabel("ms"));
        label.setFont(font);
        label.setForeground(Color.black);
        controls.add(dateStampCB);
        dateStampCB.setFont(font);
        addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
               removeAll();
               doControls = !doControls;
               if (doControls) {
                   surf.stop();
                   add(controls);
               } else {
                   try {
                       surf.sleepAmount = Long.parseLong(tf.getText().trim());
                   } catch (Exception ex) {
                       ex.printStackTrace();
                   }
                   surf.start();
                   add(surf);
               }
               validate();
               repaint();
            }
        });
    }

    private class Surface extends JPanel implements Runnable {

        private static final long serialVersionUID = -4298072680026629003L;
        private Thread thread;
        private long sleepAmount = 1000;
        private int w, h;
        private BufferedImage bimg;
        private Graphics2D big;
        private Font font = new Font("Times New Roman", Font.PLAIN, 11);

        private int columnInc;
        private int pts[];
        private int ptNum;
        private int ascent, descent;
        //private float freeMemory, totalMemory;
        //private Rectangle graphOutlineRect = new Rectangle();
        private Rectangle2D mfRect = new Rectangle2D.Float();
        private Rectangle2D muRect = new Rectangle2D.Float();
        private Line2D graphLine = new Line2D.Float();
        private Color graphColor = new Color(46, 139, 87);
        private Color mfColor = new Color(0, 100, 0);
        private String usedStr;

        public Surface() {
            setBackground(Color.black);
            addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    if (thread == null) start(); else stop();
                }
            });
        }

        public Dimension getMinimumSize() {
            return getPreferredSize();
        }

        public Dimension getMaximumSize() {
            return getPreferredSize();
        }

        public Dimension getPreferredSize() {
            return new Dimension(135,80);
        }

        public void paint(Graphics g) {

            if (big == null) {
                return;
            }

            big.setBackground(getBackground());
            big.clearRect(0,0,w,h);

            float freeMemory  = Runtime.getRuntime().freeMemory();
            float totalMemory = Runtime.getRuntime().totalMemory();
            //float totalMemory = Runtime.getRuntime().maxMemory();

            // .. Draw allocated and used strings ..
            big.setColor(Color.green);
            big.drawString(String.valueOf((int) totalMemory/1024) + "Ko allocated",  4.0f, ascent+0.5f);
            usedStr = String.valueOf(((int) (totalMemory - freeMemory))/1024) + "Ko used";
            big.drawString(usedStr, 4, h-descent);

            // Calculate remaining size
            float ssH = ascent + descent;
            float remainingHeight = (h - (ssH*2) - 0.5f);
            int nbBlocks = 20;
            float blockHeight = remainingHeight/nbBlocks;
            float blockWidth = 20.0f;
            //float remainingWidth = (w - blockWidth - 10);

            // .. Memory Free ..
            big.setColor(mfColor);
            int MemUsage = (int) ((freeMemory / totalMemory) * nbBlocks);
            int i = 0;
            for ( ; i < MemUsage ; i++) {
                mfRect.setRect(5,  ssH+i*blockHeight, blockWidth, blockHeight-1);
                big.fill(mfRect);
            }

            // .. Memory Used ..
            big.setColor(Color.green);
            for ( ; i < nbBlocks; i++)  {
                muRect.setRect(5, ssH+i*blockHeight, blockWidth, blockHeight-1);
                big.fill(muRect);
            }

            // .. Draw History Lines ..
            big.setColor(graphColor);
            int graphX = 30;
            int graphY = (int) ssH;
            int graphW = w - graphX - 5;
            int graphH = (int) remainingHeight;
            for (i = 0 ; i < nbBlocks; i++)  {
                muRect.setRect(graphX, graphY+i*blockHeight-0.5f, graphW, blockHeight);
                big.draw(muRect);
            }

            // .. Draw History columns ..
            int graphColumn = graphW/15;

            if (columnInc == 0) {
                columnInc = graphColumn;
            }
            for (int j = graphX+columnInc; j < graphW+graphX; j+=graphColumn) {
                graphLine.setLine(j,graphY,j,graphY+graphH);
                big.draw(graphLine);
            }

            --columnInc;

            if (pts == null) {
                pts = new int[graphW];
                ptNum = 0;
            } else if (pts.length != graphW) {
                int tmp[] = null;
                if (ptNum < graphW) {
                    tmp = new int[ptNum];
                    System.arraycopy(pts, 0, tmp, 0, tmp.length);
                } else {
                    tmp = new int[graphW];
                    System.arraycopy(pts, pts.length-tmp.length, tmp, 0, tmp.length);
                    ptNum = tmp.length - 2;
                }
                pts = new int[graphW];
                System.arraycopy(tmp, 0, pts, 0, tmp.length);
            } else {
                big.setColor(Color.yellow);
                pts[ptNum] = (int)(graphY+graphH*(freeMemory/totalMemory));
                for (int j=graphX+graphW-ptNum, k=0;k < ptNum; k++, j++) {
                    if (k != 0) {
                        if (pts[k] != pts[k-1]) {
                            big.drawLine(j-1, pts[k-1], j, pts[k]);
                        } else {
                            big.fillRect(j, pts[k], 1, 1);
                        }
                    }
                }
                if (ptNum+2 == pts.length) {
                    // throw out oldest point
                    for (int j = 1;j < ptNum; j++) {
                        pts[j-1] = pts[j];
                    }
                    --ptNum;
                } else {
                    ptNum++;
                }
            }
            g.drawImage(bimg, 0, 0, this);
        }

        public void start() {
            thread = new Thread(this);
            thread.setPriority(Thread.MIN_PRIORITY);
            thread.setName("MemoryMonitor");
            thread.start();
        }

        public synchronized void stop() {
            thread = null;
            notify();
        }

        public void run() {

            Thread me = Thread.currentThread();

            while (thread == me && !isShowing() || getSize().width == 0) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) { return; }
            }

            while (thread == me && isShowing()) {
                Dimension d = getSize();
                if (d.width != w || d.height != h) {
                    w = d.width;
                    h = d.height;
                    bimg = (BufferedImage) createImage(w, h);
                    big = bimg.createGraphics();
                    big.setFont(font);
                    FontMetrics fm = big.getFontMetrics(font);
                    ascent = fm.getAscent();
                    descent = fm.getDescent();
                }
                repaint();
                try {
                    Thread.sleep(sleepAmount);
                } catch (InterruptedException e) { break; }
                if (JMemoryMonitor.dateStampCB.isSelected()) {
                     System.out.println(new Date().toString() + " " + usedStr);
                }
            }
            thread = null;
        }
    }

    public static void main(String s[]) {
        final JMemoryMonitor demo = new JMemoryMonitor();
        WindowListener l = new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);}
            public void windowDeiconified(WindowEvent e) { demo.surf.start(); }
            public void windowIconified(WindowEvent e) { demo.surf.stop(); }
        };
        JFrame f = new JFrame("Memory Monitor");
        f.addWindowListener(l);
        f.getContentPane().add("Center", demo);
        f.pack();
        f.setSize(new Dimension(200,200));
        f.setVisible(true);
        demo.surf.start();
    }
} 

Java

Shadow Border

28/01/2009
Commentaires fermés

/*
 * Created on 17 oct. 06
 * By Gabriel DROMARD
 */

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.RenderingHints;

import javax.swing.JPanel;
import javax.swing.border.AbstractBorder;

/**
 * A class which implements a shadow border.
 *
 * <p>Code Example: </p>
 * <pre>
 *        JPanel root = new JPanel();
 *        // Generate 4 example for each TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT and BOTTOM_RIGHT configurations
 *        for(int i=0; i<4; ++i) {
 *            JPanel test = new JPanel();
 *            test.setPreferredSize(new Dimension(100, 100));
 *            test.setBackground(Color.WHITE);
 *            test.setOpaque(false);
 *            test.setBorder(new ShadowBorder(Color.GRAY, Color.GRAY, 10, i));
 *            root.add(test);
 *        }
 *        //SwingHelper.openInFrame(root);
 *        JFrame frame = new JFrame();
 *        frame.getContentPane().setLayout(new BorderLayout());
 *        frame.getContentPane().add(root, BorderLayout.CENTER);
 *        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
 *        frame.pack();
 *        frame.setVisible(true);
 * </pre>
 */
public class ShadowBorder extends AbstractBorder {
    private int shadowWidth = 10;
    private int inset = 5;
    protected Color lineBorderColor = null;
    protected Color shadowColor = null;
    protected int type = 2;
    public static final int TOP_LEFT = 0;
    public static final int TOP_RIGHT = 1;
    public static final int BOTTOM_LEFT = 2;
    public static final int BOTTOM_RIGHT = 3;

    /**
     * Auto-generated main method to display this
     * JPanel inside a new JFrame.
     */
    public static void main(String[] args) {
        JPanel root = new JPanel();
        for(int i=0; i<4; ++i) {
            JPanel test = new JPanel();
            test.setPreferredSize(new Dimension(100, 100));
            test.setBackground(Color.WHITE);
            test.setOpaque(false);
            test.setBorder(new ShadowBorder(Color.GRAY, Color.GRAY, 10, i));
            root.add(test);
        }
        SwingHelper.openInFrame(root);
    }

    /**
     * Creates a shadow border with the specified shadow width and whose
     * colors will be derived from the background color of the
     * component passed into the paintBorder method.
     * @param shadowWidth the length of shadow
     * @param
     * @param
     * @param
     */
    public ShadowBorder(Color shadowColor, Color lineBorderColor, int shadowWidth, int type) {
        super();
        this.shadowWidth = shadowWidth;
        this.shadowColor = shadowColor;
        this.lineBorderColor = lineBorderColor;
        this.type = type;
    }

    /**
     * Returns the insets of the border.
     * @param c the component for which this border insets value applies
     */
    public Insets getBorderInsets(Component c) {
        int hPosition = shadowWidth;
        int vPosition = shadowWidth;

        if(type == TOP_LEFT) {
            hPosition = 0;
            vPosition = 0;
        } else if(type == TOP_RIGHT) {
            hPosition = shadowWidth;
            vPosition = 0;
        } else if(type == BOTTOM_LEFT) {
            hPosition = 0;
            vPosition = shadowWidth;
        } else if(type == BOTTOM_RIGHT) {
            hPosition = shadowWidth;
            vPosition = shadowWidth;
        }
        return new Insets((shadowWidth - hPosition)+inset, (shadowWidth - vPosition)+inset, hPosition+inset, vPosition+inset);
    }

    /**
     * Reinitialize the insets parameter with this Border's current Insets.
     * @param c the component for which this border insets value applies
     * @param insets the object to be reinitialized
     */
    public Insets getBorderInsets(Component c, Insets insets) {
        insets.left = insets.top = insets.right = insets.bottom = shadowWidth+2;
        return insets;
    }

    /**
     * Returns the shadow color of the border
     * when rendered on the specified component.  If no shadow
     * color was specified at instantiation, the shadow color
     * is derived from the specified component's background color.
     * @param c the component for which the shadow may be derived
     */
    public Color getShadowColor(Component c) {
        Color shadow = getShadowColor();
        if(shadow == null) shadow = c.getBackground().darker().darker();
        return shadow;
    }

    /**
     * Returns the shadow color of the border.
     * Will return null if no shadow color was specified at instantiation.
     */
    public Color getShadowColor() {
        return shadowColor;
    }

    /**
     * Returns whether or not the border is opaque.
     */
    public boolean isBorderOpaque() {
        return true;
    }

    /**
     * Paints the border for the specified component with the specified position and size.
     * @param c the component for which this border is being painted
     * @param g the paint graphics
     * @param x the x position of the painted border
     * @param y the y position of the painted border
     * @param width the width of the painted border
     * @param height the height of the painted border
     */
    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
        int hPosition = shadowWidth;
        int vPosition = shadowWidth;

        if(type == TOP_LEFT) {
            hPosition = 0;
            vPosition = 0;
        } else if(type == TOP_RIGHT) {
            hPosition = shadowWidth;
            vPosition = 0;
        } else if(type == BOTTOM_LEFT) {
            hPosition = 0;
            vPosition = shadowWidth;
        } else if(type == BOTTOM_RIGHT) {
            hPosition = shadowWidth;
            vPosition = shadowWidth;
        }
        width = width - 1;
        height = height - 1;
        Graphics2D gg = (Graphics2D) g;
        // backup old color to be able to restore it at the end of paint
        Color oldColor = gg.getColor();
        // Translate position
        gg.translate(x, y);
        // paint shadow
        paintShadow(c, gg, getShadowColor(c), hPosition, vPosition, width-shadowWidth, height-shadowWidth, shadowWidth);
        // Fill with background color the panel
        gg.setColor(c.getBackground());
        gg.fillRect(shadowWidth - hPosition, shadowWidth - vPosition, width-shadowWidth, height-shadowWidth);
        // Draw line border
        if (lineBorderColor != null) {
           gg.setColor(lineBorderColor);
           gg.drawRect(shadowWidth - hPosition, shadowWidth - vPosition, width-shadowWidth, height-shadowWidth);
        }
        // Reset position
        gg.translate(-x, -y);
        // Re put oldColor
        gg.setColor(oldColor);
    }

    /**
     *
     * @param c           the component for which this border is being painted
     * @param gg          the paint graphics
     * @param shadowColor The color of the shadow
     * @param x           the x position of the painted border
     * @param y           the y position of the painted border
     * @param width       the width of the painted border
     * @param height      the height of the painted border
     * @param shadowWidth The shadow width
     */
    public static void paintShadow(Component c, Graphics2D gg, Color shadowColor, int x, int y, int width, int height, int shadowWidth) {
        // Set anti aliasing
        gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING , RenderingHints.VALUE_ANTIALIAS_ON);
        // Draw shadow
        AlphaComposite ac = null;
        gg.setColor(shadowColor);
        // Initial shadow width:
        int sw = width - 2*shadowWidth;
        // Initial shadow height:
        int sh = height - 2*shadowWidth;
        // Draw shadow
        for(int i=0; i<shadowWidth; ++i) {
            ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f/(i+1));
            gg.setComposite(ac);
            gg.fillRoundRect(x+shadowWidth-i, y+shadowWidth-i, sw + 2*i, sh + 2*i, i*2, i*2);
        }
        // Reset transparency
        ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1);
        gg.setComposite(ac);
    }
}

Java