code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * SortedStrings. * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.util.ini; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; /** * An object that represents an array of alpabetized Strings. Implemented * with an String array that grows as appropriate. */ public class SortedStrings extends Alphabetizer implements Cloneable { public static final int DEFAULT_SIZE = 32; private String[] strings; private int string_count; private double growth_rate = 2.0; /** * Constructor creates a new SortedStrings object of default * size. */ public SortedStrings() { clear(); } /** * Constructor creates a new SortedStrings object of size passed. */ public SortedStrings(int initial_size) { clear(initial_size); } /** * Contructor creates a new SortedStrings object using a DataInput * object. The first int in the DataInput object is assumed to be * the size wanted for the SortedStrings object. */ public SortedStrings(DataInput in) throws IOException { int count = string_count = in.readInt(); String[] arr = strings = new String[count]; for (int i = 0; i < count; i++) arr[i] = in.readUTF(); } /** * Contructor creates a new SortedStrings object, initializing it * with the String[] passed. */ public SortedStrings(String[] array) { this(array.length); int new_size = array.length; for (int i = 0; i < new_size; i++) add(array[i]); } /** * Clones the SortedStrings object. */ public Object clone() { try { SortedStrings clone = (SortedStrings) super.clone(); clone.strings = (String[]) strings.clone(); return clone; } catch (CloneNotSupportedException e) { return null; } } /** * Writes a the SortedStrings object to the DataOutput object. */ public void emit(DataOutput out) throws IOException { int count = string_count; String[] arr = strings; out.writeInt(count); for (int i = 0; i < count; i++) out.writeUTF(arr[i]); } /** * Merge two sorted lists of integers. The time complexity of * the merge is O(n). */ public SortedStrings merge(SortedStrings that) { int count1 = this.string_count; int count2 = that.string_count; String[] ints1 = this.strings; String[] ints2 = that.strings; String num1, num2; int i1 = 0, i2 = 0; SortedStrings res = new SortedStrings(count1 + count2); while (i1 < count1 && i2 < count2) { num1 = ints1[i1]; num2 = ints2[i2]; if (compare(num1, num2) < 0) { res.add(num1); i1++; } else if (compare(num2, num1) < 0) { res.add(num2); i2++; } else { res.add(num1); i1++; i2++; } } if (i1 < count1) { for (; i1 < count1; i1++) res.add(ints1[i1]); } else for (; i2 < count2; i2++) res.add(ints2[i2]); return res; } /** * Returns a SortedStrings object that has the Strings * from this object that are not in the one passed. */ public SortedStrings diff(SortedStrings that) { int count1 = this.string_count; int count2 = that.string_count; String[] ints1 = this.strings; String[] ints2 = that.strings; String num1, num2; int i1 = 0, i2 = 0; SortedStrings res = new SortedStrings(count1); while (i1 < count1 && i2 < count2) { num1 = ints1[i1]; num2 = ints2[i2]; if (compare(num1, num2) < 0) { res.add(num1); i1++; } else if (compare(num2, num1) < 0) i2++; else { i1++; i2++; } } if (i1 < count1) { for (; i1 < count1; i1++) res.add(ints1[i1]); } return res; } /** * Clears the Strings from the object and creates a new one * of the default size. */ public void clear() { clear(DEFAULT_SIZE); } /** * Clears the Strings from the object and creates a new one * of the size passed. */ public void clear(int initial_size) { strings = new String[initial_size]; string_count = 0; } /** * Adds the String passed to the array in its proper place -- sorted. */ public void add(String num) { if (string_count == 0 || greaterThan(num, strings[string_count - 1])) { if (string_count == strings.length) strings = (String[]) Array.grow(strings, growth_rate); strings[string_count] = num; string_count++; } else insert(search(num), num); } /** * Inserts the String passed to the array at the index passed. */ private void insert(int index, String num) { if (strings[index] == num) return; else { if (string_count == strings.length) strings = (String[]) Array.grow(strings, growth_rate); System.arraycopy(strings, index, strings, index + 1, string_count - index); strings[index] = num; string_count++; } } /** * Removes the String passed from the array. */ public void remove(String num) { int index = search(num); if (index < string_count && equalTo(strings[index], num)) removeIndex(index); } /** * Removes the String from the beginning of the array to the * index passed. */ public void removeIndex(int index) { if (index < string_count) { System.arraycopy(strings, index + 1, strings, index, string_count - index - 1); string_count--; } } /** * Returns true flag if the String passed is in the array. */ public boolean contains(String num) { int index = search(num); return index < string_count && equalTo(strings[search(num)], num); } /** * Returns the number of Strings in the array. */ public int stringCount() { return string_count; } /** * Returns String index of the int passed. */ public int indexOf(String num) { int index = search(num); return index < string_count && equalTo(strings[index], num) ? index : -1; } /** * Returns the String value at the index passed. */ public String stringAt(int index) { return strings[index]; } /** * Returns the index where the String value passed is located * or where it should be sorted to if it is not present. */ protected int search(String num) { String[] strings = this.strings; int lb = 0, ub = string_count, index; String index_key; while (true) { if (lb >= ub - 1) { if (lb < string_count && !greaterThan(num, strings[lb])) return lb; else return lb + 1; } index = (lb + ub) / 2; index_key = strings[index]; if (greaterThan(num, index_key)) lb = index + 1; else if (lessThan(num, index_key)) ub = index; else return index; } } /** * Returns an String[] that contains the value in the SortedStrings * object. */ public String[] toStringArray() { String[] array = new String[string_count]; System.arraycopy(strings, 0, array, 0, string_count); return array; } /** * Returns a sorted String[] from the String[] passed. */ public static String[] sort(String[] input) { SortedStrings new_strings = new SortedStrings(input); return new_strings.toStringArray(); } }
Java
/* * Array. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.util.ini; /** * This class represents an array of objects. * * @author Jeremy Cloud * @version 1.0.0 */ public class Array { public static Object[] copy(Object[] sors, Object[] dest) { System.arraycopy(sors, 0, dest, 0, sors.length); return dest; } public static String[] doubleArray(String[] sors) { System.out.print("** doubling string array... "); int new_size = (sors.length <= 8 ? 16 : sors.length << 1); String[] dest = new String[new_size]; System.arraycopy(sors, 0, dest, 0, sors.length); System.out.println("done **."); return dest; } public static int[] doubleArray(int[] sors) { int new_size = (sors.length < 8 ? 16 : sors.length << 1); int[] dest = new int[new_size]; System.arraycopy(sors, 0, dest, 0, sors.length); return dest; } public static int[] grow(int[] sors, double growth_rate) { int new_size = Math.max((int) (sors.length * growth_rate), sors.length + 1); int[] dest = new int[new_size]; System.arraycopy(sors, 0, dest, 0, sors.length); return dest; } public static boolean[] grow(boolean[] sors, double growth_rate) { int new_size = Math.max((int) (sors.length * growth_rate), sors.length + 1); boolean[] dest = new boolean[new_size]; System.arraycopy(sors, 0, dest, 0, sors.length); return dest; } public static Object[] grow(Object[] sors, double growth_rate) { int new_size = Math.max((int) (sors.length * growth_rate), sors.length + 1); Object[] dest = new Object[new_size]; System.arraycopy(sors, 0, dest, 0, sors.length); return dest; } public static String[] grow(String[] sors, double growth_rate) { int new_size = Math.max((int) (sors.length * growth_rate), sors.length + 1); String[] dest = new String[new_size]; System.arraycopy(sors, 0, dest, 0, sors.length); return dest; } /** * @param start - inclusive * @param end - exclusive */ public static void shiftUp(Object[] array, int start, int end) { int count = end - start; if (count > 0) System.arraycopy(array, start, array, start + 1, count); } /** * @param start - inclusive * @param end - exclusive */ public static void shiftDown(Object[] array, int start, int end) { int count = end - start; if (count > 0) System.arraycopy(array, start, array, start - 1, count); } public static void shift(Object[] array, int start, int amount) { int count = array.length - start - (amount > 0 ? amount : 0); System.arraycopy(array, start, array, start + amount, count); } }
Java
/* * BMPLoader. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.util; import java.awt.Image; import java.awt.Toolkit; import java.awt.image.ColorModel; import java.awt.image.IndexColorModel; import java.awt.image.MemoryImageSource; import java.io.IOException; import java.io.InputStream; /** * A decoder for Windows bitmap (.BMP) files. * Compression not supported. */ public class BMPLoader { private InputStream is; private int curPos = 0; private int bitmapOffset; // starting position of image data private int width; // image width in pixels private int height; // image height in pixels private short bitsPerPixel; // 1, 4, 8, or 24 (no color map) private int compression; // 0 (none), 1 (8-bit RLE), or 2 (4-bit RLE) private int actualSizeOfBitmap; private int scanLineSize; private int actualColorsUsed; private byte r[], g[], b[]; // color palette private int noOfEntries; private byte[] byteData; // Unpacked data private int[] intData; // Unpacked data public BMPLoader() { } public Image getBMPImage(InputStream stream) throws Exception { read(stream); return Toolkit.getDefaultToolkit().createImage(getImageSource()); } protected int readInt() throws IOException { int b1 = is.read(); int b2 = is.read(); int b3 = is.read(); int b4 = is.read(); curPos += 4; return ((b4 << 24) + (b3 << 16) + (b2 << 8) + (b1 << 0)); } protected short readShort() throws IOException { int b1 = is.read(); int b2 = is.read(); curPos += 4; return (short) ((b2 << 8) + b1); } protected void getFileHeader() throws IOException, Exception { // Actual contents (14 bytes): short fileType = 0x4d42;// always "BM" int fileSize; // size of file in bytes short reserved1 = 0; // always 0 short reserved2 = 0; // always 0 fileType = readShort(); if (fileType != 0x4d42) throw new Exception("Not a BMP file"); // wrong file type fileSize = readInt(); reserved1 = readShort(); reserved2 = readShort(); bitmapOffset = readInt(); } protected void getBitmapHeader() throws IOException { // Actual contents (40 bytes): int size; // size of this header in bytes short planes; // no. of color planes: always 1 int sizeOfBitmap; // size of bitmap in bytes (may be 0: if so, calculate) int horzResolution; // horizontal resolution, pixels/meter (may be 0) int vertResolution; // vertical resolution, pixels/meter (may be 0) int colorsUsed; // no. of colors in palette (if 0, calculate) int colorsImportant; // no. of important colors (appear first in palette) (0 means all are important) boolean topDown; int noOfPixels; size = readInt(); width = readInt(); height = readInt(); planes = readShort(); bitsPerPixel = readShort(); compression = readInt(); sizeOfBitmap = readInt(); horzResolution = readInt(); vertResolution = readInt(); colorsUsed = readInt(); colorsImportant = readInt(); topDown = (height < 0); noOfPixels = width * height; // Scan line is padded with zeroes to be a multiple of four bytes scanLineSize = ((width * bitsPerPixel + 31) / 32) * 4; if (sizeOfBitmap != 0) actualSizeOfBitmap = sizeOfBitmap; else // a value of 0 doesn't mean zero - it means we have to calculate it actualSizeOfBitmap = scanLineSize * height; if (colorsUsed != 0) actualColorsUsed = colorsUsed; else // a value of 0 means we determine this based on the bits per pixel if (bitsPerPixel < 16) actualColorsUsed = 1 << bitsPerPixel; else actualColorsUsed = 0; // no palette } protected void getPalette() throws IOException { noOfEntries = actualColorsUsed; //IJ.write("noOfEntries: " + noOfEntries); if (noOfEntries > 0) { r = new byte[noOfEntries]; g = new byte[noOfEntries]; b = new byte[noOfEntries]; int reserved; for (int i = 0; i < noOfEntries; i++) { b[i] = (byte) is.read(); g[i] = (byte) is.read(); r[i] = (byte) is.read(); reserved = is.read(); curPos += 4; } } } protected void unpack(byte[] rawData, int rawOffset, int[] intData, int intOffset, int w) { int j = intOffset; int k = rawOffset; int mask = 0xff; for (int i = 0; i < w; i++) { int b0 = (((int) (rawData[k++])) & mask); int b1 = (((int) (rawData[k++])) & mask) << 8; int b2 = (((int) (rawData[k++])) & mask) << 16; intData[j] = 0xff000000 | b0 | b1 | b2; j++; } } protected void unpack(byte[] rawData, int rawOffset, int bpp, byte[] byteData, int byteOffset, int w) throws Exception { int j = byteOffset; int k = rawOffset; byte mask; int pixPerByte; switch (bpp) { case 1: mask = (byte) 0x01; pixPerByte = 8; break; case 4: mask = (byte) 0x0f; pixPerByte = 2; break; case 8: mask = (byte) 0xff; pixPerByte = 1; break; default: throw new Exception("Unsupported bits-per-pixel value"); } for (int i = 0;;) { int shift = 8 - bpp; for (int ii = 0; ii < pixPerByte; ii++) { byte br = rawData[k]; br >>= shift; byteData[j] = (byte) (br & mask); //System.out.println("Setting byteData[" + j + "]=" + Test.byteToHex(byteData[j])); j++; i++; if (i == w) return; shift -= bpp; } k++; } } protected int readScanLine(byte[] b, int off, int len) throws IOException { int bytesRead = 0; int l = len; int r = 0; while (len > 0) { bytesRead = is.read(b, off, len); if (bytesRead == -1) return r == 0 ? -1 : r; if (bytesRead == len) return l; len -= bytesRead; off += bytesRead; r += bytesRead; } return l; } protected void getPixelData() throws IOException, Exception { byte[] rawData; // the raw unpacked data // Skip to the start of the bitmap data (if we are not already there) long skip = bitmapOffset - curPos; if (skip > 0) { is.skip(skip); curPos += skip; } int len = scanLineSize; if (bitsPerPixel > 8) intData = new int[width * height]; else byteData = new byte[width * height]; rawData = new byte[actualSizeOfBitmap]; int rawOffset = 0; int offset = (height - 1) * width; for (int i = height - 1; i >= 0; i--) { int n = readScanLine(rawData, rawOffset, len); if (n < len) throw new Exception("Scan line ended prematurely after " + n + " bytes"); if (bitsPerPixel > 8) { // Unpack and create one int per pixel unpack(rawData, rawOffset, intData, offset, width); } else { // Unpack and create one byte per pixel unpack(rawData, rawOffset, bitsPerPixel, byteData, offset, width); } rawOffset += len; offset -= width; } } public void read(InputStream is) throws IOException, Exception { this.is = is; getFileHeader(); getBitmapHeader(); if (compression != 0) throw new Exception("BMP Compression not supported"); getPalette(); getPixelData(); } public MemoryImageSource getImageSource() { ColorModel cm; MemoryImageSource mis; if (noOfEntries > 0) { // There is a color palette; create an IndexColorModel cm = new IndexColorModel(bitsPerPixel, noOfEntries, r, g, b); } else { // There is no palette; use the default RGB color model cm = ColorModel.getRGBdefault(); } // Create MemoryImageSource if (bitsPerPixel > 8) { // use one int per pixel mis = new MemoryImageSource(width, height, cm, intData, 0, width); } else { // use one byte per pixel mis = new MemoryImageSource(width, height, cm, byteData, 0, width); } return mis; // this can be used by JComponent.createImage() } }
Java
/* * FileNameFilter. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.util; import java.io.File; import java.util.ArrayList; import java.util.StringTokenizer; /** * FileName filter that works for both javax.swing.filechooser and java.io. */ public class FileNameFilter extends javax.swing.filechooser.FileFilter implements java.io.FileFilter { protected java.util.List extensions = new ArrayList(); protected String default_extension = null; protected String description; protected boolean allowDir = true; /** * Constructs the list of extensions out of a string of comma-separated * elements, each of which represents one extension. * * @param ext the list of comma-separated extensions */ public FileNameFilter(String ext, String description) { this(ext, description, true); } public FileNameFilter(String ext, String description, boolean allowDir) { this.description = description; this.allowDir = allowDir; StringTokenizer st = new StringTokenizer(ext, ", "); String extension; while (st.hasMoreTokens()) { extension = st.nextToken(); extensions.add(extension); if (default_extension == null) default_extension = extension; } } /** * determines if the filename is an acceptable one. If a * filename ends with one of the extensions the filter was * initialized with, then the function returns true. if not, * the function returns false. * * @param dir the directory the file is in * @return true if the filename has a valid extension, false otherwise */ public boolean accept(File dir) { for (int i = 0; i < extensions.size(); i++) { if (allowDir) { if (dir.isDirectory() || dir.getName().endsWith("." + (String) extensions.get(i))) return true; } else { if (dir.getName().endsWith("." + (String) extensions.get(i))) return true; } } return extensions.size() == 0; } /** * Returns the default extension. * * @return the default extension */ public String getDefaultExtension() { return default_extension; } public void setDefaultExtension(String ext) { default_extension = ext; } public String getDescription() { return description; } }
Java
/* * FileUtil. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.util; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; /** * @author Scott Pennell */ public class FileUtil { private static List supportedExtensions = null; public static File[] findFilesRecursively(File directory) { if (directory.isFile()) { File[] f = new File[1]; f[0] = directory; return f; } List list = new ArrayList(); addSongsRecursive(list, directory); return ((File[]) list.toArray(new File[list.size()])); } private static void addSongsRecursive(List found, File rootDir) { if (rootDir == null) return; // we do not want waste time File[] files = rootDir.listFiles(); if (files == null) return; for (int i = 0; i < files.length; i++) { File file = new File(rootDir, files[i].getName()); if (file.isDirectory()) addSongsRecursive(found, file); else { if (isMusicFile(files[i])) { found.add(file); } } } } public static boolean isMusicFile(File f) { List exts = getSupportedExtensions(); int sz = exts.size(); String ext; String name = f.getName(); for (int i = 0; i < sz; i++) { ext = (String) exts.get(i); if (ext.equals(".wsz") || ext.equals(".m3u")) continue; if (name.endsWith(ext)) return true; } return false; } public static List getSupportedExtensions() { if (supportedExtensions == null) { String ext = Config.getInstance().getExtensions(); StringTokenizer st = new StringTokenizer(ext, ","); supportedExtensions = new ArrayList(); while (st.hasMoreTokens()) supportedExtensions.add("." + st.nextElement()); } return (supportedExtensions); } public static String getSupprtedExtensions() { List exts = getSupportedExtensions(); StringBuffer s = new StringBuffer(); int sz = exts.size(); String ext; for (int i = 0; i < sz; i++) { ext = (String) exts.get(i); if (ext.equals(".wsz") || ext.equals(".m3u")) continue; if (i == 0) s.append(ext); else s.append(";").append(ext); } return s.toString(); } public static String padString(String s, int length) { return padString(s, ' ', length); } public static String padString(String s, char padChar, int length) { int slen, numPads = 0; if (s == null) { s = ""; numPads = length; } else if ((slen = s.length()) > length) { s = s.substring(0, length); } else if (slen < length) { numPads = length - slen; } if (numPads == 0) return s; char[] c = new char[numPads]; Arrays.fill(c, padChar); return s + new String(c); } public static String rightPadString(String s, int length) { return (rightPadString(s, ' ', length)); } public static String rightPadString(String s, char padChar, int length) { int slen, numPads = 0; if (s == null) { s = ""; numPads = length; } else if ((slen = s.length()) > length) { s = s.substring(length); } else if (slen < length) { numPads = length - slen; } if (numPads == 0) return (s); char[] c = new char[numPads]; Arrays.fill(c, padChar); return new String(c) + s; } }
Java
/* * Config. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.util; import java.io.File; import java.util.StringTokenizer; import javax.swing.ImageIcon; import javax.swing.JFrame; import javazoom.jlgui.player.amp.util.ini.Configuration; /** * This class provides all parameters for jlGui coming from a file. */ public class Config { public static String[] protocols = { "http:", "file:", "ftp:", "https:", "ftps:", "jar:" }; public static String TAGINFO_POLICY_FILE = "file"; public static String TAGINFO_POLICY_ALL = "all"; public static String TAGINFO_POLICY_NONE = "none"; private static String CONFIG_FILE_NAME = "jlgui.ini"; private Configuration _config = null; // configuration keys private static final String LAST_URL = "last_url", LAST_DIR = "last_dir", ORIGINE_X = "origine_x", ORIGINE_Y = "origine_y", LAST_SKIN = "last_skin", LAST_SKIN_DIR = "last_skin_dir", EXTENSIONS = "allowed_extensions", PLAYLIST_IMPL = "playlist_impl", TAGINFO_MPEG_IMPL = "taginfo_mpeg_impl", TAGINFO_OGGVORBIS_IMPL = "taginfo_oggvorbis_impl", TAGINFO_APE_IMPL = "taginfo_ape_impl", TAGINFO_FLAC_IMPL = "taginfo_flac_impl", LAST_PLAYLIST = "last_playlist", PROXY_SERVER = "proxy_server", PROXY_PORT = "proxy_port", PROXY_LOGIN = "proxy_login", PROXY_PASSWORD = "proxy_password", PLAYLIST_ENABLED = "playlist_enabled", SHUFFLE_ENABLED = "shuffle_enabled", REPEAT_ENABLED = "repeat_enabled", EQUALIZER_ENABLED = "equalizer_enabled", EQUALIZER_ON = "equalizer_on", EQUALIZER_AUTO = "equalizer_auto", LAST_EQUALIZER = "last_equalizer", SCREEN_LIMIT = "screen_limit", TAGINFO_POLICY = "taginfo_policy", VOLUME_VALUE = "volume_value", AUDIO_DEVICE = "audio_device", VISUAL_MODE = "visual_mode"; private static Config _instance = null; private String _audioDevice = ""; private String _visualMode = ""; private String _extensions = "m3u,pls,wsz,snd,aifc,aif,wav,au,mp1,mp2,mp3,ogg,spx,flac,ape,mac"; private String _lastUrl = ""; private String _lastDir = ""; private String _lastSkinDir = ""; private String _lastEqualizer = ""; private String _defaultSkin = ""; private String _playlist = "javazoom.jlgui.player.amp.playlist.BasePlaylist"; private String _taginfoMpeg = "javazoom.jlgui.player.amp.tag.MpegInfo"; private String _taginfoOggVorbis = "javazoom.jlgui.player.amp.tag.OggVorbisInfo"; private String _taginfoAPE = "javazoom.jlgui.player.amp.tag.APEInfo"; private String _taginfoFlac = "javazoom.jlgui.player.amp.tag.FlacInfo"; private String _playlistFilename = ""; private int _x = 0; private int _y = 0; private String _proxyServer = ""; private String _proxyLogin = ""; private String _proxyPassword = ""; private int _proxyPort = -1; private int _volume = -1; private boolean _playlistEnabled = false; private boolean _shuffleEnabled = false; private boolean _repeatEnabled = false; private boolean _equalizerEnabled = false; private boolean _equalizerOn = false; private boolean _equalizerAuto = false; private boolean _screenLimit = false; private String _taginfoPolicy = TAGINFO_POLICY_FILE; private JFrame topParent = null; private ImageIcon iconParent = null; private Config() { } /** * Returns Config instance. */ public synchronized static Config getInstance() { if (_instance == null) { _instance = new Config(); } return _instance; } public void setTopParent(JFrame frame) { topParent = frame; } public JFrame getTopParent() { if (topParent == null) { topParent = new JFrame(); } return topParent; } public void setIconParent(ImageIcon icon) { iconParent = icon; } public ImageIcon getIconParent() { return iconParent; } /** * Returns JavaSound audio device. * @return String */ public String getAudioDevice() { return _audioDevice; } /** * Set JavaSound audio device. * @param dev String */ public void setAudioDevice(String dev) { _audioDevice = dev; } /** * Return visual mode. * @return */ public String getVisualMode() { return _visualMode; } /** * Set visual mode. * @param mode */ public void setVisualMode(String mode) { _visualMode = mode; } /** * Returns playlist filename. */ public String getPlaylistFilename() { return _playlistFilename; } /** * Sets playlist filename. */ public void setPlaylistFilename(String pl) { _playlistFilename = pl; } /** * Returns last equalizer values. */ public int[] getLastEqualizer() { int[] vals = null; if ((_lastEqualizer != null) && (!_lastEqualizer.equals(""))) { vals = new int[11]; int i = 0; StringTokenizer st = new StringTokenizer(_lastEqualizer, ","); while (st.hasMoreTokens()) { String v = st.nextToken(); vals[i++] = Integer.parseInt(v); } } return vals; } /** * Sets last equalizer values. */ public void setLastEqualizer(int[] vals) { if (vals != null) { String dump = ""; for (int i = 0; i < vals.length; i++) { dump = dump + vals[i] + ","; } _lastEqualizer = dump.substring(0, (dump.length() - 1)); } } /** * Return screen limit flag. * * @return is screen limit flag */ public boolean isScreenLimit() { return _screenLimit; } /** * Set screen limit flag. * * @param b */ public void setScreenLimit(boolean b) { _screenLimit = b; } /** * Returns last URL. */ public String getLastURL() { return _lastUrl; } /** * Sets last URL. */ public void setLastURL(String url) { _lastUrl = url; } /** * Returns last Directory. */ public String getLastDir() { if ((_lastDir != null) && (!_lastDir.endsWith(File.separator))) { _lastDir = _lastDir + File.separator; } return _lastDir; } /** * Sets last Directory. */ public void setLastDir(String dir) { _lastDir = dir; if ((_lastDir != null) && (!_lastDir.endsWith(File.separator))) { _lastDir = _lastDir + File.separator; } } /** * Returns last skin directory. */ public String getLastSkinDir() { if ((_lastSkinDir != null) && (!_lastSkinDir.endsWith(File.separator))) { _lastSkinDir = _lastSkinDir + File.separator; } return _lastSkinDir; } /** * Sets last skin directory. */ public void setLastSkinDir(String dir) { _lastSkinDir = dir; if ((_lastSkinDir != null) && (!_lastSkinDir.endsWith(File.separator))) { _lastSkinDir = _lastSkinDir + File.separator; } } /** * Returns audio extensions. */ public String getExtensions() { return _extensions; } /** * Returns proxy server. */ public String getProxyServer() { return _proxyServer; } /** * Returns proxy port. */ public int getProxyPort() { return _proxyPort; } /** * Returns volume value. */ public int getVolume() { return _volume; } /** * Returns volume value. */ public void setVolume(int vol) { _volume = vol; } /** * Returns X location. */ public int getXLocation() { return _x; } /** * Returns Y location. */ public int getYLocation() { return _y; } /** * Sets X,Y location. */ public void setLocation(int x, int y) { _x = x; _y = y; } /** * Sets Proxy info. */ public void setProxy(String url, int port, String login, String password) { _proxyServer = url; _proxyPort = port; _proxyLogin = login; _proxyPassword = password; } /** * Enables Proxy. */ public boolean enableProxy() { if ((_proxyServer != null) && (!_proxyServer.equals(""))) { System.getProperties().put("proxySet", "true"); System.getProperties().put("proxyHost", _proxyServer); System.getProperties().put("proxyPort", "" + _proxyPort); return true; } else return false; } /** * Returns PlaylistUI state. */ public boolean isPlaylistEnabled() { return _playlistEnabled; } /** * Sets PlaylistUI state. */ public void setPlaylistEnabled(boolean ena) { _playlistEnabled = ena; } /** * Returns ShuffleUI state. */ public boolean isShuffleEnabled() { return _shuffleEnabled; } /** * Sets ShuffleUI state. */ public void setShuffleEnabled(boolean ena) { _shuffleEnabled = ena; } /** * Returns RepeatUI state. */ public boolean isRepeatEnabled() { return _repeatEnabled; } /** * Sets RepeatUI state. */ public void setRepeatEnabled(boolean ena) { _repeatEnabled = ena; } /** * Returns EqualizerUI state. */ public boolean isEqualizerEnabled() { return _equalizerEnabled; } /** * Sets EqualizerUI state. */ public void setEqualizerEnabled(boolean ena) { _equalizerEnabled = ena; } /** * Returns default skin. */ public String getDefaultSkin() { return _defaultSkin; } /** * Sets default skin. */ public void setDefaultSkin(String skin) { _defaultSkin = skin; } /** * Returns playlist classname implementation. */ public String getPlaylistClassName() { return _playlist; } /** * Set playlist classname implementation. */ public void setPlaylistClassName(String s) { _playlist = s; } /** * Returns Mpeg TagInfo classname implementation. */ public String getMpegTagInfoClassName() { return _taginfoMpeg; } /** * Returns Ogg Vorbis TagInfo classname implementation. */ public String getOggVorbisTagInfoClassName() { return _taginfoOggVorbis; } /** * Returns APE TagInfo classname implementation. */ public String getAPETagInfoClassName() { return _taginfoAPE; } /** * Returns Ogg Vorbis TagInfo classname implementation. */ public String getFlacTagInfoClassName() { return _taginfoFlac; } /** * Loads configuration for the specified file. */ public void load(String configfile) { CONFIG_FILE_NAME = configfile; load(); } /** * Loads configuration. */ public void load() { _config = new Configuration(CONFIG_FILE_NAME); // Creates config entries if needed. if (_config.get(AUDIO_DEVICE) == null) _config.add(AUDIO_DEVICE, _audioDevice); if (_config.get(VISUAL_MODE) == null) _config.add(VISUAL_MODE, _visualMode); if (_config.get(LAST_URL) == null) _config.add(LAST_URL, _lastUrl); if (_config.get(LAST_EQUALIZER) == null) _config.add(LAST_EQUALIZER, _lastEqualizer); if (_config.get(LAST_DIR) == null) _config.add(LAST_DIR, _lastDir); if (_config.get(LAST_SKIN_DIR) == null) _config.add(LAST_SKIN_DIR, _lastSkinDir); if (_config.get(TAGINFO_POLICY) == null) _config.add(TAGINFO_POLICY, _taginfoPolicy); if (_config.getInt(ORIGINE_X) == -1) _config.add(ORIGINE_X, _x); if (_config.getInt(ORIGINE_Y) == -1) _config.add(ORIGINE_Y, _y); if (_config.get(LAST_SKIN) == null) _config.add(LAST_SKIN, _defaultSkin); if (_config.get(LAST_PLAYLIST) == null) _config.add(LAST_PLAYLIST, _playlistFilename); if (_config.get(PLAYLIST_IMPL) == null) _config.add(PLAYLIST_IMPL, _playlist); if (_config.get(TAGINFO_MPEG_IMPL) == null) _config.add(TAGINFO_MPEG_IMPL, _taginfoMpeg); if (_config.get(TAGINFO_OGGVORBIS_IMPL) == null) _config.add(TAGINFO_OGGVORBIS_IMPL, _taginfoOggVorbis); if (_config.get(TAGINFO_APE_IMPL) == null) _config.add(TAGINFO_APE_IMPL, _taginfoAPE); if (_config.get(TAGINFO_FLAC_IMPL) == null) _config.add(TAGINFO_FLAC_IMPL, _taginfoFlac); if (_config.get(EXTENSIONS) == null) _config.add(EXTENSIONS, _extensions); if (_config.get(PROXY_SERVER) == null) _config.add(PROXY_SERVER, _proxyServer); if (_config.getInt(PROXY_PORT) == -1) _config.add(PROXY_PORT, _proxyPort); if (_config.getInt(VOLUME_VALUE) == -1) _config.add(VOLUME_VALUE, _volume); if (_config.get(PROXY_LOGIN) == null) _config.add(PROXY_LOGIN, _proxyLogin); if (_config.get(PROXY_PASSWORD) == null) _config.add(PROXY_PASSWORD, _proxyPassword); if (!_config.getBoolean(PLAYLIST_ENABLED)) _config.add(PLAYLIST_ENABLED, _playlistEnabled); if (!_config.getBoolean(SHUFFLE_ENABLED)) _config.add(SHUFFLE_ENABLED, _shuffleEnabled); if (!_config.getBoolean(REPEAT_ENABLED)) _config.add(REPEAT_ENABLED, _repeatEnabled); if (!_config.getBoolean(EQUALIZER_ENABLED)) _config.add(EQUALIZER_ENABLED, _equalizerEnabled); if (!_config.getBoolean(EQUALIZER_ON)) _config.add(EQUALIZER_ON, _equalizerOn); if (!_config.getBoolean(EQUALIZER_AUTO)) _config.add(EQUALIZER_AUTO, _equalizerAuto); if (!_config.getBoolean(SCREEN_LIMIT)) _config.add(SCREEN_LIMIT, _screenLimit); // Reads config entries _audioDevice = _config.get(AUDIO_DEVICE, _audioDevice); _visualMode = _config.get(VISUAL_MODE, _visualMode); _lastUrl = _config.get(LAST_URL, _lastUrl); _lastEqualizer = _config.get(LAST_EQUALIZER, _lastEqualizer); _lastDir = _config.get(LAST_DIR, _lastDir); _lastSkinDir = _config.get(LAST_SKIN_DIR, _lastSkinDir); _x = _config.getInt(ORIGINE_X, _x); _y = _config.getInt(ORIGINE_Y, _y); _defaultSkin = _config.get(LAST_SKIN, _defaultSkin); _playlistFilename = _config.get(LAST_PLAYLIST, _playlistFilename); _taginfoPolicy = _config.get(TAGINFO_POLICY, _taginfoPolicy); _extensions = _config.get(EXTENSIONS, _extensions); _playlist = _config.get(PLAYLIST_IMPL, _playlist); _taginfoMpeg = _config.get(TAGINFO_MPEG_IMPL, _taginfoMpeg); _taginfoOggVorbis = _config.get(TAGINFO_OGGVORBIS_IMPL, _taginfoOggVorbis); _taginfoAPE = _config.get(TAGINFO_APE_IMPL, _taginfoAPE); _taginfoFlac = _config.get(TAGINFO_FLAC_IMPL, _taginfoFlac); _proxyServer = _config.get(PROXY_SERVER, _proxyServer); _proxyPort = _config.getInt(PROXY_PORT, _proxyPort); _volume = _config.getInt(VOLUME_VALUE, _volume); _proxyLogin = _config.get(PROXY_LOGIN, _proxyLogin); _proxyPassword = _config.get(PROXY_PASSWORD, _proxyPassword); _playlistEnabled = _config.getBoolean(PLAYLIST_ENABLED, _playlistEnabled); _shuffleEnabled = _config.getBoolean(SHUFFLE_ENABLED, _shuffleEnabled); _repeatEnabled = _config.getBoolean(REPEAT_ENABLED, _repeatEnabled); _equalizerEnabled = _config.getBoolean(EQUALIZER_ENABLED, _equalizerEnabled); _equalizerOn = _config.getBoolean(EQUALIZER_ON, _equalizerOn); _equalizerAuto = _config.getBoolean(EQUALIZER_AUTO, _equalizerAuto); _screenLimit = _config.getBoolean(SCREEN_LIMIT, _screenLimit); } /** * Saves configuration. */ public void save() { if (_config != null) { _config.add(ORIGINE_X, _x); _config.add(ORIGINE_Y, _y); if (_lastDir != null) _config.add(LAST_DIR, _lastDir); if (_lastSkinDir != null) _config.add(LAST_SKIN_DIR, _lastSkinDir); if (_audioDevice != null) _config.add(AUDIO_DEVICE, _audioDevice); if (_visualMode != null) _config.add(VISUAL_MODE, _visualMode); if (_lastUrl != null) _config.add(LAST_URL, _lastUrl); if (_lastEqualizer != null) _config.add(LAST_EQUALIZER, _lastEqualizer); if (_playlistFilename != null) _config.add(LAST_PLAYLIST, _playlistFilename); if (_playlist != null) _config.add(PLAYLIST_IMPL, _playlist); if (_defaultSkin != null) _config.add(LAST_SKIN, _defaultSkin); if (_taginfoPolicy != null) _config.add(TAGINFO_POLICY, _taginfoPolicy); if (_volume != -1) _config.add(VOLUME_VALUE, _volume); _config.add(PLAYLIST_ENABLED, _playlistEnabled); _config.add(SHUFFLE_ENABLED, _shuffleEnabled); _config.add(REPEAT_ENABLED, _repeatEnabled); _config.add(EQUALIZER_ENABLED, _equalizerEnabled); _config.add(EQUALIZER_ON, _equalizerOn); _config.add(EQUALIZER_AUTO, _equalizerAuto); _config.add(SCREEN_LIMIT, _screenLimit); _config.save(); } } /** * @return equalizer auto flag */ public boolean isEqualizerAuto() { return _equalizerAuto; } /** * @return equalizer on flag */ public boolean isEqualizerOn() { return _equalizerOn; } /** * @param b */ public void setEqualizerAuto(boolean b) { _equalizerAuto = b; } /** * @param b */ public void setEqualizerOn(boolean b) { _equalizerOn = b; } public static boolean startWithProtocol(String input) { boolean ret = false; if (input != null) { input = input.toLowerCase(); for (int i = 0; i < protocols.length; i++) { if (input.startsWith(protocols[i])) { ret = true; break; } } } return ret; } /** * @return tag info policy */ public String getTaginfoPolicy() { return _taginfoPolicy; } /** * @param string */ public void setTaginfoPolicy(String string) { _taginfoPolicy = string; } }
Java
/* * FileSelector. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.util; import java.io.File; import javax.swing.JFileChooser; import javax.swing.JFrame; import javazoom.jlgui.player.amp.Loader; /** * This class is used to select a file or directory for loading or saving. */ public class FileSelector { public static final int OPEN = 1; public static final int SAVE = 2; public static final int SAVE_AS = 3; public static final int DIRECTORY = 4; private File[] files = null; private File directory = null; private static FileSelector instance = null; public File[] getFiles() { return files; } public File getDirectory() { return directory; } public static final FileSelector getInstance() { if (instance == null) instance = new FileSelector(); return instance; } /** * Opens a dialog box so that the user can search for a file * with the given extension and returns the filename selected. * * @param extensions the extension of the filename to be selected, * or "" if any filename can be used * @param directory the folder to be put in the starting directory * @param mode the action that will be performed on the file, used to tell what * files are valid * @return the selected file */ public static File[] selectFile(Loader loader, int mode, boolean multiple, String extensions, String description, File directory) { return selectFile(loader, mode, multiple, null, extensions, description, null, directory); } /** * Opens a dialog box so that the user can search for a file * with the given extension and returns the filename selected. * * @param extensions the extension of the filename to be selected, * or "" if any filename can be used * @param titlePrefix the string to be put in the title, followed by : SaveAs * @param mode the action that will be performed on the file, used to tell what * files are valid * @param defaultFile the default file * @param directory the string to be put in the starting directory * @return the selected filename */ public static File[] selectFile(Loader loader, int mode, boolean multiple, File defaultFile, String extensions, String description, String titlePrefix, File directory) { JFrame mainWindow = null; if (loader instanceof JFrame) { mainWindow = (JFrame) loader; } JFileChooser filePanel = new JFileChooser(); StringBuffer windowTitle = new StringBuffer(); if (titlePrefix != null && titlePrefix.length() > 0) windowTitle.append(titlePrefix).append(": "); switch (mode) { case OPEN: windowTitle.append("Open"); break; case SAVE: windowTitle.append("Save"); break; case SAVE_AS: windowTitle.append("Save As"); break; case DIRECTORY: windowTitle.append("Choose Directory"); break; } filePanel.setDialogTitle(windowTitle.toString()); FileNameFilter filter = new FileNameFilter(extensions, description); filePanel.setFileFilter(filter); if (defaultFile != null) filePanel.setSelectedFile(defaultFile); if (directory != null) filePanel.setCurrentDirectory(directory); filePanel.setMultiSelectionEnabled(multiple); int retVal = -1; switch (mode) { case OPEN: filePanel.setDialogType(JFileChooser.OPEN_DIALOG); retVal = filePanel.showOpenDialog(mainWindow); break; case SAVE: filePanel.setDialogType(JFileChooser.SAVE_DIALOG); retVal = filePanel.showSaveDialog(mainWindow); break; case SAVE_AS: filePanel.setDialogType(JFileChooser.SAVE_DIALOG); retVal = filePanel.showSaveDialog(mainWindow); break; case DIRECTORY: filePanel.setDialogType(JFileChooser.SAVE_DIALOG); filePanel.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); retVal = filePanel.showDialog(mainWindow, "Select"); break; } if (retVal == JFileChooser.APPROVE_OPTION) { if (multiple) getInstance().files = filePanel.getSelectedFiles(); else { getInstance().files = new File[1]; getInstance().files[0] = filePanel.getSelectedFile(); } getInstance().directory = filePanel.getCurrentDirectory(); } else { getInstance().files = null; } return getInstance().files; } }
Java
/* * Preferences. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.util.ui; import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.Method; import java.util.MissingResourceException; import java.util.ResourceBundle; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.border.EmptyBorder; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import javazoom.jlgui.player.amp.PlayerUI; import javazoom.jlgui.player.amp.util.Config; public class Preferences extends JFrame implements TreeSelectionListener, ActionListener { private static Preferences instance = null; private JTree tree = null; private ResourceBundle bundle = null; private DefaultMutableTreeNode options = null; private DefaultMutableTreeNode filetypes = null; private DefaultMutableTreeNode device = null; private DefaultMutableTreeNode proxy = null; private DefaultMutableTreeNode plugins = null; private DefaultMutableTreeNode visual = null; private DefaultMutableTreeNode visuals = null; private DefaultMutableTreeNode output = null; //private DefaultMutableTreeNode drm = null; private DefaultMutableTreeNode skins = null; private DefaultMutableTreeNode browser = null; private JScrollPane treePane = null; private JScrollPane workPane = null; private JButton close = null; private PlayerUI player = null; public Preferences(PlayerUI player) { super(); this.player = player; setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); ImageIcon icon = Config.getInstance().getIconParent(); if (icon != null) setIconImage(icon.getImage()); } public static synchronized Preferences getInstance(PlayerUI player) { if (instance == null) { instance = new Preferences(player); instance.loadUI(); } return instance; } private void loadUI() { bundle = ResourceBundle.getBundle("javazoom/jlgui/player/amp/util/ui/preferences"); setTitle(getResource("title")); DefaultMutableTreeNode root = new DefaultMutableTreeNode(); // Options if (getResource("tree.options") != null) { options = new DefaultMutableTreeNode(getResource("tree.options")); if (getResource("tree.options.device") != null) { device = new DefaultMutableTreeNode(); device.setUserObject(new NodeItem(getResource("tree.options.device"), getResource("tree.options.device.impl"))); options.add(device); } if (getResource("tree.options.visual") != null) { visual = new DefaultMutableTreeNode(); visual.setUserObject(new NodeItem(getResource("tree.options.visual"), getResource("tree.options.visual.impl"))); options.add(visual); } if (getResource("tree.options.filetypes") != null) { filetypes = new DefaultMutableTreeNode(); filetypes.setUserObject(new NodeItem(getResource("tree.options.filetypes"), getResource("tree.options.filetypes.impl"))); options.add(filetypes); } if (getResource("tree.options.system") != null) { proxy = new DefaultMutableTreeNode(); proxy.setUserObject(new NodeItem(getResource("tree.options.system"), getResource("tree.options.system.impl"))); options.add(proxy); } root.add(options); } // Plugins if (getResource("tree.plugins") != null) { plugins = new DefaultMutableTreeNode(getResource("tree.plugins")); if (getResource("tree.plugins.visualization") != null) { visuals = new DefaultMutableTreeNode(); visuals.setUserObject(new NodeItem(getResource("tree.plugins.visualization"), getResource("tree.plugins.visualization.impl"))); plugins.add(visuals); } if (getResource("tree.plugins.output") != null) { output = new DefaultMutableTreeNode(); output.setUserObject(new NodeItem(getResource("tree.plugins.output"), getResource("tree.plugins.output.impl"))); plugins.add(output); } /*if (getResource("tree.plugins.drm") != null) { drm = new DefaultMutableTreeNode(); drm.setUserObject(new NodeItem(getResource("tree.plugins.drm"), getResource("tree.plugins.drm.impl"))); plugins.add(drm); }*/ root.add(plugins); } // Skins if (getResource("tree.skins") != null) { skins = new DefaultMutableTreeNode(getResource("tree.skins")); if (getResource("tree.skins.browser") != null) { browser = new DefaultMutableTreeNode(); browser.setUserObject(new NodeItem(getResource("tree.skins.browser"), getResource("tree.skins.browser.impl"))); skins.add(browser); } root.add(skins); } tree = new JTree(root); tree.setRootVisible(false); DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer(); renderer.setLeafIcon(null); renderer.setClosedIcon(null); renderer.setOpenIcon(null); tree.setCellRenderer(renderer); tree.addTreeSelectionListener(this); int i = 0; while (i < tree.getRowCount()) { tree.expandRow(i++); } tree.setBorder(new EmptyBorder(1, 4, 1, 2)); GridBagLayout layout = new GridBagLayout(); getContentPane().setLayout(layout); GridBagConstraints cnts = new GridBagConstraints(); cnts.fill = GridBagConstraints.BOTH; cnts.weightx = 0.3; cnts.weighty = 1.0; cnts.gridx = 0; cnts.gridy = 0; treePane = new JScrollPane(tree); JPanel leftPane = new JPanel(); leftPane.setLayout(new BorderLayout()); leftPane.add(treePane, BorderLayout.CENTER); if (getResource("button.close") != null) { close = new JButton(getResource("button.close")); close.addActionListener(this); leftPane.add(close, BorderLayout.SOUTH); } getContentPane().add(leftPane, cnts); cnts.weightx = 1.0; cnts.gridx = 1; cnts.gridy = 0; workPane = new JScrollPane(new JPanel()); getContentPane().add(workPane, cnts); } public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (node == null) return; if (node.isLeaf()) { Object nodeItem = node.getUserObject(); if ((nodeItem != null) && (nodeItem instanceof NodeItem)) { PreferenceItem pane = getPreferenceItem(((NodeItem) nodeItem).getImpl()); if (pane != null) { pane.setPlayer(player); pane.loadUI(); pane.setParentFrame(this); workPane.setViewportView(pane); } } } } public void selectSkinBrowserPane() { TreeNode[] path = browser.getPath(); tree.setSelectionPath(new TreePath(path)); } public void actionPerformed(ActionEvent ev) { if (ev.getSource() == close) { if (player != null) { Config config = player.getConfig(); config.save(); } dispose(); } } /** * Return I18N value of a given key. * @param key * @return */ public String getResource(String key) { String value = null; if (key != null) { try { value = bundle.getString(key); } catch (MissingResourceException e) { } } return value; } public PreferenceItem getPreferenceItem(String impl) { PreferenceItem item = null; if (impl != null) { try { Class aClass = Class.forName(impl); Method method = aClass.getMethod("getInstance", null); item = (PreferenceItem) method.invoke(null, null); } catch (Exception e) { // TODO } } return item; } }
Java
/* * TypePreference. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.util.ui; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ResourceBundle; import java.util.StringTokenizer; import javax.swing.DefaultListModel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class TypePreference extends PreferenceItem implements ActionListener, ListSelectionListener { private DefaultListModel listModel = null; private JList types = null; private JPanel listPane = null; private JPanel extensionPane = null; private static TypePreference instance = null; private TypePreference() { listModel = new DefaultListModel(); } public static TypePreference getInstance() { if (instance == null) { instance = new TypePreference(); } return instance; } public void loadUI() { if (loaded == false) { bundle = ResourceBundle.getBundle("javazoom/jlgui/player/amp/util/ui/type"); setBorder(new TitledBorder(getResource("title"))); loadTypes(); types = new JList(listModel); types.setBorder(new EmptyBorder(1, 2, 1, 1)); types.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); types.setLayoutOrientation(JList.VERTICAL); types.setVisibleRowCount(12); types.addListSelectionListener(this); JScrollPane listScroller = new JScrollPane(types); listScroller.setPreferredSize(new Dimension(80, 240)); listPane = new JPanel(); listPane.add(listScroller); extensionPane = new JPanel(); GridBagLayout layout = new GridBagLayout(); setLayout(layout); GridBagConstraints cnts = new GridBagConstraints(); cnts.fill = GridBagConstraints.BOTH; cnts.gridwidth = 1; cnts.weightx = 0.30; cnts.weighty = 1.0; cnts.gridx = 0; cnts.gridy = 0; add(listPane, cnts); cnts.gridwidth = 1; cnts.weightx = 0.70; cnts.weighty = 1.0; cnts.gridx = 1; cnts.gridy = 0; add(extensionPane, cnts); loaded = true; } } public void actionPerformed(ActionEvent ev) { } public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { if (types.getSelectedIndex() == -1) { } else { } } } private void loadTypes() { String extensions = player.getConfig().getExtensions(); StringTokenizer st = new StringTokenizer(extensions, ","); while (st.hasMoreTokens()) { String type = st.nextToken(); listModel.addElement(type); } } }
Java
/* * EmptyPreference. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.util.ui; import javax.swing.border.TitledBorder; public class EmptyPreference extends PreferenceItem { private static EmptyPreference instance = null; private EmptyPreference() { } public static EmptyPreference getInstance() { if (instance == null) { instance = new EmptyPreference(); } return instance; } public void loadUI() { if (loaded == false) { setBorder(new TitledBorder("")); loaded = true; } } }
Java
/* * SystemPreference. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.util.ui; import java.awt.BorderLayout; import java.awt.Font; import java.util.Iterator; import java.util.Properties; import java.util.ResourceBundle; import java.util.TreeMap; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; public class SystemPreference extends PreferenceItem { private JTextArea info = null; private boolean loaded = false; private static SystemPreference instance = null; private SystemPreference() { } public static SystemPreference getInstance() { if (instance == null) { instance = new SystemPreference(); } return instance; } public void loadUI() { if (loaded == false) { bundle = ResourceBundle.getBundle("javazoom/jlgui/player/amp/util/ui/system"); setBorder(new TitledBorder(getResource("title"))); setLayout(new BorderLayout()); info = new JTextArea(16,35); info.setFont(new Font("Dialog", Font.PLAIN, 11)); info.setEditable(false); info.setCursor(null); info.setBorder(new EmptyBorder(1,2,1,1)); Properties props = System.getProperties(); Iterator it = props.keySet().iterator(); TreeMap map = new TreeMap(); while (it.hasNext()) { String key = (String) it.next(); String value = props.getProperty(key); map.put(key, value); } it = map.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); String value = (String) map.get(key); info.append(key + "=" + value + "\r\n"); } JScrollPane infoScroller = new JScrollPane(info); infoScroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); infoScroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); add(infoScroller, BorderLayout.CENTER); info.setCaretPosition(0); loaded = true; } } }
Java
/* * DevicePreference. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.util.ui; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.MessageFormat; import java.util.Iterator; import java.util.List; import java.util.ResourceBundle; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; import javazoom.jlgui.basicplayer.BasicController; import javazoom.jlgui.basicplayer.BasicPlayer; public class DevicePreference extends PreferenceItem implements ActionListener { private BasicPlayer bplayer = null; private static DevicePreference instance = null; private DevicePreference() { } public static DevicePreference getInstance() { if (instance == null) { instance = new DevicePreference(); } return instance; } public void loadUI() { removeAll(); bundle = ResourceBundle.getBundle("javazoom/jlgui/player/amp/util/ui/device"); setBorder(new TitledBorder(getResource("title"))); BoxLayout layout = new BoxLayout(this, BoxLayout.Y_AXIS); setLayout(layout); BasicController controller = null; if (player != null) controller = player.getController(); if ((controller != null) && (controller instanceof BasicPlayer)) { bplayer = (BasicPlayer) controller; List devices = bplayer.getMixers(); String mixer = bplayer.getMixerName(); ButtonGroup group = new ButtonGroup(); Iterator it = devices.iterator(); while (it.hasNext()) { String name = (String) it.next(); JRadioButton radio = new JRadioButton(name); if (name.equals(mixer)) { radio.setSelected(true); } else { radio.setSelected(false); } group.add(radio); radio.addActionListener(this); radio.setAlignmentX(Component.LEFT_ALIGNMENT); add(radio); } JPanel lineInfo = new JPanel(); lineInfo.setLayout(new BoxLayout(lineInfo, BoxLayout.Y_AXIS)); lineInfo.setAlignmentX(Component.LEFT_ALIGNMENT); lineInfo.setBorder(new EmptyBorder(4, 6, 0, 0)); if (getResource("line.buffer.size") != null) { Object[] args = { new Integer(bplayer.getLineCurrentBufferSize()) }; String str = MessageFormat.format(getResource("line.buffer.size"), args); JLabel lineBufferSizeLabel = new JLabel(str); lineInfo.add(lineBufferSizeLabel); } if (getResource("help") != null) { lineInfo.add(Box.createRigidArea(new Dimension(0, 30))); JLabel helpLabel = new JLabel(getResource("help")); lineInfo.add(helpLabel); } add(lineInfo); } } public void actionPerformed(ActionEvent ev) { if (bplayer != null) bplayer.setMixerName(ev.getActionCommand()); } }
Java
/* * PreferenceItem. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.util.ui; import java.util.MissingResourceException; import java.util.ResourceBundle; import javax.swing.JFrame; import javax.swing.JPanel; import javazoom.jlgui.player.amp.PlayerUI; public abstract class PreferenceItem extends JPanel { protected PlayerUI player = null; protected ResourceBundle bundle = null; protected boolean loaded = false; protected JFrame parent = null; /** * Return I18N value of a given key. * @param key * @return */ public String getResource(String key) { String value = null; if (key != null) { try { value = bundle.getString(key); } catch (MissingResourceException e) { } } return value; } public void setPlayer(PlayerUI player) { this.player = player; } public JFrame getParentFrame() { return parent; } public void setParentFrame(JFrame parent) { this.parent = parent; } public abstract void loadUI(); }
Java
/* * SkinPreference. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.util.ui; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.ResourceBundle; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.ListSelectionModel; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javazoom.jlgui.player.amp.util.FileNameFilter; import javazoom.jlgui.player.amp.util.FileSelector; public class SkinPreference extends PreferenceItem implements ActionListener, ListSelectionListener { public static final String DEFAULTSKIN = "<Default Skin>"; public static final String SKINEXTENSION = "wsz"; private DefaultListModel listModel = null; private JList skins = null; private JTextArea info = null; private JPanel listPane = null; private JPanel infoPane = null; private JPanel browsePane = null; private JButton selectSkinDir = null; private static SkinPreference instance = null; private SkinPreference() { listModel = new DefaultListModel(); } public static SkinPreference getInstance() { if (instance == null) { instance = new SkinPreference(); } return instance; } public void loadUI() { if (loaded == false) { bundle = ResourceBundle.getBundle("javazoom/jlgui/player/amp/util/ui/skin"); setBorder(new TitledBorder(getResource("title"))); File dir = null; if (player != null) { dir = new File(player.getConfig().getLastSkinDir()); } loadSkins(dir); skins = new JList(listModel); skins.setBorder(new EmptyBorder(1, 2, 1, 1)); skins.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); skins.setLayoutOrientation(JList.VERTICAL); skins.setVisibleRowCount(12); skins.addListSelectionListener(this); JScrollPane listScroller = new JScrollPane(skins); listScroller.setPreferredSize(new Dimension(300, 140)); listPane = new JPanel(); listPane.add(listScroller); infoPane = new JPanel(); info = new JTextArea(4, 35); info.setEditable(false); info.setCursor(null); JScrollPane infoScroller = new JScrollPane(info); infoScroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); infoScroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); infoPane.add(infoScroller); browsePane = new JPanel(); selectSkinDir = new JButton(getResource("browser.directory.button")); selectSkinDir.addActionListener(this); browsePane.add(selectSkinDir); GridBagLayout layout = new GridBagLayout(); setLayout(layout); GridBagConstraints cnts = new GridBagConstraints(); cnts.fill = GridBagConstraints.BOTH; cnts.gridwidth = 1; cnts.weightx = 1.0; cnts.weighty = 0.60; cnts.gridx = 0; cnts.gridy = 0; add(listPane, cnts); cnts.gridwidth = 1; cnts.weightx = 1.0; cnts.weighty = 0.30; cnts.gridx = 0; cnts.gridy = 1; add(infoPane, cnts); cnts.weightx = 1.0; cnts.weighty = 0.10; cnts.gridx = 0; cnts.gridy = 2; add(browsePane, cnts); loaded = true; } } public void actionPerformed(ActionEvent ev) { if (ev.getActionCommand().equalsIgnoreCase(getResource("browser.directory.button"))) { File[] file = FileSelector.selectFile(player.getLoader(), FileSelector.DIRECTORY, false, "", "Directories", new File(player.getConfig().getLastSkinDir())); if ((file != null) && (file[0].isDirectory())) { player.getConfig().setLastSkinDir(file[0].getAbsolutePath()); loadSkins(file[0]); } } } public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { if (skins.getSelectedIndex() == -1) { } else { String name = (String) listModel.get(skins.getSelectedIndex()); String filename = player.getConfig().getLastSkinDir() + name + "." + SKINEXTENSION; player.getSkin().setPath(filename); player.loadSkin(); player.getConfig().setDefaultSkin(filename); String readme = player.getSkin().getReadme(); if (readme == null) readme = ""; info.setText(readme); info.setCaretPosition(0); } } } private void loadSkins(File dir) { listModel.clear(); listModel.addElement(DEFAULTSKIN); if ((dir != null) && (dir.exists())) { File[] files = dir.listFiles(new FileNameFilter(SKINEXTENSION, "Skins", false)); if ((files != null) && (files.length > 0)) { for (int i = 0; i < files.length; i++) { String filename = files[i].getName(); listModel.addElement(filename.substring(0, filename.length() - 4)); } } } } }
Java
/* * VisualPreference. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.util.ui; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Hashtable; import java.util.ResourceBundle; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JSlider; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javazoom.jlgui.player.amp.visual.ui.SpectrumTimeAnalyzer; public class VisualPreference extends PreferenceItem implements ActionListener, ChangeListener { private JPanel modePane = null; private JPanel spectrumPane = null; private JPanel oscilloPane = null; private JRadioButton spectrumMode = null; private JRadioButton oscilloMode = null; private JRadioButton offMode = null; private JCheckBox peaksBox = null; private JSlider analyzerFalloff = null; private JSlider peaksFalloff = null; private static VisualPreference instance = null; private VisualPreference() { } public static VisualPreference getInstance() { if (instance == null) { instance = new VisualPreference(); } return instance; } public void loadUI() { if (loaded == false) { bundle = ResourceBundle.getBundle("javazoom/jlgui/player/amp/util/ui/visual"); setBorder(new TitledBorder(getResource("title"))); modePane = new JPanel(); modePane.setBorder(new TitledBorder(getResource("mode.title"))); modePane.setLayout(new FlowLayout()); spectrumMode = new JRadioButton(getResource("mode.spectrum")); spectrumMode.addActionListener(this); oscilloMode = new JRadioButton(getResource("mode.oscilloscope")); oscilloMode.addActionListener(this); offMode = new JRadioButton(getResource("mode.off")); offMode.addActionListener(this); SpectrumTimeAnalyzer analyzer = null; if (player != null) { analyzer = player.getSkin().getAcAnalyzer(); int displayMode = SpectrumTimeAnalyzer.DISPLAY_MODE_OFF; if (analyzer != null) { displayMode = analyzer.getDisplayMode(); } if (displayMode == SpectrumTimeAnalyzer.DISPLAY_MODE_SPECTRUM_ANALYSER) { spectrumMode.setSelected(true); } else if (displayMode == SpectrumTimeAnalyzer.DISPLAY_MODE_SCOPE) { oscilloMode.setSelected(true); } else if (displayMode == SpectrumTimeAnalyzer.DISPLAY_MODE_OFF) { offMode.setSelected(true); } } ButtonGroup modeGroup = new ButtonGroup(); modeGroup.add(spectrumMode); modeGroup.add(oscilloMode); modeGroup.add(offMode); modePane.add(spectrumMode); modePane.add(oscilloMode); modePane.add(offMode); spectrumPane = new JPanel(); spectrumPane.setLayout(new BoxLayout(spectrumPane, BoxLayout.Y_AXIS)); peaksBox = new JCheckBox(getResource("spectrum.peaks")); peaksBox.setAlignmentX(Component.LEFT_ALIGNMENT); peaksBox.addActionListener(this); if ((analyzer != null) && (analyzer.isPeaksEnabled())) peaksBox.setSelected(true); else peaksBox.setSelected(false); spectrumPane.add(peaksBox); // Analyzer falloff. JLabel analyzerFalloffLabel = new JLabel(getResource("spectrum.analyzer.falloff")); analyzerFalloffLabel.setAlignmentX(Component.LEFT_ALIGNMENT); spectrumPane.add(analyzerFalloffLabel); int minDecay = (int) (SpectrumTimeAnalyzer.MIN_SPECTRUM_ANALYSER_DECAY * 100); int maxDecay = (int) (SpectrumTimeAnalyzer.MAX_SPECTRUM_ANALYSER_DECAY * 100); int decay = (maxDecay + minDecay) / 2; if (analyzer != null) { decay = (int) (analyzer.getSpectrumAnalyserDecay() * 100); } analyzerFalloff = new JSlider(JSlider.HORIZONTAL, minDecay, maxDecay, decay); analyzerFalloff.setMajorTickSpacing(1); analyzerFalloff.setPaintTicks(true); analyzerFalloff.setMaximumSize(new Dimension(150, analyzerFalloff.getPreferredSize().height)); analyzerFalloff.setAlignmentX(Component.LEFT_ALIGNMENT); analyzerFalloff.setSnapToTicks(true); analyzerFalloff.addChangeListener(this); spectrumPane.add(analyzerFalloff); // Peaks falloff. JLabel peaksFalloffLabel = new JLabel(getResource("spectrum.peaks.falloff")); peaksFalloffLabel.setAlignmentX(Component.LEFT_ALIGNMENT); spectrumPane.add(peaksFalloffLabel); int peakDelay = SpectrumTimeAnalyzer.DEFAULT_SPECTRUM_ANALYSER_PEAK_DELAY; int fps = SpectrumTimeAnalyzer.DEFAULT_FPS; if (analyzer != null) { fps = analyzer.getFps(); peakDelay = analyzer.getPeakDelay(); } peaksFalloff = new JSlider(JSlider.HORIZONTAL, 0, 4, computeSliderValue(peakDelay, fps)); peaksFalloff.setMajorTickSpacing(1); peaksFalloff.setPaintTicks(true); peaksFalloff.setSnapToTicks(true); Hashtable labelTable = new Hashtable(); labelTable.put(new Integer(0), new JLabel("Slow")); labelTable.put(new Integer(4), new JLabel("Fast")); peaksFalloff.setLabelTable(labelTable); peaksFalloff.setPaintLabels(true); peaksFalloff.setMaximumSize(new Dimension(150, peaksFalloff.getPreferredSize().height)); peaksFalloff.setAlignmentX(Component.LEFT_ALIGNMENT); peaksFalloff.addChangeListener(this); spectrumPane.add(peaksFalloff); // Spectrum pane spectrumPane.setBorder(new TitledBorder(getResource("spectrum.title"))); if (getResource("oscilloscope.title") != null) { oscilloPane = new JPanel(); oscilloPane.setBorder(new TitledBorder(getResource("oscilloscope.title"))); } GridBagLayout layout = new GridBagLayout(); setLayout(layout); GridBagConstraints cnts = new GridBagConstraints(); cnts.fill = GridBagConstraints.BOTH; cnts.gridwidth = 2; cnts.weightx = 2.0; cnts.weighty = 0.25; cnts.gridx = 0; cnts.gridy = 0; add(modePane, cnts); cnts.gridwidth = 1; cnts.weightx = 1.0; cnts.weighty = 1.0; cnts.gridx = 0; cnts.gridy = 1; add(spectrumPane, cnts); cnts.weightx = 1.0; cnts.weighty = 1.0; cnts.gridx = 1; cnts.gridy = 1; if (oscilloPane != null) add(oscilloPane, cnts); if (analyzer == null) { disablePane(modePane); disablePane(spectrumPane); disablePane(oscilloPane); } loaded = true; } } private void disablePane(JPanel pane) { if (pane != null) { Component[] cpns = pane.getComponents(); if (cpns != null) { for (int i = 0; i < cpns.length; i++) { cpns[i].setEnabled(false); } } } } public void actionPerformed(ActionEvent ev) { if (player != null) { SpectrumTimeAnalyzer analyzer = player.getSkin().getAcAnalyzer(); if (analyzer != null) { if (ev.getSource().equals(spectrumMode)) { analyzer.setDisplayMode(SpectrumTimeAnalyzer.DISPLAY_MODE_SPECTRUM_ANALYSER); analyzer.startDSP(null); } else if (ev.getSource().equals(oscilloMode)) { analyzer.setDisplayMode(SpectrumTimeAnalyzer.DISPLAY_MODE_SCOPE); analyzer.startDSP(null); } else if (ev.getSource().equals(offMode)) { analyzer.setDisplayMode(SpectrumTimeAnalyzer.DISPLAY_MODE_OFF); analyzer.closeDSP(); analyzer.repaint(); } else if (ev.getSource().equals(peaksBox)) { if (peaksBox.isSelected()) analyzer.setPeaksEnabled(true); else analyzer.setPeaksEnabled(false); } } } } public void stateChanged(ChangeEvent ce) { if (player != null) { SpectrumTimeAnalyzer analyzer = player.getSkin().getAcAnalyzer(); if (analyzer != null) { if (ce.getSource() == analyzerFalloff) { if (!analyzerFalloff.getValueIsAdjusting()) { analyzer.setSpectrumAnalyserDecay(analyzerFalloff.getValue() * 1.0f / 100.0f); } } else if (ce.getSource() == peaksFalloff) { if (!peaksFalloff.getValueIsAdjusting()) { analyzer.setPeakDelay(computeDelay(peaksFalloff.getValue(), analyzer.getFps())); } } } } } private int computeDelay(int slidervalue, int fps) { float p = SpectrumTimeAnalyzer.DEFAULT_SPECTRUM_ANALYSER_PEAK_DELAY_FPS_RATIO; float n = SpectrumTimeAnalyzer.DEFAULT_SPECTRUM_ANALYSER_PEAK_DELAY_FPS_RATIO_RANGE; int delay = Math.round(((-n * slidervalue * 1.0f / 2.0f) + p + n) * fps); return delay; } private int computeSliderValue(int delay, int fps) { float p = SpectrumTimeAnalyzer.DEFAULT_SPECTRUM_ANALYSER_PEAK_DELAY_FPS_RATIO; float n = SpectrumTimeAnalyzer.DEFAULT_SPECTRUM_ANALYSER_PEAK_DELAY_FPS_RATIO_RANGE; int value = (int) Math.round((((p - (delay * 1.0 / fps * 1.0f)) * 2 / n) + 2)); return value; } }
Java
/* * NodeItem. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.util.ui; public class NodeItem { private String name = null; private String impl = null; public NodeItem(String name, String impl) { super(); this.name = name; this.impl = impl; } public String getImpl() { return impl; } public String toString() { return name; } }
Java
/* * OutputPreference. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.util.ui; import java.util.ResourceBundle; import javax.swing.border.TitledBorder; public class OutputPreference extends PreferenceItem { private static OutputPreference instance = null; private OutputPreference() { } public static OutputPreference getInstance() { if (instance == null) { instance = new OutputPreference(); } return instance; } public void loadUI() { if (loaded == false) { bundle = ResourceBundle.getBundle("javazoom/jlgui/player/amp/util/ui/output"); setBorder(new TitledBorder(getResource("title"))); loaded = true; } } }
Java
/* * VisualizationPreference. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.util.ui; import java.util.ResourceBundle; import javax.swing.border.TitledBorder; public class VisualizationPreference extends PreferenceItem { private static VisualizationPreference instance = null; private VisualizationPreference() { } public static VisualizationPreference getInstance() { if (instance == null) { instance = new VisualizationPreference(); } return instance; } public void loadUI() { if (loaded == false) { bundle = ResourceBundle.getBundle("javazoom/jlgui/player/amp/util/ui/visualization"); setBorder(new TitledBorder(getResource("title"))); loaded = true; } } }
Java
/* * Cubic. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.equalizer.ui; public class Cubic { float a, b, c, d; /* a + b*u + c*u^2 +d*u^3 */ public Cubic(float a, float b, float c, float d) { this.a = a; this.b = b; this.c = c; this.d = d; } /** * Evaluate cubic. * @param u * @return */ public float eval(float u) { return (((d * u) + c) * u + b) * u + a; } }
Java
/* * EqualizerUI. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.equalizer.ui; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javazoom.jlgui.player.amp.PlayerActionEvent; import javazoom.jlgui.player.amp.PlayerUI; import javazoom.jlgui.player.amp.skin.AbsoluteLayout; import javazoom.jlgui.player.amp.skin.DropTargetAdapter; import javazoom.jlgui.player.amp.skin.ImageBorder; import javazoom.jlgui.player.amp.skin.Skin; import javazoom.jlgui.player.amp.util.Config; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * This class implements an equalizer UI. * <p/> * The equalizer consists of 32 band-pass filters. * Each band of the equalizer can take on a fractional value between * -1.0 and +1.0. * At -1.0, the input signal is attenuated by 6dB, at +1.0 the signal is * amplified by 6dB. */ public class EqualizerUI extends JPanel implements ActionListener, ChangeListener { private static Log log = LogFactory.getLog(EqualizerUI.class); private int minGain = 0; private int maxGain = 100; private int[] gainValue = { 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50 }; private int[] PRESET_NORMAL = { 50, 50, 50, 50, 50, 50, 50, 50, 50, 50 }; private int[] PRESET_CLASSICAL = { 50, 50, 50, 50, 50, 50, 70, 70, 70, 76 }; private int[] PRESET_CLUB = { 50, 50, 42, 34, 34, 34, 42, 50, 50, 50 }; private int[] PRESET_DANCE = { 26, 34, 46, 50, 50, 66, 70, 70, 50, 50 }; private int[] PRESET_FULLBASS = { 26, 26, 26, 36, 46, 62, 76, 78, 78, 78 }; private int[] PRESET_FULLBASSTREBLE = { 34, 34, 50, 68, 62, 46, 28, 22, 18, 18 }; private int[] PRESET_FULLTREBLE = { 78, 78, 78, 62, 42, 24, 8, 8, 8, 8 }; private int[] PRESET_LAPTOP = { 38, 22, 36, 60, 58, 46, 38, 24, 16, 14 }; private int[] PRESET_LIVE = { 66, 50, 40, 36, 34, 34, 40, 42, 42, 42 }; private int[] PRESET_PARTY = { 32, 32, 50, 50, 50, 50, 50, 50, 32, 32 }; private int[] PRESET_POP = { 56, 38, 32, 30, 38, 54, 56, 56, 54, 54 }; private int[] PRESET_REGGAE = { 48, 48, 50, 66, 48, 34, 34, 48, 48, 48 }; private int[] PRESET_ROCK = { 32, 38, 64, 72, 56, 40, 28, 24, 24, 24 }; private int[] PRESET_TECHNO = { 30, 34, 48, 66, 64, 48, 30, 24, 24, 28 }; private Config config = null; private PlayerUI player = null; private Skin ui = null; private JPopupMenu mainpopup = null; public static final int LINEARDIST = 1; public static final int OVERDIST = 2; private float[] bands = null; private int[] eqgains = null; private int eqdist = OVERDIST; public EqualizerUI() { super(); setDoubleBuffered(true); config = Config.getInstance(); eqgains = new int[10]; setLayout(new AbsoluteLayout()); int[] vals = config.getLastEqualizer(); if (vals != null) { for (int h = 0; h < vals.length; h++) { gainValue[h] = vals[h]; } } // DnD support disabled. DropTargetAdapter dnd = new DropTargetAdapter() { public void processDrop(Object data) { return; } }; DropTarget dt = new DropTarget(this, DnDConstants.ACTION_COPY, dnd, false); } /** * Return skin. * @return */ public Skin getSkin() { return ui; } /** * Set skin. * @param ui */ public void setSkin(Skin ui) { this.ui = ui; } /** * Set parent player. * @param mp */ public void setPlayer(PlayerUI mp) { player = mp; } public void loadUI() { log.info("Load EqualizerUI (EDT=" + SwingUtilities.isEventDispatchThread() + ")"); removeAll(); // Background ImageBorder border = new ImageBorder(); border.setImage(ui.getEqualizerImage()); setBorder(border); // On/Off add(ui.getAcEqOnOff(), ui.getAcEqOnOff().getConstraints()); ui.getAcEqOnOff().removeActionListener(this); ui.getAcEqOnOff().addActionListener(this); // Auto add(ui.getAcEqAuto(), ui.getAcEqAuto().getConstraints()); ui.getAcEqAuto().removeActionListener(this); ui.getAcEqAuto().addActionListener(this); // Sliders add(ui.getAcEqPresets(), ui.getAcEqPresets().getConstraints()); for (int i = 0; i < ui.getAcEqSliders().length; i++) { add(ui.getAcEqSliders()[i], ui.getAcEqSliders()[i].getConstraints()); ui.getAcEqSliders()[i].setValue(maxGain - gainValue[i]); ui.getAcEqSliders()[i].removeChangeListener(this); ui.getAcEqSliders()[i].addChangeListener(this); } if (ui.getSpline() != null) { ui.getSpline().setValues(gainValue); add(ui.getSpline(), ui.getSpline().getConstraints()); } // Popup menu on TitleBar mainpopup = new JPopupMenu(); String[] presets = { "Normal", "Classical", "Club", "Dance", "Full Bass", "Full Bass & Treble", "Full Treble", "Laptop", "Live", "Party", "Pop", "Reggae", "Rock", "Techno" }; JMenuItem mi; for (int p = 0; p < presets.length; p++) { mi = new JMenuItem(presets[p]); mi.removeActionListener(this); mi.addActionListener(this); mainpopup.add(mi); } ui.getAcEqPresets().removeActionListener(this); ui.getAcEqPresets().addActionListener(this); validate(); } /* (non-Javadoc) * @see javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent) */ public void stateChanged(ChangeEvent e) { for (int i = 0; i < ui.getAcEqSliders().length; i++) { gainValue[i] = maxGain - ui.getAcEqSliders()[i].getValue(); } if (ui.getSpline() != null) ui.getSpline().repaint(); // Apply equalizer values. synchronizeEqualizer(); } /** * Set bands array for equalizer. * * @param bands */ public void setBands(float[] bands) { this.bands = bands; } /** * Apply equalizer function. * * @param gains * @param min * @param max */ public void updateBands(int[] gains, int min, int max) { if ((gains != null) && (bands != null)) { int j = 0; float gvalj = (gains[j] * 2.0f / (max - min) * 1.0f) - 1.0f; float gvalj1 = (gains[j + 1] * 2.0f / (max - min) * 1.0f) - 1.0f; // Linear distribution : 10 values => 32 values. if (eqdist == LINEARDIST) { float a = (gvalj1 - gvalj) * 1.0f; float b = gvalj * 1.0f - (gvalj1 - gvalj) * j; // x=s*x' float s = (gains.length - 1) * 1.0f / (bands.length - 1) * 1.0f; for (int i = 0; i < bands.length; i++) { float ind = s * i; if (ind > (j + 1)) { j++; gvalj = (gains[j] * 2.0f / (max - min) * 1.0f) - 1.0f; gvalj1 = (gains[j + 1] * 2.0f / (max - min) * 1.0f) - 1.0f; a = (gvalj1 - gvalj) * 1.0f; b = gvalj * 1.0f - (gvalj1 - gvalj) * j; } // a*x+b bands[i] = a * i * 1.0f * s + b; } } // Over distribution : 10 values => 10 first value of 32 values. else if (eqdist == OVERDIST) { for (int i = 0; i < gains.length; i++) { bands[i] = (gains[i] * 2.0f / (max - min) * 1.0f) - 1.0f; } } } } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); log.debug("Action=" + cmd + " (EDT=" + SwingUtilities.isEventDispatchThread() + ")"); // On/Off if (cmd.equals(PlayerActionEvent.ACEQONOFF)) { if (ui.getAcEqOnOff().isSelected()) { config.setEqualizerOn(true); } else { config.setEqualizerOn(false); } synchronizeEqualizer(); } // Auto else if (cmd.equals(PlayerActionEvent.ACEQAUTO)) { if (ui.getAcEqAuto().isSelected()) { config.setEqualizerAuto(true); } else { config.setEqualizerAuto(false); } } // Presets else if (cmd.equals(PlayerActionEvent.ACEQPRESETS)) { if (e.getModifiers() == MouseEvent.BUTTON1_MASK) { mainpopup.show(this, ui.getAcEqPresets().getLocation().x, ui.getAcEqPresets().getLocation().y); } } else if (cmd.equals("Normal")) { updateSliders(PRESET_NORMAL); synchronizeEqualizer(); } else if (cmd.equals("Classical")) { updateSliders(PRESET_CLASSICAL); synchronizeEqualizer(); } else if (cmd.equals("Club")) { updateSliders(PRESET_CLUB); synchronizeEqualizer(); } else if (cmd.equals("Dance")) { updateSliders(PRESET_DANCE); synchronizeEqualizer(); } else if (cmd.equals("Full Bass")) { updateSliders(PRESET_FULLBASS); synchronizeEqualizer(); } else if (cmd.equals("Full Bass & Treble")) { updateSliders(PRESET_FULLBASSTREBLE); synchronizeEqualizer(); } else if (cmd.equals("Full Treble")) { updateSliders(PRESET_FULLTREBLE); synchronizeEqualizer(); } else if (cmd.equals("Laptop")) { updateSliders(PRESET_LAPTOP); synchronizeEqualizer(); } else if (cmd.equals("Live")) { updateSliders(PRESET_LIVE); synchronizeEqualizer(); } else if (cmd.equals("Party")) { updateSliders(PRESET_PARTY); synchronizeEqualizer(); } else if (cmd.equals("Pop")) { updateSliders(PRESET_POP); synchronizeEqualizer(); } else if (cmd.equals("Reggae")) { updateSliders(PRESET_REGGAE); synchronizeEqualizer(); } else if (cmd.equals("Rock")) { updateSliders(PRESET_ROCK); synchronizeEqualizer(); } else if (cmd.equals("Techno")) { updateSliders(PRESET_TECHNO); synchronizeEqualizer(); } } /** * Update sliders from gains array. * * @param gains */ public void updateSliders(int[] gains) { if (gains != null) { for (int i = 0; i < gains.length; i++) { gainValue[i + 1] = gains[i]; ui.getAcEqSliders()[i + 1].setValue(maxGain - gainValue[i + 1]); } } } /** * Apply equalizer values. */ public void synchronizeEqualizer() { config.setLastEqualizer(gainValue); if (config.isEqualizerOn()) { for (int j = 0; j < eqgains.length; j++) { eqgains[j] = -gainValue[j + 1] + maxGain; } updateBands(eqgains, minGain, maxGain); } else { for (int j = 0; j < eqgains.length; j++) { eqgains[j] = (maxGain - minGain) / 2; } updateBands(eqgains, minGain, maxGain); } } /** * Return equalizer bands distribution. * @return */ public int getEqdist() { return eqdist; } /** * Set equalizer bands distribution. * @param i */ public void setEqdist(int i) { eqdist = i; } /** * Simulates "On/Off" selection. */ public void pressOnOff() { ui.getAcEqOnOff().doClick(); } /** * Simulates "Auto" selection. */ public void pressAuto() { ui.getAcEqAuto().doClick(); } }
Java
/* * NaturalSpline. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.equalizer.ui; import java.awt.Polygon; public class NaturalSpline extends ControlCurve { public final int STEPS = 12; public NaturalSpline() { super(); } /* * calculates the natural cubic spline that interpolates y[0], y[1], ... * y[n] The first segment is returned as C[0].a + C[0].b*u + C[0].c*u^2 + * C[0].d*u^3 0<=u <1 the other segments are in C[1], C[2], ... C[n-1] */ Cubic[] calcNaturalCubic(int n, int[] x) { float[] gamma = new float[n + 1]; float[] delta = new float[n + 1]; float[] D = new float[n + 1]; int i; /* * We solve the equation [2 1 ] [D[0]] [3(x[1] - x[0]) ] |1 4 1 | |D[1]| * |3(x[2] - x[0]) | | 1 4 1 | | . | = | . | | ..... | | . | | . | | 1 4 * 1| | . | |3(x[n] - x[n-2])| [ 1 2] [D[n]] [3(x[n] - x[n-1])] * * by using row operations to convert the matrix to upper triangular and * then back sustitution. The D[i] are the derivatives at the knots. */ gamma[0] = 1.0f / 2.0f; for (i = 1; i < n; i++) { gamma[i] = 1 / (4 - gamma[i - 1]); } gamma[n] = 1 / (2 - gamma[n - 1]); delta[0] = 3 * (x[1] - x[0]) * gamma[0]; for (i = 1; i < n; i++) { delta[i] = (3 * (x[i + 1] - x[i - 1]) - delta[i - 1]) * gamma[i]; } delta[n] = (3 * (x[n] - x[n - 1]) - delta[n - 1]) * gamma[n]; D[n] = delta[n]; for (i = n - 1; i >= 0; i--) { D[i] = delta[i] - gamma[i] * D[i + 1]; } /* now compute the coefficients of the cubics */ Cubic[] C = new Cubic[n]; for (i = 0; i < n; i++) { C[i] = new Cubic((float) x[i], D[i], 3 * (x[i + 1] - x[i]) - 2 * D[i] - D[i + 1], 2 * (x[i] - x[i + 1]) + D[i] + D[i + 1]); } return C; } /** * Return a cubic spline. */ public Polygon getPolyline() { Polygon p = new Polygon(); if (pts.npoints >= 2) { Cubic[] X = calcNaturalCubic(pts.npoints - 1, pts.xpoints); Cubic[] Y = calcNaturalCubic(pts.npoints - 1, pts.ypoints); // very crude technique - just break each segment up into steps lines int x = (int) Math.round(X[0].eval(0)); int y = (int) Math.round(Y[0].eval(0)); p.addPoint(x, boundY(y)); for (int i = 0; i < X.length; i++) { for (int j = 1; j <= STEPS; j++) { float u = j / (float) STEPS; x = Math.round(X[i].eval(u)); y = Math.round(Y[i].eval(u)); p.addPoint(x, boundY(y)); } } } return p; } }
Java
/* * SplinePanel. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.equalizer.ui; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.Polygon; import javax.swing.JPanel; import javazoom.jlgui.player.amp.skin.AbsoluteConstraints; public class SplinePanel extends JPanel { private AbsoluteConstraints constraints = null; private Image backgroundImage = null; private Image barImage = null; private int[] values = null; private Color[] gradient = null; public SplinePanel() { super(); setDoubleBuffered(true); setLayout(null); } public Color[] getGradient() { return gradient; } public void setGradient(Color[] gradient) { this.gradient = gradient; } public void setConstraints(AbsoluteConstraints cnts) { constraints = cnts; } public AbsoluteConstraints getConstraints() { return constraints; } public Image getBarImage() { return barImage; } public void setBarImage(Image barImage) { this.barImage = barImage; } public Image getBackgroundImage() { return backgroundImage; } public void setBackgroundImage(Image backgroundImage) { this.backgroundImage = backgroundImage; } public int[] getValues() { return values; } public void setValues(int[] values) { this.values = values; } /* (non-Javadoc) * @see javax.swing.JComponent#paintComponent(java.awt.Graphics) */ public void paintComponent(Graphics g) { if (backgroundImage != null) g.drawImage(backgroundImage, 0, 0, null); if (barImage != null) g.drawImage(barImage, 0, getHeight()/2, null); if ((values != null) && (values.length > 0)) { NaturalSpline curve = new NaturalSpline(); float dx = 1.0f * getWidth() / (values.length - 2); int h = getHeight(); curve.setMaxHeight(h); curve.setMinHeight(0); for (int i = 1; i < values.length; i++) { int x1 = (int) Math.round(dx * (i - 1)); int y1 = ((int) Math.round((h * values[i] / 100))); y1 = curve.boundY(y1); curve.addPoint(x1, y1); } Polygon spline = curve.getPolyline(); if (gradient != null) { for (int i=0;i<(spline.npoints-1);i++) { g.setColor(gradient[spline.ypoints[i]]); g.drawLine(spline.xpoints[i], spline.ypoints[i],spline.xpoints[i+1], spline.ypoints[i+1]); } } else { g.drawPolyline(spline.xpoints, spline.ypoints, spline.npoints); } } } }
Java
/* * ControlCurve. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.equalizer.ui; import java.awt.Polygon; public abstract class ControlCurve { static final int EPSILON = 36; /* square of distance for picking */ protected Polygon pts; protected int selection = -1; int maxHeight = -1; int minHeight = -1; public ControlCurve() { pts = new Polygon(); } public int boundY(int y) { int ny = y; if ((minHeight >= 0) && (y < minHeight)) { ny = 0; } if ((maxHeight >= 0) && (y >= maxHeight)) { ny = maxHeight - 1; } return ny; } public void setMaxHeight(int h) { maxHeight = h; } public void setMinHeight(int h) { minHeight = h; } /** * Return index of control point near to (x,y) or -1 if nothing near. * @param x * @param y * @return */ public int selectPoint(int x, int y) { int mind = Integer.MAX_VALUE; selection = -1; for (int i = 0; i < pts.npoints; i++) { int d = sqr(pts.xpoints[i] - x) + sqr(pts.ypoints[i] - y); if (d < mind && d < EPSILON) { mind = d; selection = i; } } return selection; } /** * Square of an int. * @param x * @return */ static int sqr(int x) { return x * x; } /** * Add a control point, return index of new control point. * @param x * @param y * @return */ public int addPoint(int x, int y) { pts.addPoint(x, y); return selection = pts.npoints - 1; } /** * Set selected control point. * @param x * @param y */ public void setPoint(int x, int y) { if (selection >= 0) { pts.xpoints[selection] = x; pts.ypoints[selection] = y; } } /** * Remove selected control point. */ public void removePoint() { if (selection >= 0) { pts.npoints--; for (int i = selection; i < pts.npoints; i++) { pts.xpoints[i] = pts.xpoints[i + 1]; pts.ypoints[i] = pts.ypoints[i + 1]; } } } public abstract Polygon getPolyline(); }
Java
/* * 21.04.2004 Original verion. davagin@udm.ru. *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.tag; import org.tritonus.share.sampled.TAudioFormat; import org.tritonus.share.sampled.file.TAudioFileFormat; import javax.sound.sampled.AudioFileFormat; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.UnsupportedAudioFileException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Calendar; import java.util.Date; import java.util.Map; import java.util.Vector; /** * This class gives information (audio format and comments) about APE file or URL. */ public class APEInfo implements TagInfo { protected int channels = -1; protected int bitspersample = -1; protected int samplerate = -1; protected int bitrate = -1; protected int version = -1; protected String compressionlevel = null; protected int totalframes = -1; protected int blocksperframe = -1; protected int finalframeblocks = -1; protected int totalblocks = -1; protected int peaklevel = -1; protected long duration = -1; protected String author = null; protected String title = null; protected String copyright = null; protected Date date = null; protected String comment = null; protected String track = null; protected String genre = null; protected String album = null; protected long size = 0; protected String location = null; /** * Constructor. */ public APEInfo() { super(); } /** * Load and parse APE info from File. * * @param input * @throws IOException */ public void load(File input) throws IOException, UnsupportedAudioFileException { size = input.length(); location = input.getPath(); loadInfo(input); } /** * Load and parse APE info from URL. * * @param input * @throws IOException * @throws UnsupportedAudioFileException */ public void load(URL input) throws IOException, UnsupportedAudioFileException { location = input.toString(); loadInfo(input); } /** * Load and parse APE info from InputStream. * * @param input * @throws IOException * @throws UnsupportedAudioFileException */ public void load(InputStream input) throws IOException, UnsupportedAudioFileException { loadInfo(input); } /** * Load APE info from input stream. * * @param input * @throws IOException * @throws UnsupportedAudioFileException */ protected void loadInfo(InputStream input) throws IOException, UnsupportedAudioFileException { AudioFileFormat aff = AudioSystem.getAudioFileFormat(input); loadInfo(aff); } /** * Load APE info from file. * * @param file * @throws IOException * @throws UnsupportedAudioFileException */ protected void loadInfo(File file) throws IOException, UnsupportedAudioFileException { AudioFileFormat aff = AudioSystem.getAudioFileFormat(file); loadInfo(aff); } /** * Load APE info from AudioFileFormat. * * @param aff */ protected void loadInfo(AudioFileFormat aff) throws UnsupportedAudioFileException { String type = aff.getType().toString(); if (!type.equalsIgnoreCase("Monkey's Audio (ape)") && !type.equalsIgnoreCase("Monkey's Audio (mac)")) throw new UnsupportedAudioFileException("Not APE audio format"); if (aff instanceof TAudioFileFormat) { Map props = ((TAudioFileFormat) aff).properties(); if (props.containsKey("duration")) duration = ((Long) props.get("duration")).longValue(); if (props.containsKey("author")) author = (String) props.get("author"); if (props.containsKey("title")) title = (String) props.get("title"); if (props.containsKey("copyright")) copyright = (String) props.get("copyright"); if (props.containsKey("date")) date = (Date) props.get("date"); if (props.containsKey("comment")) comment = (String) props.get("comment"); if (props.containsKey("album")) album = (String) props.get("album"); if (props.containsKey("track")) track = (String) props.get("track"); if (props.containsKey("genre")) genre = (String) props.get("genre"); AudioFormat af = aff.getFormat(); channels = af.getChannels(); samplerate = (int) af.getSampleRate(); bitspersample = af.getSampleSizeInBits(); if (af instanceof TAudioFormat) { props = ((TAudioFormat) af).properties(); if (props.containsKey("bitrate")) bitrate = ((Integer) props.get("bitrate")).intValue(); if (props.containsKey("ape.version")) version = ((Integer) props.get("ape.version")).intValue(); if (props.containsKey("ape.compressionlevel")) { int cl = ((Integer) props.get("ape.compressionlevel")).intValue(); switch (cl) { case 1000: compressionlevel = "Fast"; break; case 2000: compressionlevel = "Normal"; break; case 3000: compressionlevel = "High"; break; case 4000: compressionlevel = "Extra High"; break; case 5000: compressionlevel = "Insane"; break; } } if (props.containsKey("ape.totalframes")) totalframes = ((Integer) props.get("ape.totalframes")).intValue(); if (props.containsKey("ape.blocksperframe")) totalframes = ((Integer) props.get("ape.blocksperframe")).intValue(); if (props.containsKey("ape.finalframeblocks")) finalframeblocks = ((Integer) props.get("ape.finalframeblocks")).intValue(); if (props.containsKey("ape.totalblocks")) totalblocks = ((Integer) props.get("ape.totalblocks")).intValue(); if (props.containsKey("ape.peaklevel")) peaklevel = ((Integer) props.get("ape.peaklevel")).intValue(); } } } /** * Load APE info from URL. * * @param input * @throws IOException * @throws UnsupportedAudioFileException */ protected void loadInfo(URL input) throws IOException, UnsupportedAudioFileException { AudioFileFormat aff = AudioSystem.getAudioFileFormat(input); loadInfo(aff); } public long getSize() { return size; } public String getLocation() { return location; } public int getVersion() { return version; } public String getCompressionlevel() { return compressionlevel; } public int getTotalframes() { return totalframes; } public int getBlocksperframe() { return blocksperframe; } public int getFinalframeblocks() { return finalframeblocks; } public int getChannels() { return channels; } public int getSamplingRate() { return samplerate; } public int getBitsPerSample() { return bitspersample; } public int getTotalblocks() { return totalblocks; } public long getPlayTime() { return duration / 1000; } public int getBitRate() { return bitrate * 1000; } public int getPeaklevel() { return peaklevel; } public int getTrack() { int t; try { t = Integer.parseInt(track); } catch (Exception e) { t = -1; } return t; } public String getYear() { if (date != null) { Calendar c = Calendar.getInstance(); c.setTime(date); return String.valueOf(c.get(Calendar.YEAR)); } return null; } public String getGenre() { return genre; } public String getTitle() { return title; } public String getArtist() { return author; } public String getAlbum() { return album; } public Vector getComment() { if (comment != null) { Vector c = new Vector(); c.add(comment); return c; } return null; } public String getCopyright() { return copyright; } }
Java
/* * TagInfo. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.tag; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Vector; import javax.sound.sampled.UnsupportedAudioFileException; /** * This interface define needed features for song information. * Adapted from Scott Pennell interface. */ public interface TagInfo { public void load(InputStream input) throws IOException, UnsupportedAudioFileException; public void load(URL input) throws IOException, UnsupportedAudioFileException; public void load(File input) throws IOException, UnsupportedAudioFileException; /** * Get Sampling Rate * * @return sampling rate */ public int getSamplingRate(); /** * Get Nominal Bitrate * * @return bitrate in bps */ public int getBitRate(); /** * Get channels. * * @return channels */ public int getChannels(); /** * Get play time in seconds. * * @return play time in seconds */ public long getPlayTime(); /** * Get the title of the song. * * @return the title of the song */ public String getTitle(); /** * Get the artist that performed the song * * @return the artist that performed the song */ public String getArtist(); /** * Get the name of the album upon which the song resides * * @return the album name */ public String getAlbum(); /** * Get the track number of this track on the album * * @return the track number */ public int getTrack(); /** * Get the genre string of the music * * @return the genre string */ public String getGenre(); /** * Get the year the track was released * * @return the year the track was released */ public String getYear(); /** * Get any comments provided about the song * * @return the comments */ public Vector getComment(); }
Java
/* * 21.04.2004 Original verion. davagin@udm.ru. *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.tag; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Vector; import javax.sound.sampled.AudioFileFormat; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.UnsupportedAudioFileException; /** * This class gives information (audio format and comments) about Flac file or URL. */ public class FlacInfo implements TagInfo { protected int channels = -1; protected int bitspersample = -1; protected int samplerate = -1; protected long size = 0; protected String location = null; /** * Constructor. */ public FlacInfo() { super(); } /** * Load and parse Flac info from File. * * @param input * @throws IOException */ public void load(File input) throws IOException, UnsupportedAudioFileException { size = input.length(); location = input.getPath(); loadInfo(input); } /** * Load and parse Flac info from URL. * * @param input * @throws IOException * @throws UnsupportedAudioFileException */ public void load(URL input) throws IOException, UnsupportedAudioFileException { location = input.toString(); loadInfo(input); } /** * Load and parse Flac info from InputStream. * * @param input * @throws IOException * @throws UnsupportedAudioFileException */ public void load(InputStream input) throws IOException, UnsupportedAudioFileException { loadInfo(input); } /** * Load Flac info from input stream. * * @param input * @throws IOException * @throws UnsupportedAudioFileException */ protected void loadInfo(InputStream input) throws IOException, UnsupportedAudioFileException { AudioFileFormat aff = AudioSystem.getAudioFileFormat(input); loadInfo(aff); } /** * Load Flac info from file. * * @param file * @throws IOException * @throws UnsupportedAudioFileException */ protected void loadInfo(File file) throws IOException, UnsupportedAudioFileException { AudioFileFormat aff = AudioSystem.getAudioFileFormat(file); loadInfo(aff); } /** * Load Flac info from AudioFileFormat. * * @param aff */ protected void loadInfo(AudioFileFormat aff) throws UnsupportedAudioFileException { String type = aff.getType().toString(); if (!type.equalsIgnoreCase("flac")) throw new UnsupportedAudioFileException("Not Flac audio format"); AudioFormat af = aff.getFormat(); channels = af.getChannels(); samplerate = (int) af.getSampleRate(); bitspersample = af.getSampleSizeInBits(); } /** * Load Flac info from URL. * * @param input * @throws IOException * @throws UnsupportedAudioFileException */ protected void loadInfo(URL input) throws IOException, UnsupportedAudioFileException { AudioFileFormat aff = AudioSystem.getAudioFileFormat(input); loadInfo(aff); } public long getSize() { return size; } public String getLocation() { return location; } public int getChannels() { return channels; } public int getSamplingRate() { return samplerate; } public int getBitsPerSample() { return bitspersample; } public Vector getComment() { return null; } public String getYear() { return null; } public String getGenre() { return null; } public int getTrack() { return -1; } public String getAlbum() { return null; } public String getArtist() { return null; } public String getTitle() { return null; } public long getPlayTime() { return -1; } public int getBitRate() { return -1; } }
Java
/* * MpegInfo. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.tag; import org.tritonus.share.sampled.file.TAudioFileFormat; import javax.sound.sampled.AudioFileFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.UnsupportedAudioFileException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Iterator; import java.util.Map; import java.util.Vector; /** * This class gives information (audio format and comments) about MPEG file or URL. */ public class MpegInfo implements TagInfo { protected int channels = -1; protected String channelsMode = null; protected String version = null; protected int rate = 0; protected String layer = null; protected String emphasis = null; protected int nominalbitrate = 0; protected long total = 0; protected String vendor = null; protected String location = null; protected long size = 0; protected boolean copyright = false; protected boolean crc = false; protected boolean original = false; protected boolean priv = false; protected boolean vbr = false; protected int track = -1; protected String year = null; protected String genre = null; protected String title = null; protected String artist = null; protected String album = null; protected Vector comments = null; /** * Constructor. */ public MpegInfo() { super(); } /** * Load and parse MPEG info from File. * * @param input * @throws IOException */ public void load(File input) throws IOException, UnsupportedAudioFileException { size = input.length(); location = input.getPath(); loadInfo(input); } /** * Load and parse MPEG info from URL. * * @param input * @throws IOException * @throws UnsupportedAudioFileException */ public void load(URL input) throws IOException, UnsupportedAudioFileException { location = input.toString(); loadInfo(input); } /** * Load and parse MPEG info from InputStream. * * @param input * @throws IOException * @throws UnsupportedAudioFileException */ public void load(InputStream input) throws IOException, UnsupportedAudioFileException { loadInfo(input); } /** * Load info from input stream. * * @param input * @throws IOException * @throws UnsupportedAudioFileException */ protected void loadInfo(InputStream input) throws IOException, UnsupportedAudioFileException { AudioFileFormat aff = AudioSystem.getAudioFileFormat(input); loadInfo(aff); } /** * Load MP3 info from file. * * @param file * @throws IOException * @throws UnsupportedAudioFileException */ protected void loadInfo(File file) throws IOException, UnsupportedAudioFileException { AudioFileFormat aff = AudioSystem.getAudioFileFormat(file); loadInfo(aff); } /** * Load info from AudioFileFormat. * * @param aff */ protected void loadInfo(AudioFileFormat aff) throws UnsupportedAudioFileException { String type = aff.getType().toString(); if (!type.equalsIgnoreCase("mp3")) throw new UnsupportedAudioFileException("Not MP3 audio format"); if (aff instanceof TAudioFileFormat) { Map props = ((TAudioFileFormat) aff).properties(); if (props.containsKey("mp3.channels")) channels = ((Integer) props.get("mp3.channels")).intValue(); if (props.containsKey("mp3.frequency.hz")) rate = ((Integer) props.get("mp3.frequency.hz")).intValue(); if (props.containsKey("mp3.bitrate.nominal.bps")) nominalbitrate = ((Integer) props.get("mp3.bitrate.nominal.bps")).intValue(); if (props.containsKey("mp3.version.layer")) layer = "Layer " + props.get("mp3.version.layer"); if (props.containsKey("mp3.version.mpeg")) { version = (String) props.get("mp3.version.mpeg"); if (version.equals("1")) version = "MPEG1"; else if (version.equals("2")) version = "MPEG2-LSF"; else if (version.equals("2.5")) version = "MPEG2.5-LSF"; } if (props.containsKey("mp3.mode")) { int mode = ((Integer) props.get("mp3.mode")).intValue(); if (mode == 0) channelsMode = "Stereo"; else if (mode == 1) channelsMode = "Joint Stereo"; else if (mode == 2) channelsMode = "Dual Channel"; else if (mode == 3) channelsMode = "Single Channel"; } if (props.containsKey("mp3.crc")) crc = ((Boolean) props.get("mp3.crc")).booleanValue(); if (props.containsKey("mp3.vbr")) vbr = ((Boolean) props.get("mp3.vbr")).booleanValue(); if (props.containsKey("mp3.copyright")) copyright = ((Boolean) props.get("mp3.copyright")).booleanValue(); if (props.containsKey("mp3.original")) original = ((Boolean) props.get("mp3.original")).booleanValue(); emphasis = "none"; if (props.containsKey("title")) title = (String) props.get("title"); if (props.containsKey("author")) artist = (String) props.get("author"); if (props.containsKey("album")) album = (String) props.get("album"); if (props.containsKey("date")) year = (String) props.get("date"); if (props.containsKey("duration")) total = (long) Math.round((((Long) props.get("duration")).longValue()) / 1000000); if (props.containsKey("mp3.id3tag.genre")) genre = (String) props.get("mp3.id3tag.genre"); if (props.containsKey("mp3.id3tag.track")) { try { track = Integer.parseInt((String) props.get("mp3.id3tag.track")); } catch (NumberFormatException e1) { // Not a number } } } } /** * Load MP3 info from URL. * * @param input * @throws IOException * @throws UnsupportedAudioFileException */ protected void loadInfo(URL input) throws IOException, UnsupportedAudioFileException { AudioFileFormat aff = AudioSystem.getAudioFileFormat(input); loadInfo(aff); loadShoutastInfo(aff); } /** * Load Shoutcast info from AudioFileFormat. * * @param aff * @throws IOException * @throws UnsupportedAudioFileException */ protected void loadShoutastInfo(AudioFileFormat aff) throws IOException, UnsupportedAudioFileException { String type = aff.getType().toString(); if (!type.equalsIgnoreCase("mp3")) throw new UnsupportedAudioFileException("Not MP3 audio format"); if (aff instanceof TAudioFileFormat) { Map props = ((TAudioFileFormat) aff).properties(); // Try shoutcast meta data (if any). Iterator it = props.keySet().iterator(); comments = new Vector(); while (it.hasNext()) { String key = (String) it.next(); if (key.startsWith("mp3.shoutcast.metadata.")) { String value = (String) props.get(key); key = key.substring(23, key.length()); if (key.equalsIgnoreCase("icy-name")) { title = value; } else if (key.equalsIgnoreCase("icy-genre")) { genre = value; } else { comments.add(key + "=" + value); } } } } } public boolean getVBR() { return vbr; } public int getChannels() { return channels; } public String getVersion() { return version; } public String getEmphasis() { return emphasis; } public boolean getCopyright() { return copyright; } public boolean getCRC() { return crc; } public boolean getOriginal() { return original; } public String getLayer() { return layer; } public long getSize() { return size; } public String getLocation() { return location; } /*-- TagInfo Implementation --*/ public int getSamplingRate() { return rate; } public int getBitRate() { return nominalbitrate; } public long getPlayTime() { return total; } public String getTitle() { return title; } public String getArtist() { return artist; } public String getAlbum() { return album; } public int getTrack() { return track; } public String getGenre() { return genre; } public Vector getComment() { return comments; } public String getYear() { return year; } /** * Get channels mode. * * @return channels mode */ public String getChannelsMode() { return channelsMode; } }
Java
/* * TagInfoFactory. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.tag; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.net.MalformedURLException; import java.net.URL; import javax.sound.sampled.UnsupportedAudioFileException; import javazoom.jlgui.player.amp.tag.ui.APEDialog; import javazoom.jlgui.player.amp.tag.ui.EmptyDialog; import javazoom.jlgui.player.amp.tag.ui.FlacDialog; import javazoom.jlgui.player.amp.tag.ui.MpegDialog; import javazoom.jlgui.player.amp.tag.ui.OggVorbisDialog; import javazoom.jlgui.player.amp.tag.ui.TagInfoDialog; import javazoom.jlgui.player.amp.util.Config; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * This class is a factory for TagInfo and TagInfoDialog. * It allows to any plug custom TagIngfo parser matching to TagInfo * interface. */ public class TagInfoFactory { private static Log log = LogFactory.getLog(TagInfoFactory.class); private static TagInfoFactory instance = null; private Class MpegTagInfoClass = null; private Class VorbisTagInfoClass = null; private Class APETagInfoClass = null; private Class FlacTagInfoClass = null; private Config conf = null; private TagInfoFactory() { super(); conf = Config.getInstance(); String classname = conf.getMpegTagInfoClassName(); MpegTagInfoClass = getTagInfoImpl(classname); if (MpegTagInfoClass == null) { log.error("Error : TagInfo implementation not found in " + classname + " hierarchy"); MpegTagInfoClass = getTagInfoImpl("javazoom.jlgui.player.amp.tag.MpegInfo"); } classname = conf.getOggVorbisTagInfoClassName(); VorbisTagInfoClass = getTagInfoImpl(classname); if (VorbisTagInfoClass == null) { log.error("Error : TagInfo implementation not found in " + classname + " hierarchy"); VorbisTagInfoClass = getTagInfoImpl("javazoom.jlgui.player.amp.tag.OggVorbisInfo"); } classname = conf.getAPETagInfoClassName(); APETagInfoClass = getTagInfoImpl(classname); if (APETagInfoClass == null) { log.error("Error : TagInfo implementation not found in " + classname + " hierarchy"); APETagInfoClass = getTagInfoImpl("javazoom.jlgui.player.amp.tag.APEInfo"); } classname = conf.getFlacTagInfoClassName(); FlacTagInfoClass = getTagInfoImpl(classname); if (FlacTagInfoClass == null) { log.error("Error : TagInfo implementation not found in " + classname + " hierarchy"); FlacTagInfoClass = getTagInfoImpl("javazoom.jlgui.player.amp.tag.FlacInfo"); } } public static synchronized TagInfoFactory getInstance() { if (instance == null) { instance = new TagInfoFactory(); } return instance; } /** * Return tag info from a given URL. * * @param location * @return TagInfo structure for given URL */ public TagInfo getTagInfo(URL location) { TagInfo taginfo; try { taginfo = getTagInfoImplInstance(MpegTagInfoClass); taginfo.load(location); } catch (IOException ex) { log.debug(ex); taginfo = null; } catch (UnsupportedAudioFileException ex) { // Not Mpeg Format taginfo = null; } if (taginfo == null) { // Check Ogg Vorbis format. try { taginfo = getTagInfoImplInstance(VorbisTagInfoClass); taginfo.load(location); } catch (UnsupportedAudioFileException ex) { // Not Ogg Vorbis Format taginfo = null; } catch (IOException ex) { log.debug(ex); taginfo = null; } } if (taginfo == null) { // Check APE format. try { taginfo = getTagInfoImplInstance(APETagInfoClass); taginfo.load(location); } catch (UnsupportedAudioFileException ex) { // Not APE Format taginfo = null; } catch (IOException ex) { log.debug(ex); taginfo = null; } } if (taginfo == null) { // Check Flac format. try { taginfo = getTagInfoImplInstance(FlacTagInfoClass); taginfo.load(location); } catch (UnsupportedAudioFileException ex) { // Not Flac Format taginfo = null; } catch (IOException ex) { log.debug(ex); taginfo = null; } } return taginfo; } /** * Return tag info from a given String. * * @param location * @return TagInfo structure for given location */ public TagInfo getTagInfo(String location) { if (Config.startWithProtocol(location)) { try { return getTagInfo(new URL(location)); } catch (MalformedURLException e) { return null; } } else { return getTagInfo(new File(location)); } } /** * Get TagInfo for given file. * * @param location * @return TagInfo structure for given location */ public TagInfo getTagInfo(File location) { TagInfo taginfo; // Check Mpeg format. try { taginfo = getTagInfoImplInstance(MpegTagInfoClass); taginfo.load(location); } catch (IOException ex) { log.debug(ex); taginfo = null; } catch (UnsupportedAudioFileException ex) { // Not Mpeg Format taginfo = null; } if (taginfo == null) { // Check Ogg Vorbis format. try { //taginfo = new OggVorbisInfo(location); taginfo = getTagInfoImplInstance(VorbisTagInfoClass); taginfo.load(location); } catch (UnsupportedAudioFileException ex) { // Not Ogg Vorbis Format taginfo = null; } catch (IOException ex) { log.debug(ex); taginfo = null; } } if (taginfo == null) { // Check APE format. try { taginfo = getTagInfoImplInstance(APETagInfoClass); taginfo.load(location); } catch (UnsupportedAudioFileException ex) { // Not APE Format taginfo = null; } catch (IOException ex) { log.debug(ex); taginfo = null; } } if (taginfo == null) { // Check Flac format. try { taginfo = getTagInfoImplInstance(FlacTagInfoClass); taginfo.load(location); } catch (UnsupportedAudioFileException ex) { // Not Flac Format taginfo = null; } catch (IOException ex) { log.debug(ex); taginfo = null; } } return taginfo; } /** * Return dialog (graphical) to display tag info. * * @param taginfo * @return TagInfoDialog for given TagInfo */ public TagInfoDialog getTagInfoDialog(TagInfo taginfo) { TagInfoDialog dialog; if (taginfo != null) { if (taginfo instanceof OggVorbisInfo) { dialog = new OggVorbisDialog(conf.getTopParent(), "OggVorbis info", (OggVorbisInfo) taginfo); } else if (taginfo instanceof MpegInfo) { dialog = new MpegDialog(conf.getTopParent(), "Mpeg info", (MpegInfo) taginfo); } else if (taginfo instanceof APEInfo) { dialog = new APEDialog(conf.getTopParent(), "Ape info", (APEInfo) taginfo); } else if (taginfo instanceof FlacInfo) { dialog = new FlacDialog(conf.getTopParent(), "Flac info", (FlacInfo) taginfo); } else { dialog = new EmptyDialog(conf.getTopParent(), "No info", taginfo); } } else { dialog = new EmptyDialog(conf.getTopParent(), "No info", null); } return dialog; } /** * Load and check class implementation from classname. * * @param classname * @return TagInfo implementation for given class name */ public Class getTagInfoImpl(String classname) { Class aClass = null; boolean interfaceFound = false; if (classname != null) { try { aClass = Class.forName(classname); Class superClass = aClass; // Looking for TagInfo interface implementation. while (superClass != null) { Class[] interfaces = superClass.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { if ((interfaces[i].getName()).equals("javazoom.jlgui.player.amp.tag.TagInfo")) { interfaceFound = true; break; } } if (interfaceFound) break; superClass = superClass.getSuperclass(); } if (interfaceFound) log.info(classname + " loaded"); else log.info(classname + " not loaded"); } catch (ClassNotFoundException e) { log.error("Error : " + classname + " : " + e.getMessage()); } } return aClass; } /** * Return new instance of given class. * * @param aClass * @return TagInfo for given class */ public TagInfo getTagInfoImplInstance(Class aClass) { TagInfo instance = null; if (aClass != null) { try { Class[] argsClass = new Class[] {}; Constructor c = aClass.getConstructor(argsClass); instance = (TagInfo) (c.newInstance(null)); } catch (Exception e) { log.error("Cannot Instanciate : " + aClass.getName() + " : " + e.getMessage()); } } return instance; } }
Java
/* * OggVorbisInfo. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.tag; import org.tritonus.share.sampled.file.TAudioFileFormat; import javax.sound.sampled.AudioFileFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.UnsupportedAudioFileException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Map; import java.util.Vector; /** * This class gives information (audio format and comments) about Ogg Vorbis file or URL. */ public class OggVorbisInfo implements TagInfo { protected int serial = 0; protected int channels = 0; protected int version = 0; protected int rate = 0; protected int minbitrate = 0; protected int maxbitrate = 0; protected int averagebitrate = 0; protected int nominalbitrate = 0; protected long totalms = 0; protected String vendor = ""; protected String location = null; protected long size = 0; protected int track = -1; protected String year = null; protected String genre = null; protected String title = null; protected String artist = null; protected String album = null; protected Vector comments = new Vector(); /** * Constructor. */ public OggVorbisInfo() { super(); } /** * Load and parse Ogg Vorbis info from File. * * @param input * @throws IOException */ public void load(File input) throws IOException, UnsupportedAudioFileException { size = input.length(); location = input.getPath(); loadInfo(input); } /** * Load and parse Ogg Vorbis info from URL. * * @param input * @throws IOException * @throws UnsupportedAudioFileException */ public void load(URL input) throws IOException, UnsupportedAudioFileException { location = input.toString(); loadInfo(input); } /** * Load and parse Ogg Vorbis info from InputStream. * * @param input * @throws IOException * @throws UnsupportedAudioFileException */ public void load(InputStream input) throws IOException, UnsupportedAudioFileException { loadInfo(input); } /** * Load info from input stream. * * @param input * @throws IOException * @throws UnsupportedAudioFileException */ protected void loadInfo(InputStream input) throws IOException, UnsupportedAudioFileException { AudioFileFormat aff = AudioSystem.getAudioFileFormat(input); loadInfo(aff); } /** * Load Ogg Vorbis info from file. * * @param file * @throws IOException * @throws UnsupportedAudioFileException */ protected void loadInfo(File file) throws IOException, UnsupportedAudioFileException { AudioFileFormat aff = AudioSystem.getAudioFileFormat(file); loadInfo(aff); } /** * Load Ogg Vorbis info from URL. * * @param input * @throws IOException * @throws UnsupportedAudioFileException */ protected void loadInfo(URL input) throws IOException, UnsupportedAudioFileException { AudioFileFormat aff = AudioSystem.getAudioFileFormat(input); loadInfo(aff); loadExtendedInfo(aff); } /** * Load info from AudioFileFormat. * * @param aff * @throws UnsupportedAudioFileException */ protected void loadInfo(AudioFileFormat aff) throws UnsupportedAudioFileException { String type = aff.getType().toString(); if (!type.equalsIgnoreCase("ogg")) throw new UnsupportedAudioFileException("Not Ogg Vorbis audio format"); if (aff instanceof TAudioFileFormat) { Map props = ((TAudioFileFormat) aff).properties(); if (props.containsKey("ogg.channels")) channels = ((Integer) props.get("ogg.channels")).intValue(); if (props.containsKey("ogg.frequency.hz")) rate = ((Integer) props.get("ogg.frequency.hz")).intValue(); if (props.containsKey("ogg.bitrate.nominal.bps")) nominalbitrate = ((Integer) props.get("ogg.bitrate.nominal.bps")).intValue(); averagebitrate = nominalbitrate; if (props.containsKey("ogg.bitrate.max.bps")) maxbitrate = ((Integer) props.get("ogg.bitrate.max.bps")).intValue(); if (props.containsKey("ogg.bitrate.min.bps")) minbitrate = ((Integer) props.get("ogg.bitrate.min.bps")).intValue(); if (props.containsKey("ogg.version")) version = ((Integer) props.get("ogg.version")).intValue(); if (props.containsKey("ogg.serial")) serial = ((Integer) props.get("ogg.serial")).intValue(); if (props.containsKey("ogg.comment.encodedby")) vendor = (String) props.get("ogg.comment.encodedby"); if (props.containsKey("copyright")) comments.add((String) props.get("copyright")); if (props.containsKey("title")) title = (String) props.get("title"); if (props.containsKey("author")) artist = (String) props.get("author"); if (props.containsKey("album")) album = (String) props.get("album"); if (props.containsKey("date")) year = (String) props.get("date"); if (props.containsKey("comment")) comments.add((String) props.get("comment")); if (props.containsKey("duration")) totalms = (long) Math.round((((Long) props.get("duration")).longValue()) / 1000000); if (props.containsKey("ogg.comment.genre")) genre = (String) props.get("ogg.comment.genre"); if (props.containsKey("ogg.comment.track")) { try { track = Integer.parseInt((String) props.get("ogg.comment.track")); } catch (NumberFormatException e1) { // Not a number } } if (props.containsKey("ogg.comment.ext.1")) comments.add((String) props.get("ogg.comment.ext.1")); if (props.containsKey("ogg.comment.ext.2")) comments.add((String) props.get("ogg.comment.ext.2")); if (props.containsKey("ogg.comment.ext.3")) comments.add((String) props.get("ogg.comment.ext.3")); } } /** * Load extended info from AudioFileFormat. * * @param aff * @throws IOException * @throws UnsupportedAudioFileException */ protected void loadExtendedInfo(AudioFileFormat aff) throws IOException, UnsupportedAudioFileException { String type = aff.getType().toString(); if (!type.equalsIgnoreCase("ogg")) throw new UnsupportedAudioFileException("Not Ogg Vorbis audio format"); if (aff instanceof TAudioFileFormat) { //Map props = ((TAudioFileFormat) aff).properties(); // How to load icecast meta data (if any) ?? } } public int getSerial() { return serial; } public int getChannels() { return channels; } public int getVersion() { return version; } public int getMinBitrate() { return minbitrate; } public int getMaxBitrate() { return maxbitrate; } public int getAverageBitrate() { return averagebitrate; } public long getSize() { return size; } public String getVendor() { return vendor; } public String getLocation() { return location; } /*-- TagInfo Implementation --*/ public int getSamplingRate() { return rate; } public int getBitRate() { return nominalbitrate; } public long getPlayTime() { return totalms; } public String getTitle() { return title; } public String getArtist() { return artist; } public String getAlbum() { return album; } public int getTrack() { return track; } public String getGenre() { return genre; } public Vector getComment() { return comments; } public String getYear() { return year; } }
Java
/* * FlacDialog. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.tag.ui; import java.text.DecimalFormat; import javax.swing.JFrame; import javazoom.jlgui.player.amp.tag.FlacInfo; /** * FlacDialog class implements a DialogBox to diplay Flac info. */ public class FlacDialog extends TagInfoDialog { private FlacInfo _flacinfo = null; /** * Creates new form FlacDialog */ public FlacDialog(JFrame parent, String title, FlacInfo mi) { super(parent, title); initComponents(); _flacinfo = mi; int size = _flacinfo.getLocation().length(); locationLabel.setText(size > 50 ? ("..." + _flacinfo.getLocation().substring(size - 50)) : _flacinfo.getLocation()); if ((_flacinfo.getTitle() != null) && (!_flacinfo.getTitle().equals(""))) textField.append("Title=" + _flacinfo.getTitle() + "\n"); if ((_flacinfo.getArtist() != null) && (!_flacinfo.getArtist().equals(""))) textField.append("Artist=" + _flacinfo.getArtist() + "\n"); if ((_flacinfo.getAlbum() != null) && (!_flacinfo.getAlbum().equals(""))) textField.append("Album=" + _flacinfo.getAlbum() + "\n"); if (_flacinfo.getTrack() > 0) textField.append("Track=" + _flacinfo.getTrack() + "\n"); if ((_flacinfo.getYear() != null) && (!_flacinfo.getYear().equals(""))) textField.append("Year=" + _flacinfo.getYear() + "\n"); if ((_flacinfo.getGenre() != null) && (!_flacinfo.getGenre().equals(""))) textField.append("Genre=" + _flacinfo.getGenre() + "\n"); java.util.List comments = _flacinfo.getComment(); if (comments != null) { for (int i = 0; i < comments.size(); i++) textField.append(comments.get(i) + "\n"); } DecimalFormat df = new DecimalFormat("#,###,###"); sizeLabel.setText("Size : " + df.format(_flacinfo.getSize()) + " bytes"); channelsLabel.setText("Channels: " + _flacinfo.getChannels()); bitspersampleLabel.setText("Bits Per Sample: " + _flacinfo.getBitsPerSample()); samplerateLabel.setText("Sample Rate: " + _flacinfo.getSamplingRate() + " Hz"); buttonsPanel.add(_close); pack(); } /** * This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jPanel3 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); locationLabel = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); textField = new javax.swing.JTextArea(); jPanel2 = new javax.swing.JPanel(); lengthLabel = new javax.swing.JLabel(); sizeLabel = new javax.swing.JLabel(); channelsLabel = new javax.swing.JLabel(); bitspersampleLabel = new javax.swing.JLabel(); bitrateLabel = new javax.swing.JLabel(); samplerateLabel = new javax.swing.JLabel(); buttonsPanel = new javax.swing.JPanel(); getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.Y_AXIS)); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setResizable(false); jPanel3.setLayout(new java.awt.GridBagLayout()); jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); jLabel1.setText("File/URL :"); jPanel1.add(jLabel1); jPanel1.add(locationLabel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jPanel1, gridBagConstraints); jLabel2.setText("Standard Tags"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jLabel2, gridBagConstraints); jLabel3.setText("File/Stream info"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jLabel3, gridBagConstraints); textField.setColumns(20); textField.setRows(10); jScrollPane1.setViewportView(textField); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jScrollPane1, gridBagConstraints); jPanel2.setLayout(new javax.swing.BoxLayout(jPanel2, javax.swing.BoxLayout.Y_AXIS)); jPanel2.add(lengthLabel); jPanel2.add(sizeLabel); jPanel2.add(channelsLabel); jPanel2.add(bitspersampleLabel); jPanel2.add(bitrateLabel); jPanel2.add(samplerateLabel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jPanel2, gridBagConstraints); getContentPane().add(jPanel3); getContentPane().add(buttonsPanel); //pack(); } // </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel bitrateLabel; private javax.swing.JLabel bitspersampleLabel; private javax.swing.JPanel buttonsPanel; private javax.swing.JLabel channelsLabel; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lengthLabel; private javax.swing.JLabel locationLabel; private javax.swing.JLabel samplerateLabel; private javax.swing.JLabel sizeLabel; private javax.swing.JTextArea textField; // End of variables declaration//GEN-END:variables }
Java
/* * MpegDialog. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.tag.ui; import java.text.DecimalFormat; import javax.swing.JFrame; import javazoom.jlgui.player.amp.tag.MpegInfo; /** * OggVorbisDialog class implements a DialogBox to diplay OggVorbis info. */ public class MpegDialog extends TagInfoDialog { private MpegInfo _mpeginfo = null; /** * Creates new form MpegDialog */ public MpegDialog(JFrame parent, String title, MpegInfo mi) { super(parent, title); initComponents(); _mpeginfo = mi; int size = _mpeginfo.getLocation().length(); locationLabel.setText(size > 50 ? ("..." + _mpeginfo.getLocation().substring(size - 50)) : _mpeginfo.getLocation()); if ((_mpeginfo.getTitle() != null) && ((!_mpeginfo.getTitle().equals("")))) textField.append("Title=" + _mpeginfo.getTitle() + "\n"); if ((_mpeginfo.getArtist() != null) && ((!_mpeginfo.getArtist().equals("")))) textField.append("Artist=" + _mpeginfo.getArtist() + "\n"); if ((_mpeginfo.getAlbum() != null) && ((!_mpeginfo.getAlbum().equals("")))) textField.append("Album=" + _mpeginfo.getAlbum() + "\n"); if (_mpeginfo.getTrack() > 0) textField.append("Track=" + _mpeginfo.getTrack() + "\n"); if ((_mpeginfo.getYear() != null) && ((!_mpeginfo.getYear().equals("")))) textField.append("Year=" + _mpeginfo.getYear() + "\n"); if ((_mpeginfo.getGenre() != null) && ((!_mpeginfo.getGenre().equals("")))) textField.append("Genre=" + _mpeginfo.getGenre() + "\n"); java.util.List comments = _mpeginfo.getComment(); if (comments != null) { for (int i = 0; i < comments.size(); i++) textField.append(comments.get(i) + "\n"); } int secondsAmount = Math.round(_mpeginfo.getPlayTime()); if (secondsAmount < 0) secondsAmount = 0; int minutes = secondsAmount / 60; int seconds = secondsAmount - (minutes * 60); lengthLabel.setText("Length : " + minutes + ":" + seconds); DecimalFormat df = new DecimalFormat("#,###,###"); sizeLabel.setText("Size : " + df.format(_mpeginfo.getSize()) + " bytes"); versionLabel.setText(_mpeginfo.getVersion() + " " + _mpeginfo.getLayer()); bitrateLabel.setText((_mpeginfo.getBitRate() / 1000) + " kbps"); samplerateLabel.setText(_mpeginfo.getSamplingRate() + " Hz " + _mpeginfo.getChannelsMode()); vbrLabel.setText("VBR : " + _mpeginfo.getVBR()); crcLabel.setText("CRCs : " + _mpeginfo.getCRC()); copyrightLabel.setText("Copyrighted : " + _mpeginfo.getCopyright()); originalLabel.setText("Original : " + _mpeginfo.getOriginal()); emphasisLabel.setText("Emphasis : " + _mpeginfo.getEmphasis()); buttonsPanel.add(_close); pack(); } /** * Returns VorbisInfo. */ public MpegInfo getOggVorbisInfo() { return _mpeginfo; } /** * This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jPanel3 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); locationLabel = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); textField = new javax.swing.JTextArea(); jPanel2 = new javax.swing.JPanel(); lengthLabel = new javax.swing.JLabel(); sizeLabel = new javax.swing.JLabel(); versionLabel = new javax.swing.JLabel(); bitrateLabel = new javax.swing.JLabel(); samplerateLabel = new javax.swing.JLabel(); vbrLabel = new javax.swing.JLabel(); crcLabel = new javax.swing.JLabel(); copyrightLabel = new javax.swing.JLabel(); originalLabel = new javax.swing.JLabel(); emphasisLabel = new javax.swing.JLabel(); buttonsPanel = new javax.swing.JPanel(); getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.Y_AXIS)); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setResizable(false); jPanel3.setLayout(new java.awt.GridBagLayout()); jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); jLabel1.setText("File/URL :"); jPanel1.add(jLabel1); jPanel1.add(locationLabel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jPanel1, gridBagConstraints); jLabel2.setText("Standard Tags"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jLabel2, gridBagConstraints); jLabel3.setText("File/Stream info"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jLabel3, gridBagConstraints); textField.setColumns(20); textField.setRows(10); jScrollPane1.setViewportView(textField); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jScrollPane1, gridBagConstraints); jPanel2.setLayout(new javax.swing.BoxLayout(jPanel2, javax.swing.BoxLayout.Y_AXIS)); jPanel2.add(lengthLabel); jPanel2.add(sizeLabel); jPanel2.add(versionLabel); jPanel2.add(bitrateLabel); jPanel2.add(samplerateLabel); jPanel2.add(vbrLabel); jPanel2.add(crcLabel); jPanel2.add(copyrightLabel); jPanel2.add(originalLabel); jPanel2.add(emphasisLabel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jPanel2, gridBagConstraints); getContentPane().add(jPanel3); getContentPane().add(buttonsPanel); //pack(); } // </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel bitrateLabel; private javax.swing.JPanel buttonsPanel; private javax.swing.JLabel copyrightLabel; private javax.swing.JLabel crcLabel; private javax.swing.JLabel emphasisLabel; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lengthLabel; private javax.swing.JLabel locationLabel; private javax.swing.JLabel originalLabel; private javax.swing.JLabel samplerateLabel; private javax.swing.JLabel sizeLabel; private javax.swing.JTextArea textField; private javax.swing.JLabel vbrLabel; private javax.swing.JLabel versionLabel; // End of variables declaration//GEN-END:variables }
Java
/* * EmptyDialog. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.tag.ui; import javax.swing.JFrame; import javazoom.jlgui.player.amp.tag.TagInfo; /** * OggVorbisDialog class implements a DialogBox to diplay OggVorbis info. */ public class EmptyDialog extends TagInfoDialog { private TagInfo _info = null; /** * Creates new form MpegDialog */ public EmptyDialog(JFrame parent, String title, TagInfo mi) { super(parent, title); initComponents(); _info = mi; buttonsPanel.add(_close); pack(); } /** * This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents private void initComponents() { jPanel3 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); buttonsPanel = new javax.swing.JPanel(); getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.Y_AXIS)); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setResizable(false); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("No Information Available"); jPanel3.add(jLabel1); getContentPane().add(jPanel3); getContentPane().add(buttonsPanel); //pack(); } // </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonsPanel; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel3; // End of variables declaration//GEN-END:variables }
Java
/* * TagInfoDialog. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.tag.ui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; /** * This class define a Dialog for TagiInfo to display. */ public class TagInfoDialog extends JDialog implements ActionListener { protected JButton _close = null; /** * Constructor. * @param parent * @param title */ public TagInfoDialog(JFrame parent, String title) { super(parent, title, true); _close = new JButton("Close"); _close.addActionListener(this); } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent e) { if (e.getSource() == _close) { this.dispose(); } } }
Java
/* * APEDialog. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.tag.ui; import java.text.DecimalFormat; import javax.swing.JFrame; import javazoom.jlgui.player.amp.tag.APEInfo; /** * APEDialog class implements a DialogBox to diplay APE info. */ public class APEDialog extends TagInfoDialog { private APEInfo _apeinfo = null; /** * Creates new form ApeDialog */ public APEDialog(JFrame parent, String title, APEInfo mi) { super(parent, title); initComponents(); _apeinfo = mi; int size = _apeinfo.getLocation().length(); locationLabel.setText(size > 50 ? ("..." + _apeinfo.getLocation().substring(size - 50)) : _apeinfo.getLocation()); if ((_apeinfo.getTitle() != null) && (!_apeinfo.getTitle().equals(""))) textField.append("Title=" + _apeinfo.getTitle() + "\n"); if ((_apeinfo.getArtist() != null) && (!_apeinfo.getArtist().equals(""))) textField.append("Artist=" + _apeinfo.getArtist() + "\n"); if ((_apeinfo.getAlbum() != null) && (!_apeinfo.getAlbum().equals(""))) textField.append("Album=" + _apeinfo.getAlbum() + "\n"); if (_apeinfo.getTrack() > 0) textField.append("Track=" + _apeinfo.getTrack() + "\n"); if ((_apeinfo.getYear() != null) && (!_apeinfo.getYear().equals(""))) textField.append("Year=" + _apeinfo.getYear() + "\n"); if ((_apeinfo.getGenre() != null) && (!_apeinfo.getGenre().equals(""))) textField.append("Genre=" + _apeinfo.getGenre() + "\n"); java.util.List comments = _apeinfo.getComment(); if (comments != null) { for (int i = 0; i < comments.size(); i++) textField.append(comments.get(i) + "\n"); } int secondsAmount = Math.round(_apeinfo.getPlayTime()); if (secondsAmount < 0) secondsAmount = 0; int minutes = secondsAmount / 60; int seconds = secondsAmount - (minutes * 60); lengthLabel.setText("Length : " + minutes + ":" + seconds); DecimalFormat df = new DecimalFormat("#,###,###"); sizeLabel.setText("Size : " + df.format(_apeinfo.getSize()) + " bytes"); versionLabel.setText("Version: " + df.format(_apeinfo.getVersion())); compressionLabel.setText("Compression: " + _apeinfo.getCompressionlevel()); channelsLabel.setText("Channels: " + _apeinfo.getChannels()); bitspersampleLabel.setText("Bits Per Sample: " + _apeinfo.getBitsPerSample()); bitrateLabel.setText("Average Bitrate: " + (_apeinfo.getBitRate() / 1000) + " kbps"); samplerateLabel.setText("Sample Rate: " + _apeinfo.getSamplingRate() + " Hz"); peaklevelLabel.setText("Peak Level: " + (_apeinfo.getPeaklevel() > 0 ? String.valueOf(_apeinfo.getPeaklevel()) : "")); copyrightLabel.setText("Copyrighted: " + (_apeinfo.getCopyright() != null ? _apeinfo.getCopyright() : "")); buttonsPanel.add(_close); pack(); } /** * This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jPanel3 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); locationLabel = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); textField = new javax.swing.JTextArea(); jPanel2 = new javax.swing.JPanel(); lengthLabel = new javax.swing.JLabel(); sizeLabel = new javax.swing.JLabel(); versionLabel = new javax.swing.JLabel(); compressionLabel = new javax.swing.JLabel(); channelsLabel = new javax.swing.JLabel(); bitspersampleLabel = new javax.swing.JLabel(); bitrateLabel = new javax.swing.JLabel(); samplerateLabel = new javax.swing.JLabel(); peaklevelLabel = new javax.swing.JLabel(); copyrightLabel = new javax.swing.JLabel(); buttonsPanel = new javax.swing.JPanel(); getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.Y_AXIS)); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setResizable(false); jPanel3.setLayout(new java.awt.GridBagLayout()); jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); jLabel1.setText("File/URL :"); jPanel1.add(jLabel1); jPanel1.add(locationLabel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jPanel1, gridBagConstraints); jLabel2.setText("Standard Tags"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jLabel2, gridBagConstraints); jLabel3.setText("File/Stream info"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jLabel3, gridBagConstraints); textField.setColumns(20); textField.setRows(10); jScrollPane1.setViewportView(textField); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jScrollPane1, gridBagConstraints); jPanel2.setLayout(new javax.swing.BoxLayout(jPanel2, javax.swing.BoxLayout.Y_AXIS)); jPanel2.add(lengthLabel); jPanel2.add(sizeLabel); jPanel2.add(versionLabel); jPanel2.add(compressionLabel); jPanel2.add(channelsLabel); jPanel2.add(bitspersampleLabel); jPanel2.add(bitrateLabel); jPanel2.add(samplerateLabel); jPanel2.add(peaklevelLabel); jPanel2.add(copyrightLabel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jPanel2, gridBagConstraints); getContentPane().add(jPanel3); getContentPane().add(buttonsPanel); //pack(); } // </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel bitrateLabel; private javax.swing.JLabel bitspersampleLabel; private javax.swing.JPanel buttonsPanel; private javax.swing.JLabel channelsLabel; private javax.swing.JLabel compressionLabel; private javax.swing.JLabel copyrightLabel; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lengthLabel; private javax.swing.JLabel locationLabel; private javax.swing.JLabel peaklevelLabel; private javax.swing.JLabel samplerateLabel; private javax.swing.JLabel sizeLabel; private javax.swing.JTextArea textField; private javax.swing.JLabel versionLabel; // End of variables declaration//GEN-END:variables }
Java
/* * TagSearch. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.tag.ui; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ResourceBundle; import java.util.Vector; import javax.swing.ButtonGroup; import javax.swing.DefaultListModel; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.WindowConstants; import javax.swing.border.EmptyBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javazoom.jlgui.player.amp.PlayerUI; import javazoom.jlgui.player.amp.playlist.Playlist; import javazoom.jlgui.player.amp.playlist.PlaylistItem; import javazoom.jlgui.player.amp.tag.TagInfo; /** * This class allows to search and play for a particular track in the current playlist. */ public class TagSearch extends JFrame { private static String sep = System.getProperty("file.separator"); private JTextField searchField; private JList list; private DefaultListModel m; private PlayerUI player; private Vector _playlist, restrictedPlaylist; private String lastSearch = null; private JScrollPane scroll; private ResourceBundle bundle; private JRadioButton all, artist, album, title; public TagSearch(PlayerUI ui) { super(); player = ui; _playlist = null; restrictedPlaylist = null; bundle = ResourceBundle.getBundle("javazoom/jlgui/player/amp/tag/ui/tag"); initComponents(); } public void display() { if (list.getModel().getSize() != 0) { setVisible(true); } else { JOptionPane.showMessageDialog(player.getParent(), bundle.getString("emptyPlaylistMsg"), bundle.getString("emptyPlaylistTitle"), JOptionPane.OK_OPTION); } } /** * Initialises the User Interface. */ private void initComponents() { setLayout(new GridLayout(1, 1)); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setTitle(bundle.getString("title")); this.setLocation(player.getX() + player.getWidth(), player.getY()); JPanel main = new JPanel(new BorderLayout(0, 1)); main.setBorder(new EmptyBorder(10, 10, 10, 10)); main.setMinimumSize(new java.awt.Dimension(0, 0)); main.setPreferredSize(new java.awt.Dimension(300, 400)); JPanel searchPane = new JPanel(new GridLayout(4, 1, 10, 2)); JLabel searchLabel = new JLabel(bundle.getString("searchLabel")); searchField = new JTextField(); searchField.addKeyListener(new KeyboardListener()); searchPane.add(searchLabel); searchPane.add(searchField); all = new JRadioButton(bundle.getString("radioAll"), true); artist = new JRadioButton(bundle.getString("radioArtist"), false); album = new JRadioButton(bundle.getString("radioAlbum"), false); title = new JRadioButton(bundle.getString("radioTitle"), false); all.addChangeListener(new RadioListener()); ButtonGroup filters = new ButtonGroup(); filters.add(all); filters.add(artist); filters.add(album); filters.add(title); JPanel topButtons = new JPanel(new GridLayout(1, 2)); JPanel bottomButtons = new JPanel(new GridLayout(1, 2)); topButtons.add(all); topButtons.add(artist); bottomButtons.add(album); bottomButtons.add(title); searchPane.add(topButtons); searchPane.add(bottomButtons); list = new JList(); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); initList(); list.addMouseListener(new ClickListener()); list.addKeyListener(new KeyboardListener()); scroll = new JScrollPane(list); main.add(searchPane, BorderLayout.NORTH); main.add(scroll, BorderLayout.CENTER); add(main); pack(); } /** * Initialises the list so that it displays the details of all songs in the playlist. */ private void initList() { Playlist playlist = player.getPlaylist(); int c = player.getPlaylist().getPlaylistSize(); _playlist = new Vector(); for (int i = 0; i < c; i++) { _playlist.addElement(playlist.getItemAt(i)); } restrictedPlaylist = _playlist; m = new DefaultListModel(); for (int i = 0; i < _playlist.size(); i++) { PlaylistItem plItem = (PlaylistItem) _playlist.get(i); if (plItem.isFile()) m.addElement(getDisplayString(plItem)); } list.setModel(m); } public String getDisplayString(PlaylistItem pi) { TagInfo song = pi.getTagInfo(); String element; String location = pi.getLocation(); location = location.substring(location.lastIndexOf(sep) + 1, location.lastIndexOf(".")); if (song == null) { element = location; } else { if (song.getArtist() == null || song.getArtist().equals("")) { element = location; } else { element = song.getArtist().trim(); if (song.getTitle() == null || song.getTitle().equals("")) { element += " - " + location; } else { element += " - " + song.getTitle().trim(); } } } return element; } /** * Searches the playlist for a song containing the words in the given search string. * It searches on the title, artist, album and filename of each song in the playlist. * * @param searchString The string to search for in all songs in the playlist **/ private void searchList(String searchString) { String[] s = searchString.split(" "); String lastS = ""; if (s.length > 0) lastS = s[s.length - 1]; if (lastS.equals("")) { list.setModel(m); restrictedPlaylist = _playlist; } else { DefaultListModel newModel = new DefaultListModel(); if (lastSearch != null) { if (searchString.length() <= 1 || !searchString.substring(searchString.length() - 2).equals(lastSearch)) { list.setModel(m); restrictedPlaylist = _playlist; } } Vector pI = restrictedPlaylist; restrictedPlaylist = new Vector(); for (int a = 0; a < s.length; a++) { String currentS = s[a]; int size = list.getModel().getSize(); boolean[] remove = new boolean[size]; for (int i = 0; i < size; i++) { final int TITLE_SEARCH = 0; final int ARTIST_SEARCH = 1; final int ALBUM_SEARCH = 2; final int FILENAME_SEARCH = 3; TagInfo pli = ((PlaylistItem) pI.get(i)).getTagInfo(); remove[i] = false; boolean found = false; int searchType; if (artist.isSelected()) { searchType = ARTIST_SEARCH; } else if (album.isSelected()) { searchType = ALBUM_SEARCH; } else if (title.isSelected()) { searchType = TITLE_SEARCH; } else { searchType = -1; } for (int j = 0; j <= FILENAME_SEARCH; j++) { String listString = ""; if (pli == null) { if (searchType != -1) { break; } j = FILENAME_SEARCH; } else if (searchType != -1) { j = searchType; } switch (j) { case (TITLE_SEARCH): if (pli.getTitle() != null) listString = pli.getTitle().toLowerCase(); break; case (ARTIST_SEARCH): if (pli.getArtist() != null) listString = pli.getArtist().toLowerCase(); break; case (ALBUM_SEARCH): if (pli.getAlbum() != null) listString = pli.getAlbum().toLowerCase(); break; case (FILENAME_SEARCH): String location = ((PlaylistItem) pI.get(i)).getLocation().toLowerCase(); listString = location.substring(location.lastIndexOf(sep) + 1, location.lastIndexOf(".")); break; } currentS = currentS.toLowerCase(); if (found = search(currentS, listString)) { break; } if (searchType != -1) { break; } } //if(found)foundAt[a] = i; if (found && a == 0) { //todo new newModel.addElement(getDisplayString((PlaylistItem) pI.get(i))); restrictedPlaylist.add(pI.get(i)); } if (!found && a != 0) { remove[i] = true; } } //remove all unmatching items for (int x = size - 1; x >= 0; x--) { if (remove[x]) { newModel.remove(x); restrictedPlaylist.remove(x); } } pI = restrictedPlaylist; list.setModel(newModel); } list.setModel(newModel); lastSearch = searchField.getText(); } if (list.getModel().getSize() > 0) list.setSelectedIndex(0); } /** * Searches to see if a particular string exists within another string * * @param pattern The string to search for * @param text The string in which to search for the pattern string * @return True if the pattern string exists in the text string */ private boolean search(String pattern, String text) { int pStart = 0; int tStart = 0; char[] pChar = pattern.toCharArray(); char[] tChar = text.toCharArray(); while (pStart < pChar.length && tStart < tChar.length) { if (pChar[pStart] == tChar[tStart]) { pStart++; tStart++; } else { pStart = 0; if (pChar[pStart] != tChar[tStart]) { tStart++; } } } return pStart == pChar.length; } /** * Calls the relavent methods in the player class to play a song. */ private void playSong() { Playlist playlist = player.getPlaylist(); player.pressStop(); player.setCurrentSong((PlaylistItem) restrictedPlaylist.get(list.getSelectedIndex())); playlist.setCursor(playlist.getIndex((PlaylistItem) restrictedPlaylist.get(list.getSelectedIndex()))); player.pressStart(); dispose(); } /** * Class to handle keyboard presses. */ class KeyboardListener implements KeyListener { public void keyReleased(KeyEvent e) { if (e.getSource().equals(searchField)) { if (e.getKeyCode() != KeyEvent.VK_DOWN && e.getKeyCode() != KeyEvent.VK_UP) { searchList(searchField.getText()); // Search for current search string } } } public void keyTyped(KeyEvent e) { if (list.getSelectedIndex() != -1) { if (e.getKeyChar() == KeyEvent.VK_ENTER) { playSong(); } } } public void keyPressed(KeyEvent e) { int index = list.getSelectedIndex(); if (e.getKeyCode() == KeyEvent.VK_DOWN && index < list.getModel().getSize() - 1) { //list.setSelectedIndex(index+1); JScrollBar vBar = scroll.getVerticalScrollBar(); vBar.setValue(vBar.getValue() + vBar.getUnitIncrement() * 5); } else if (e.getKeyCode() == KeyEvent.VK_UP && index >= 0) { JScrollBar vBar = scroll.getVerticalScrollBar(); vBar.setValue(vBar.getValue() - vBar.getUnitIncrement() * 5); //list.setSelectedIndex(index-1); } } } /** * Class to play a song if one is double-clicked on on the search list. */ class ClickListener extends MouseAdapter { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2 && list.getSelectedIndex() != -1) { playSong(); } } } class RadioListener implements ChangeListener { public void stateChanged(ChangeEvent e) { searchList(searchField.getText()); } } }
Java
/* * OggVorbisDialog. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.tag.ui; import java.text.DecimalFormat; import javax.swing.JFrame; import javazoom.jlgui.player.amp.tag.OggVorbisInfo; /** * OggVorbisDialog class implements a DialogBox to diplay OggVorbis info. */ public class OggVorbisDialog extends TagInfoDialog { private OggVorbisInfo _vorbisinfo = null; /** * Creates new form MpegDialog */ public OggVorbisDialog(JFrame parent, String title, OggVorbisInfo mi) { super(parent, title); initComponents(); _vorbisinfo = mi; int size = _vorbisinfo.getLocation().length(); locationLabel.setText(size > 50 ? ("..." + _vorbisinfo.getLocation().substring(size - 50)) : _vorbisinfo.getLocation()); if ((_vorbisinfo.getTitle() != null) && ((!_vorbisinfo.getTitle().equals("")))) textField.append("Title=" + _vorbisinfo.getTitle() + "\n"); if ((_vorbisinfo.getArtist() != null) && ((!_vorbisinfo.getArtist().equals("")))) textField.append("Artist=" + _vorbisinfo.getArtist() + "\n"); if ((_vorbisinfo.getAlbum() != null) && ((!_vorbisinfo.getAlbum().equals("")))) textField.append("Album=" + _vorbisinfo.getAlbum() + "\n"); if (_vorbisinfo.getTrack() > 0) textField.append("Track=" + _vorbisinfo.getTrack() + "\n"); if ((_vorbisinfo.getYear() != null) && ((!_vorbisinfo.getYear().equals("")))) textField.append("Year=" + _vorbisinfo.getYear() + "\n"); if ((_vorbisinfo.getGenre() != null) && ((!_vorbisinfo.getGenre().equals("")))) textField.append("Genre=" + _vorbisinfo.getGenre() + "\n"); java.util.List comments = _vorbisinfo.getComment(); for (int i = 0; i < comments.size(); i++) textField.append(comments.get(i) + "\n"); int secondsAmount = Math.round(_vorbisinfo.getPlayTime()); if (secondsAmount < 0) secondsAmount = 0; int minutes = secondsAmount / 60; int seconds = secondsAmount - (minutes * 60); lengthLabel.setText("Length : " + minutes + ":" + seconds); bitrateLabel.setText("Average bitrate : " + _vorbisinfo.getAverageBitrate() / 1000 + " kbps"); DecimalFormat df = new DecimalFormat("#,###,###"); sizeLabel.setText("File size : " + df.format(_vorbisinfo.getSize()) + " bytes"); nominalbitrateLabel.setText("Nominal bitrate : " + (_vorbisinfo.getBitRate() / 1000) + " kbps"); maxbitrateLabel.setText("Max bitrate : " + _vorbisinfo.getMaxBitrate() / 1000 + " kbps"); minbitrateLabel.setText("Min bitrate : " + _vorbisinfo.getMinBitrate() / 1000 + " kbps"); channelsLabel.setText("Channel : " + _vorbisinfo.getChannels()); samplerateLabel.setText("Sampling rate : " + _vorbisinfo.getSamplingRate() + " Hz"); serialnumberLabel.setText("Serial number : " + _vorbisinfo.getSerial()); versionLabel.setText("Version : " + _vorbisinfo.getVersion()); vendorLabel.setText("Vendor : " + _vorbisinfo.getVendor()); buttonsPanel.add(_close); pack(); } /** * Returns VorbisInfo. */ public OggVorbisInfo getOggVorbisInfo() { return _vorbisinfo; } /** * This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jPanel3 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); locationLabel = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); textField = new javax.swing.JTextArea(); jPanel2 = new javax.swing.JPanel(); lengthLabel = new javax.swing.JLabel(); bitrateLabel = new javax.swing.JLabel(); sizeLabel = new javax.swing.JLabel(); nominalbitrateLabel = new javax.swing.JLabel(); maxbitrateLabel = new javax.swing.JLabel(); minbitrateLabel = new javax.swing.JLabel(); channelsLabel = new javax.swing.JLabel(); samplerateLabel = new javax.swing.JLabel(); serialnumberLabel = new javax.swing.JLabel(); versionLabel = new javax.swing.JLabel(); vendorLabel = new javax.swing.JLabel(); buttonsPanel = new javax.swing.JPanel(); getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.Y_AXIS)); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setResizable(false); jPanel3.setLayout(new java.awt.GridBagLayout()); jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); jLabel1.setText("File/URL :"); jPanel1.add(jLabel1); jPanel1.add(locationLabel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jPanel1, gridBagConstraints); jLabel2.setText("Standard Tags"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jLabel2, gridBagConstraints); jLabel3.setText("File/Stream info"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jLabel3, gridBagConstraints); textField.setColumns(20); textField.setRows(10); jScrollPane1.setViewportView(textField); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jScrollPane1, gridBagConstraints); jPanel2.setLayout(new javax.swing.BoxLayout(jPanel2, javax.swing.BoxLayout.Y_AXIS)); jPanel2.add(lengthLabel); jPanel2.add(bitrateLabel); jPanel2.add(sizeLabel); jPanel2.add(nominalbitrateLabel); jPanel2.add(maxbitrateLabel); jPanel2.add(minbitrateLabel); jPanel2.add(channelsLabel); jPanel2.add(samplerateLabel); jPanel2.add(serialnumberLabel); jPanel2.add(versionLabel); jPanel2.add(vendorLabel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jPanel2, gridBagConstraints); getContentPane().add(jPanel3); getContentPane().add(buttonsPanel); //pack(); } // </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel bitrateLabel; private javax.swing.JPanel buttonsPanel; private javax.swing.JLabel channelsLabel; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lengthLabel; private javax.swing.JLabel locationLabel; private javax.swing.JLabel maxbitrateLabel; private javax.swing.JLabel minbitrateLabel; private javax.swing.JLabel nominalbitrateLabel; private javax.swing.JLabel samplerateLabel; private javax.swing.JLabel serialnumberLabel; private javax.swing.JLabel sizeLabel; private javax.swing.JTextArea textField; private javax.swing.JLabel vendorLabel; private javax.swing.JLabel versionLabel; // End of variables declaration//GEN-END:variables }
Java
/* * PlaylistItem. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- * */ package javazoom.jlgui.player.amp.playlist; import javazoom.jlgui.player.amp.tag.TagInfo; import javazoom.jlgui.player.amp.tag.TagInfoFactory; import javazoom.jlgui.player.amp.util.Config; import javazoom.jlgui.player.amp.util.FileUtil; /** * This class implements item for playlist. */ public class PlaylistItem { protected String _name = null; protected String _displayName = null; protected String _location = null; protected boolean _isFile = true; protected long _seconds = -1; protected boolean _isSelected = false; // add by JOHN YANG protected TagInfo _taginfo = null; protected PlaylistItem() { } /** * Contructor for playlist item. * * @param name Song name to be displayed * @param location File or URL * @param seconds Time length * @param isFile true for File instance */ public PlaylistItem(String name, String location, long seconds, boolean isFile) { _name = name; _seconds = seconds; _isFile = isFile; Config config = Config.getInstance(); if (config.getTaginfoPolicy().equals(Config.TAGINFO_POLICY_ALL)) { // Read tag info for any File or URL. It could take time. setLocation(location, true); } else if (config.getTaginfoPolicy().equals(Config.TAGINFO_POLICY_FILE)) { // Read tag info for any File only not for URL. if (_isFile) setLocation(location, true); else setLocation(location, false); } else { // Do not read tag info. setLocation(location, false); } } /** * Returns item name such as (hh:mm:ss) Title - Artist if available. * * @return */ public String getFormattedName() { if (_displayName == null) { if (_seconds > 0) { String length = getFormattedLength(); return "(" + length + ") " + _name; } else return _name; } // Name extracted from TagInfo or stream title. else return _displayName; } public String getName() { return _name; } public String getLocation() { return _location; } /** * Returns true if item to play is coming for a file. * * @return */ public boolean isFile() { return _isFile; } /** * Set File flag for playslit item. * * @param b */ public void setFile(boolean b) { _isFile = b; } /** * Returns playtime in seconds. If tag info is available then its playtime will be returned. * * @return playtime */ public long getLength() { if ((_taginfo != null) && (_taginfo.getPlayTime() > 0)) return _taginfo.getPlayTime(); else return _seconds; } public int getBitrate() { if (_taginfo != null) return _taginfo.getBitRate(); else return -1; } public int getSamplerate() { if (_taginfo != null) return _taginfo.getSamplingRate(); else return -1; } public int getChannels() { if (_taginfo != null) return _taginfo.getChannels(); else return -1; } public void setSelected(boolean mode) { _isSelected = mode; } public boolean isSelected() { return _isSelected; } /** * Reads file comments/tags. * * @param l */ public void setLocation(String l) { setLocation(l, false); } /** * Reads (or not) file comments/tags. * * @param l input location * @param readInfo */ public void setLocation(String l, boolean readInfo) { _location = l; if (readInfo == true) { // Read Audio Format and read tags/comments. if ((_location != null) && (!_location.equals(""))) { TagInfoFactory factory = TagInfoFactory.getInstance(); _taginfo = factory.getTagInfo(l); } } _displayName = getFormattedDisplayName(); } /** * Returns item lenght such as hh:mm:ss * * @return formatted String. */ public String getFormattedLength() { long time = getLength(); String length = ""; if (time > -1) { int minutes = (int) Math.floor(time / 60); int hours = (int) Math.floor(minutes / 60); minutes = minutes - hours * 60; int seconds = (int) (time - minutes * 60 - hours * 3600); // Hours. if (hours > 0) { length = length + FileUtil.rightPadString(hours + "", '0', 2) + ":"; } length = length + FileUtil.rightPadString(minutes + "", '0', 2) + ":" + FileUtil.rightPadString(seconds + "", '0', 2); } else length = "" + time; return length; } /** * Returns item name such as (hh:mm:ss) Title - Artist * * @return formatted String. */ public String getFormattedDisplayName() { if (_taginfo == null) return null; else { String length = getFormattedLength(); if ((_taginfo.getTitle() != null) && (!_taginfo.getTitle().equals("")) && (_taginfo.getArtist() != null) && (!_taginfo.getArtist().equals(""))) { if (getLength() > 0) return ("(" + length + ") " + _taginfo.getTitle() + " - " + _taginfo.getArtist()); else return (_taginfo.getTitle() + " - " + _taginfo.getArtist()); } else if ((_taginfo.getTitle() != null) && (!_taginfo.getTitle().equals(""))) { if (getLength() > 0) return ("(" + length + ") " + _taginfo.getTitle()); else return (_taginfo.getTitle()); } else { if (getLength() > 0) return ("(" + length + ") " + _name); else return (_name); } } } public void setFormattedDisplayName(String fname) { _displayName = fname; } /** * Return item name such as hh:mm:ss,Title,Artist * * @return formatted String. */ public String getM3UExtInf() { if (_taginfo == null) { return (_seconds + "," + _name); } else { if ((_taginfo.getTitle() != null) && (_taginfo.getArtist() != null)) { return (getLength() + "," + _taginfo.getTitle() + " - " + _taginfo.getArtist()); } else if (_taginfo.getTitle() != null) { return (getLength() + "," + _taginfo.getTitle()); } else { return (_seconds + "," + _name); } } } /** * Return TagInfo. * * @return */ public TagInfo getTagInfo() { if (_taginfo == null) { // Inspect location setLocation(_location, true); } return _taginfo; } }
Java
/* * Playlist. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.playlist; import java.util.Collection; /** * Playlist. * This interface defines method that a playlist should implement.<br> * A playlist provides a collection of item to play and a cursor to know * which item is playing. */ public interface Playlist { // Next methods will be called by the Playlist UI. /** * Loads playlist. */ public boolean load(String filename); /** * Saves playlist. */ public boolean save(String filename); /** * Adds item at a given position in the playlist. */ public void addItemAt(PlaylistItem pli, int pos); /** * Searchs and removes item from the playlist. */ public void removeItem(PlaylistItem pli); /** * Removes item at a given position from the playlist. */ public void removeItemAt(int pos); /** * Removes all items in the playlist. */ public void removeAllItems(); /** * Append item at the end of the playlist. */ public void appendItem(PlaylistItem pli); /** * Sorts items of the playlist. */ public void sortItems(int sortmode); /** * Returns item at a given position from the playlist. */ public PlaylistItem getItemAt(int pos); /** * Returns a collection of playlist items. */ public Collection getAllItems(); /** * Returns then number of items in the playlist. */ public int getPlaylistSize(); // Next methods will be used by the Player /** * Randomly re-arranges the playlist. */ public void shuffle(); /** * Returns item matching to the cursor. */ public PlaylistItem getCursor(); /** * Moves the cursor at the begining of the Playlist. */ public void begin(); /** * Returns item matching to the cursor. */ public int getSelectedIndex(); /** * Returns index of playlist item. */ public int getIndex(PlaylistItem pli); /** * Computes cursor position (next). */ public void nextCursor(); /** * Computes cursor position (previous). */ public void previousCursor(); /** * Set the modification flag for the playlist */ boolean setModified(boolean set); /** * Checks the modification flag */ public boolean isModified(); void setCursor(int index); }
Java
/* * BasePlaylist. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.playlist; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.Collection; import java.util.Iterator; import java.util.StringTokenizer; import java.util.Vector; import javazoom.jlgui.player.amp.util.Config; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * BasePlaylist implementation. * This class implements Playlist interface using a Vector. * It support .m3u and .pls playlist format. */ public class BasePlaylist implements Playlist { protected Vector _playlist = null; protected int _cursorPos = -1; protected boolean isModified; protected String M3UHome = null; protected String PLSHome = null; private static Log log = LogFactory.getLog(BasePlaylist.class); /** * Constructor. */ public BasePlaylist() { _playlist = new Vector(); } public boolean isModified() { return isModified; } /** * Loads playlist as M3U format. */ public boolean load(String filename) { setModified(true); boolean loaded = false; if ((filename != null) && (filename.toLowerCase().endsWith(".m3u"))) { loaded = loadM3U(filename); } else if ((filename != null) && (filename.toLowerCase().endsWith(".pls"))) { loaded = loadPLS(filename); } return loaded; } /** * Load playlist from M3U format. * * @param filename * @return */ protected boolean loadM3U(String filename) { Config config = Config.getInstance(); _playlist = new Vector(); boolean loaded = false; BufferedReader br = null; try { // Playlist from URL ? (http:, ftp:, file: ....) if (Config.startWithProtocol(filename)) { br = new BufferedReader(new InputStreamReader((new URL(filename)).openStream())); } else { br = new BufferedReader(new FileReader(filename)); } String line = null; String songName = null; String songFile = null; String songLength = null; while ((line = br.readLine()) != null) { if (line.trim().length() == 0) continue; if (line.startsWith("#")) { if (line.toUpperCase().startsWith("#EXTINF")) { int indA = line.indexOf(",", 0); if (indA != -1) { songName = line.substring(indA + 1, line.length()); } int indB = line.indexOf(":", 0); if (indB != -1) { if (indB < indA) songLength = (line.substring(indB + 1, indA)).trim(); } } } else { songFile = line; if (songName == null) songName = songFile; if (songLength == null) songLength = "-1"; PlaylistItem pli = null; if (Config.startWithProtocol(songFile)) { // URL. pli = new PlaylistItem(songName, songFile, Long.parseLong(songLength), false); } else { // File. File f = new File(songFile); if (f.exists()) { pli = new PlaylistItem(songName, songFile, Long.parseLong(songLength), true); } else { // Try relative path. f = new File(config.getLastDir() + songFile); if (f.exists()) { pli = new PlaylistItem(songName, config.getLastDir() + songFile, Long.parseLong(songLength), true); } else { // Try optional M3U home. if (M3UHome != null) { if (Config.startWithProtocol(M3UHome)) { pli = new PlaylistItem(songName, M3UHome + songFile, Long.parseLong(songLength), false); } else { pli = new PlaylistItem(songName, M3UHome + songFile, Long.parseLong(songLength), true); } } } } } if (pli != null) this.appendItem(pli); songFile = null; songName = null; songLength = null; } } loaded = true; } catch (Exception e) { log.debug("Can't load .m3u playlist", e); } finally { try { if (br != null) { br.close(); } } catch (Exception ioe) { log.info("Can't close .m3u playlist", ioe); } } return loaded; } /** * Load playlist in PLS format. * * @param filename * @return */ protected boolean loadPLS(String filename) { Config config = Config.getInstance(); _playlist = new Vector(); boolean loaded = false; BufferedReader br = null; try { // Playlist from URL ? (http:, ftp:, file: ....) if (Config.startWithProtocol(filename)) { br = new BufferedReader(new InputStreamReader((new URL(filename)).openStream())); } else { br = new BufferedReader(new FileReader(filename)); } String line = null; String songName = null; String songFile = null; String songLength = null; while ((line = br.readLine()) != null) { if (line.trim().length() == 0) continue; if ((line.toLowerCase().startsWith("file"))) { StringTokenizer st = new StringTokenizer(line, "="); st.nextToken(); songFile = st.nextToken().trim(); } else if ((line.toLowerCase().startsWith("title"))) { StringTokenizer st = new StringTokenizer(line, "="); st.nextToken(); songName = st.nextToken().trim(); } else if ((line.toLowerCase().startsWith("length"))) { StringTokenizer st = new StringTokenizer(line, "="); st.nextToken(); songLength = st.nextToken().trim(); } // New entry ? if (songFile != null) { PlaylistItem pli = null; if (songName == null) songName = songFile; if (songLength == null) songLength = "-1"; if (Config.startWithProtocol(songFile)) { // URL. pli = new PlaylistItem(songName, songFile, Long.parseLong(songLength), false); } else { // File. File f = new File(songFile); if (f.exists()) { pli = new PlaylistItem(songName, songFile, Long.parseLong(songLength), true); } else { // Try relative path. f = new File(config.getLastDir() + songFile); if (f.exists()) { pli = new PlaylistItem(songName, config.getLastDir() + songFile, Long.parseLong(songLength), true); } else { // Try optional PLS home. if (PLSHome != null) { if (Config.startWithProtocol(PLSHome)) { pli = new PlaylistItem(songName, PLSHome + songFile, Long.parseLong(songLength), false); } else { pli = new PlaylistItem(songName, PLSHome + songFile, Long.parseLong(songLength), true); } } } } } if (pli != null) this.appendItem(pli); songName = null; songFile = null; songLength = null; } } loaded = true; } catch (Exception e) { log.debug("Can't load .pls playlist", e); } finally { try { if (br != null) { br.close(); } } catch (Exception ioe) { log.info("Can't close .pls playlist", ioe); } } return loaded; } /** * Saves playlist in M3U format. */ public boolean save(String filename) { // Implemented by C.K if (_playlist != null) { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(filename)); bw.write("#EXTM3U"); bw.newLine(); Iterator it = _playlist.iterator(); while (it.hasNext()) { PlaylistItem pli = (PlaylistItem) it.next(); bw.write("#EXTINF:" + pli.getM3UExtInf()); bw.newLine(); bw.write(pli.getLocation()); bw.newLine(); } return true; } catch (IOException e) { log.info("Can't save playlist", e); } finally { try { if (bw != null) { bw.close(); } } catch (IOException ioe) { log.info("Can't close playlist", ioe); } } } return false; } /** * Adds item at a given position in the playlist. */ public void addItemAt(PlaylistItem pli, int pos) { _playlist.insertElementAt(pli, pos); setModified(true); } /** * Searchs and removes item from the playlist. */ public void removeItem(PlaylistItem pli) { _playlist.remove(pli); setModified(true); } /** * Removes item at a given position from the playlist. */ public void removeItemAt(int pos) { _playlist.removeElementAt(pos); setModified(true); } /** * Removes all items from the playlist. */ public void removeAllItems() { _playlist.removeAllElements(); _cursorPos = -1; setModified(true); } /** * Append item at the end of the playlist. */ public void appendItem(PlaylistItem pli) { _playlist.addElement(pli); setModified(true); } /** * Sorts items of the playlist. */ public void sortItems(int sortmode) { // TODO } /** * Shuffles items in the playlist randomly */ public void shuffle() { int size = _playlist.size(); if (size < 2) { return; } Vector v = _playlist; _playlist = new Vector(size); while ((size = v.size()) > 0) { _playlist.addElement(v.remove((int) (Math.random() * size))); } begin(); } /** * Moves the cursor at the top of the playlist. */ public void begin() { _cursorPos = -1; if (getPlaylistSize() > 0) { _cursorPos = 0; } setModified(true); } /** * Returns item at a given position from the playlist. */ public PlaylistItem getItemAt(int pos) { PlaylistItem pli = null; pli = (PlaylistItem) _playlist.elementAt(pos); return pli; } /** * Returns a collection of playlist items. */ public Collection getAllItems() { // TODO return null; } /** * Returns then number of items in the playlist. */ public int getPlaylistSize() { return _playlist.size(); } // Next methods will be used by the Player /** * Returns item matching to the cursor. */ public PlaylistItem getCursor() { if ((_cursorPos < 0) || (_cursorPos >= _playlist.size())) { return null; } return getItemAt(_cursorPos); } /** * Computes cursor position (next). */ public void nextCursor() { _cursorPos++; } /** * Computes cursor position (previous). */ public void previousCursor() { _cursorPos--; if (_cursorPos < 0) { _cursorPos = 0; } } public boolean setModified(boolean set) { isModified = set; return isModified; } public void setCursor(int index) { _cursorPos = index; } /** * Returns selected index. */ public int getSelectedIndex() { return _cursorPos; } /** * Returns index of playlist item. */ public int getIndex(PlaylistItem pli) { int pos = -1; for (int i = 0; i < _playlist.size(); i++) { pos = i; PlaylistItem p = (PlaylistItem) _playlist.elementAt(i); if (p.equals(pli)) break; } return pos; } /** * Get M3U home for relative playlist. * * @return */ public String getM3UHome() { return M3UHome; } /** * Set optional M3U home for relative playlist. * * @param string */ public void setM3UHome(String string) { M3UHome = string; } /** * Get PLS home for relative playlist. * * @return */ public String getPLSHome() { return PLSHome; } /** * Set optional PLS home for relative playlist. * * @param string */ public void setPLSHome(String string) { PLSHome = string; } }
Java
/* * PlaylistFactory. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.playlist; import java.lang.reflect.Constructor; import javazoom.jlgui.player.amp.util.Config; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * PlaylistFactory. */ public class PlaylistFactory { private static PlaylistFactory _instance = null; private Playlist _playlistInstance = null; private Config _config = null; private static Log log = LogFactory.getLog(PlaylistFactory.class); /** * Constructor. */ private PlaylistFactory() { _config = Config.getInstance(); } /** * Returns instance of PlaylistFactory. */ public synchronized static PlaylistFactory getInstance() { if (_instance == null) { _instance = new PlaylistFactory(); } return _instance; } /** * Returns Playlist instantied from full qualified class name. */ public Playlist getPlaylist() { if (_playlistInstance == null) { String classname = _config.getPlaylistClassName(); boolean interfaceFound = false; try { Class aClass = Class.forName(classname); Class superClass = aClass; // Looking for Playlist interface implementation. while (superClass != null) { Class[] interfaces = superClass.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { if ((interfaces[i].getName()).equals("javazoom.jlgui.player.amp.playlist.Playlist")) { interfaceFound = true; break; } } if (interfaceFound == true) break; superClass = superClass.getSuperclass(); } if (interfaceFound == false) { log.error("Error : Playlist implementation not found in " + classname + " hierarchy"); } else { Class[] argsClass = new Class[] {}; Constructor c = aClass.getConstructor(argsClass); _playlistInstance = (Playlist) (c.newInstance(null)); log.info(classname + " loaded"); } } catch (Exception e) { log.error("Error : " + classname + " : " + e.getMessage()); } } return _playlistInstance; } }
Java
/* * PlaylistUI. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.playlist.ui; import java.awt.Graphics; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import java.util.StringTokenizer; import java.util.Vector; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javazoom.jlgui.player.amp.PlayerActionEvent; import javazoom.jlgui.player.amp.PlayerUI; import javazoom.jlgui.player.amp.playlist.Playlist; import javazoom.jlgui.player.amp.playlist.PlaylistItem; import javazoom.jlgui.player.amp.skin.AbsoluteLayout; import javazoom.jlgui.player.amp.skin.ActiveJButton; import javazoom.jlgui.player.amp.skin.DropTargetAdapter; import javazoom.jlgui.player.amp.skin.Skin; import javazoom.jlgui.player.amp.skin.UrlDialog; import javazoom.jlgui.player.amp.tag.TagInfo; import javazoom.jlgui.player.amp.tag.TagInfoFactory; import javazoom.jlgui.player.amp.tag.ui.TagInfoDialog; import javazoom.jlgui.player.amp.util.Config; import javazoom.jlgui.player.amp.util.FileSelector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class PlaylistUI extends JPanel implements ActionListener, ChangeListener { private static Log log = LogFactory.getLog(PlaylistUI.class); public static int MAXDEPTH = 4; private Config config = null; private Skin ui = null; private Playlist playlist = null; private PlayerUI player = null; private int topIndex = 0; private int currentSelection = -1; private Vector exts = null; private boolean isSearching = false; private JPopupMenu fipopup = null; public PlaylistUI() { super(); setDoubleBuffered(true); setLayout(new AbsoluteLayout()); config = Config.getInstance(); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { handleMouseClick(e); } }); // DnD support. DropTargetAdapter dnd = new DropTargetAdapter() { public void processDrop(Object data) { processDnD(data); } }; DropTarget dt = new DropTarget(this, DnDConstants.ACTION_COPY, dnd, true); } public void setPlayer(PlayerUI mp) { player = mp; } public void setSkin(Skin skin) { ui = skin; } public Skin getSkin() { return ui; } public Playlist getPlaylist() { return playlist; } public void setPlaylist(Playlist playlist) { this.playlist = playlist; } public int getTopIndex() { return topIndex; } public void loadUI() { removeAll(); ui.getPlaylistPanel().setParent(this); add(ui.getAcPlSlider(), ui.getAcPlSlider().getConstraints()); ui.getAcPlSlider().setValue(100); ui.getAcPlSlider().removeChangeListener(this); ui.getAcPlSlider().addChangeListener(this); add(ui.getAcPlUp(), ui.getAcPlUp().getConstraints()); ui.getAcPlUp().removeActionListener(this); ui.getAcPlUp().addActionListener(this); add(ui.getAcPlDown(), ui.getAcPlDown().getConstraints()); ui.getAcPlDown().removeActionListener(this); ui.getAcPlDown().addActionListener(this); // Add menu add(ui.getAcPlAdd(), ui.getAcPlAdd().getConstraints()); ui.getAcPlAdd().removeActionListener(this); ui.getAcPlAdd().addActionListener(this); add(ui.getAcPlAddPopup(), ui.getAcPlAddPopup().getConstraints()); ui.getAcPlAddPopup().setVisible(false); ActiveJButton[] items = ui.getAcPlAddPopup().getItems(); for (int i = 0; i < items.length; i++) { items[i].addActionListener(this); } // Remove menu add(ui.getAcPlRemove(), ui.getAcPlRemove().getConstraints()); ui.getAcPlRemove().removeActionListener(this); ui.getAcPlRemove().addActionListener(this); add(ui.getAcPlRemovePopup(), ui.getAcPlRemovePopup().getConstraints()); ui.getAcPlRemovePopup().setVisible(false); items = ui.getAcPlRemovePopup().getItems(); for (int i = 0; i < items.length; i++) { items[i].removeActionListener(this); items[i].addActionListener(this); } // Select menu add(ui.getAcPlSelect(), ui.getAcPlSelect().getConstraints()); ui.getAcPlSelect().removeActionListener(this); ui.getAcPlSelect().addActionListener(this); add(ui.getAcPlSelectPopup(), ui.getAcPlSelectPopup().getConstraints()); ui.getAcPlSelectPopup().setVisible(false); items = ui.getAcPlSelectPopup().getItems(); for (int i = 0; i < items.length; i++) { items[i].removeActionListener(this); items[i].addActionListener(this); } // Misc menu add(ui.getAcPlMisc(), ui.getAcPlMisc().getConstraints()); ui.getAcPlMisc().removeActionListener(this); ui.getAcPlMisc().addActionListener(this); add(ui.getAcPlMiscPopup(), ui.getAcPlMiscPopup().getConstraints()); ui.getAcPlMiscPopup().setVisible(false); items = ui.getAcPlMiscPopup().getItems(); for (int i = 0; i < items.length; i++) { items[i].removeActionListener(this); items[i].addActionListener(this); } // List menu add(ui.getAcPlList(), ui.getAcPlList().getConstraints()); ui.getAcPlList().removeActionListener(this); ui.getAcPlList().addActionListener(this); add(ui.getAcPlListPopup(), ui.getAcPlListPopup().getConstraints()); ui.getAcPlListPopup().setVisible(false); items = ui.getAcPlListPopup().getItems(); for (int i = 0; i < items.length; i++) { items[i].removeActionListener(this); items[i].addActionListener(this); } // Popup menu fipopup = new JPopupMenu(); JMenuItem mi = new JMenuItem(ui.getResource("playlist.popup.info")); mi.setActionCommand(PlayerActionEvent.ACPLINFO); mi.removeActionListener(this); mi.addActionListener(this); fipopup.add(mi); fipopup.addSeparator(); mi = new JMenuItem(ui.getResource("playlist.popup.play")); mi.setActionCommand(PlayerActionEvent.ACPLPLAY); mi.removeActionListener(this); mi.addActionListener(this); fipopup.add(mi); fipopup.addSeparator(); mi = new JMenuItem(ui.getResource("playlist.popup.remove")); mi.setActionCommand(PlayerActionEvent.ACPLREMOVE); mi.removeActionListener(this); mi.addActionListener(this); fipopup.add(mi); validate(); repaint(); } /** * Initialize playlist. */ public void initPlayList() { topIndex = 0; nextCursor(); } /** * Repaint the file list area and scroll it if necessary */ public void nextCursor() { currentSelection = playlist.getSelectedIndex(); int n = playlist.getPlaylistSize(); int nlines = ui.getPlaylistPanel().getLines(); while (currentSelection - topIndex > nlines - 1) topIndex += 2; if (topIndex >= n) topIndex = n - 1; while (currentSelection < topIndex) topIndex -= 2; if (topIndex < 0) topIndex = 0; resetScrollBar(); repaint(); } /** * Get the item index according to the mouse y position * @param y * @return */ protected int getIndex(int y) { int n0 = playlist.getPlaylistSize(); if (n0 == 0) return -1; for (int n = 0; n < 100; n++) { if (ui.getPlaylistPanel().isIndexArea(y, n)) { if (topIndex + n > n0 - 1) return -1; return topIndex + n; } } return -1; } /* (non-Javadoc) * @see javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent) */ public void stateChanged(ChangeEvent e) { Object src = e.getSource(); //log.debug("State (EDT=" + SwingUtilities.isEventDispatchThread() + ")"); if (src == ui.getAcPlSlider()) { int n = playlist.getPlaylistSize(); float dx = (100 - ui.getAcPlSlider().getValue()) / 100.0f; int index = (int) (dx * (n - 1)); if (index != topIndex) { topIndex = index; paintList(); } } } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent e) { final ActionEvent evt = e; new Thread("PlaylistUIActionEvent") { public void run() { processActionEvent(evt); } }.start(); } /** * Process action event. * @param e */ public void processActionEvent(ActionEvent e) { String cmd = e.getActionCommand(); log.debug("Action=" + cmd + " (EDT=" + SwingUtilities.isEventDispatchThread() + ")"); int n = playlist.getPlaylistSize(); if (cmd.equals(PlayerActionEvent.ACPLUP)) { topIndex--; if (topIndex < 0) topIndex = 0; resetScrollBar(); paintList(); } else if (cmd.equals(PlayerActionEvent.ACPLDOWN)) { topIndex++; if (topIndex > n - 1) topIndex = n - 1; resetScrollBar(); paintList(); } else if (cmd.equals(PlayerActionEvent.ACPLADDPOPUP)) { ui.getAcPlAdd().setVisible(false); ui.getAcPlAddPopup().setVisible(true); } else if (cmd.equals(PlayerActionEvent.ACPLREMOVEPOPUP)) { ui.getAcPlRemove().setVisible(false); ui.getAcPlRemovePopup().setVisible(true); } else if (cmd.equals(PlayerActionEvent.ACPLSELPOPUP)) { ui.getAcPlSelect().setVisible(false); ui.getAcPlSelectPopup().setVisible(true); } else if (cmd.equals(PlayerActionEvent.ACPLMISCPOPUP)) { ui.getAcPlMisc().setVisible(false); ui.getAcPlMiscPopup().setVisible(true); } else if (cmd.equals(PlayerActionEvent.ACPLLISTPOPUP)) { ui.getAcPlList().setVisible(false); ui.getAcPlListPopup().setVisible(true); } else if (cmd.equals(PlayerActionEvent.ACPLINFO)) { popupFileInfo(); } else if (cmd.equals(PlayerActionEvent.ACPLPLAY)) { int n0 = playlist.getPlaylistSize(); PlaylistItem pli = null; for (int i = n0 - 1; i >= 0; i--) { pli = playlist.getItemAt(i); if (pli.isSelected()) break; } // Play. if ((pli != null) && (pli.getTagInfo() != null)) { player.pressStop(); player.setCurrentSong(pli); playlist.setCursor(playlist.getIndex(pli)); player.pressStart(); } } else if (cmd.equals(PlayerActionEvent.ACPLREMOVE)) { delSelectedItems(); } else if (cmd.equals(PlayerActionEvent.ACPLADDFILE)) { ui.getAcPlAddPopup().setVisible(false); ui.getAcPlAdd().setVisible(true); File[] file = FileSelector.selectFile(player.getLoader(), FileSelector.OPEN, true, config.getExtensions(), ui.getResource("playlist.popup.add.file"), new File(config.getLastDir())); if (FileSelector.getInstance().getDirectory() != null) config.setLastDir(FileSelector.getInstance().getDirectory().getPath()); addFiles(file); } else if (cmd.equals(PlayerActionEvent.ACPLADDURL)) { ui.getAcPlAddPopup().setVisible(false); ui.getAcPlAdd().setVisible(true); UrlDialog UD = new UrlDialog(config.getTopParent(), ui.getResource("playlist.popup.add.url"), player.getLoader().getLocation().x, player.getLoader().getLocation().y + player.getHeight(), null); UD.show(); if (UD.getFile() != null) { PlaylistItem pli = new PlaylistItem(UD.getFile(), UD.getURL(), -1, false); playlist.appendItem(pli); resetScrollBar(); repaint(); } } else if (cmd.equals(PlayerActionEvent.ACPLADDDIR)) { ui.getAcPlAddPopup().setVisible(false); ui.getAcPlAdd().setVisible(true); File[] file = FileSelector.selectFile(player.getLoader(), FileSelector.DIRECTORY, false, "", ui.getResource("playlist.popup.add.dir"), new File(config.getLastDir())); if (FileSelector.getInstance().getDirectory() != null) config.setLastDir(FileSelector.getInstance().getDirectory().getPath()); if (file == null || !file[0].isDirectory()) return; // TODO - add message box for wrong filename addDir(file[0]); } else if (cmd.equals(PlayerActionEvent.ACPLREMOVEALL)) { ui.getAcPlRemovePopup().setVisible(false); ui.getAcPlRemove().setVisible(true); delAllItems(); } else if (cmd.equals(PlayerActionEvent.ACPLREMOVESEL)) { ui.getAcPlRemovePopup().setVisible(false); ui.getAcPlRemove().setVisible(true); delSelectedItems(); } else if (cmd.equals(PlayerActionEvent.ACPLREMOVEMISC)) { ui.getAcPlRemovePopup().setVisible(false); ui.getAcPlRemove().setVisible(true); // TODO } else if (cmd.equals(PlayerActionEvent.ACPLREMOVECROP)) { ui.getAcPlRemovePopup().setVisible(false); ui.getAcPlRemove().setVisible(true); // TODO } else if (cmd.equals(PlayerActionEvent.ACPLSELALL)) { ui.getAcPlSelectPopup().setVisible(false); ui.getAcPlSelect().setVisible(true); selFunctions(1); } else if (cmd.equals(PlayerActionEvent.ACPLSELINV)) { ui.getAcPlSelectPopup().setVisible(false); ui.getAcPlSelect().setVisible(true); selFunctions(-1); } else if (cmd.equals(PlayerActionEvent.ACPLSELZERO)) { ui.getAcPlSelectPopup().setVisible(false); ui.getAcPlSelect().setVisible(true); selFunctions(0); } else if (cmd.equals(PlayerActionEvent.ACPLMISCOPTS)) { ui.getAcPlMiscPopup().setVisible(false); ui.getAcPlMisc().setVisible(true); // TODO } else if (cmd.equals(PlayerActionEvent.ACPLMISCFILE)) { ui.getAcPlMiscPopup().setVisible(false); ui.getAcPlMisc().setVisible(true); popupFileInfo(); } else if (cmd.equals(PlayerActionEvent.ACPLMISCSORT)) { ui.getAcPlMiscPopup().setVisible(false); ui.getAcPlMisc().setVisible(true); // TODO } else if (cmd.equals(PlayerActionEvent.ACPLLISTLOAD)) { ui.getAcPlListPopup().setVisible(false); ui.getAcPlList().setVisible(true); File[] file = FileSelector.selectFile(player.getLoader(), FileSelector.OPEN, true, config.getExtensions(), ui.getResource("playlist.popup.list.load"), new File(config.getLastDir())); if (FileSelector.getInstance().getDirectory() != null) config.setLastDir(FileSelector.getInstance().getDirectory().getPath()); if ((file != null) && (file[0] != null)) { String fsFile = file[0].getName(); if ((fsFile.toLowerCase().endsWith(ui.getResource("playlist.extension.m3u"))) || (fsFile.toLowerCase().endsWith(ui.getResource("playlist.extension.pls")))) { if (player.loadPlaylist(config.getLastDir() + fsFile)) { config.setPlaylistFilename(config.getLastDir() + fsFile); playlist.begin(); playlist.setCursor(-1); // TODO topIndex = 0; } resetScrollBar(); repaint(); } } } else if (cmd.equals(PlayerActionEvent.ACPLLISTSAVE)) { ui.getAcPlListPopup().setVisible(false); ui.getAcPlList().setVisible(true); // TODO } else if (cmd.equals(PlayerActionEvent.ACPLLISTNEW)) { ui.getAcPlListPopup().setVisible(false); ui.getAcPlList().setVisible(true); // TODO } } /** * Display file info. */ public void popupFileInfo() { int n0 = playlist.getPlaylistSize(); PlaylistItem pli = null; for (int i = n0 - 1; i >= 0; i--) { pli = playlist.getItemAt(i); if (pli.isSelected()) break; } // Display Tag Info. if (pli != null) { TagInfo taginfo = pli.getTagInfo(); TagInfoFactory factory = TagInfoFactory.getInstance(); TagInfoDialog dialog = factory.getTagInfoDialog(taginfo); dialog.setLocation(player.getLoader().getLocation().x, player.getLoader().getLocation().y + player.getHeight()); dialog.show(); } } /** * Selection operation in pledit window * @param mode -1 : inverse selected items, 0 : select none, 1 : select all */ private void selFunctions(int mode) { int n0 = playlist.getPlaylistSize(); if (n0 == 0) return; for (int i = 0; i < n0; i++) { PlaylistItem pli = playlist.getItemAt(i); if (pli == null) break; if (mode == -1) { // inverse selection pli.setSelected(!pli.isSelected()); } else if (mode == 0) { // select none pli.setSelected(false); } else if (mode == 1) { // select all pli.setSelected(true); } } repaint(); } /** * Remove all items in playlist. */ private void delAllItems() { int n0 = playlist.getPlaylistSize(); if (n0 == 0) return; playlist.removeAllItems(); topIndex = 0; ui.getAcPlSlider().setValue(100); repaint(); } /** * Remove selected items in playlist. */ private void delSelectedItems() { int n0 = playlist.getPlaylistSize(); boolean brepaint = false; for (int i = n0 - 1; i >= 0; i--) { if (playlist.getItemAt(i).isSelected()) { playlist.removeItemAt(i); brepaint = true; } } if (brepaint) { int n = playlist.getPlaylistSize(); if (topIndex >= n) topIndex = n - 1; if (topIndex < 0) topIndex = 0; resetScrollBar(); repaint(); } } /** * Add file(s) to playlist. * @param file */ public void addFiles(File[] file) { if (file != null) { for (int i = 0; i < file.length; i++) { String fsFile = file[i].getName(); if ((!fsFile.toLowerCase().endsWith(ui.getResource("skin.extension"))) && (!fsFile.toLowerCase().endsWith(ui.getResource("playlist.extension.m3u"))) && (!fsFile.toLowerCase().endsWith(ui.getResource("playlist.extension.pls")))) { PlaylistItem pli = new PlaylistItem(fsFile, file[i].getAbsolutePath(), -1, true); playlist.appendItem(pli); resetScrollBar(); repaint(); } } } } /** * Handle mouse clicks on playlist. * @param evt */ protected void handleMouseClick(MouseEvent evt) { int x = evt.getX(); int y = evt.getY(); ui.getAcPlAddPopup().setVisible(false); ui.getAcPlAdd().setVisible(true); ui.getAcPlRemovePopup().setVisible(false); ui.getAcPlRemove().setVisible(true); ui.getAcPlSelectPopup().setVisible(false); ui.getAcPlSelect().setVisible(true); ui.getAcPlMiscPopup().setVisible(false); ui.getAcPlMisc().setVisible(true); ui.getAcPlListPopup().setVisible(false); ui.getAcPlList().setVisible(true); // Check select action if (ui.getPlaylistPanel().isInSelectArea(x, y)) { int index = getIndex(y); if (index != -1) { // PopUp if (javax.swing.SwingUtilities.isRightMouseButton(evt)) { if (fipopup != null) fipopup.show(this, x, y); } else { PlaylistItem pli = playlist.getItemAt(index); if (pli != null) { pli.setSelected(!pli.isSelected()); if ((evt.getClickCount() == 2) && (evt.getModifiers() == MouseEvent.BUTTON1_MASK)) { player.pressStop(); player.setCurrentSong(pli); playlist.setCursor(index); player.pressStart(); } } } repaint(); } } } /** * Process Drag&Drop * @param data */ public void processDnD(Object data) { log.debug("Playlist DnD"); // Looking for files to drop. if (data instanceof List) { List al = (List) data; if ((al != null) && (al.size() > 0)) { ArrayList fileList = new ArrayList(); ArrayList folderList = new ArrayList(); ListIterator li = al.listIterator(); while (li.hasNext()) { File f = (File) li.next(); if ((f.exists()) && (f.canRead())) { if (f.isFile()) fileList.add(f); else if (f.isDirectory()) folderList.add(f); } } addFiles(fileList); addDirs(folderList); } } else if (data instanceof String) { String files = (String) data; if ((files.length() > 0)) { ArrayList fileList = new ArrayList(); ArrayList folderList = new ArrayList(); StringTokenizer st = new StringTokenizer(files, System.getProperty("line.separator")); // Transfer files dropped. while (st.hasMoreTokens()) { String path = st.nextToken(); if (path.startsWith("file://")) { path = path.substring(7, path.length()); if (path.endsWith("\r")) path = path.substring(0, (path.length() - 1)); } File f = new File(path); if ((f.exists()) && (f.canRead())) { if (f.isFile()) fileList.add(f); else if (f.isDirectory()) folderList.add(f); } } addFiles(fileList); addDirs(folderList); } } else { log.info("Unknown dropped objects"); } } /** * Add files to playlistUI. * @param fileList */ public void addFiles(List fileList) { if (fileList.size() > 0) { File[] file = (File[]) fileList.toArray(new File[fileList.size()]); addFiles(file); } } /** * Add directories to playlistUI. * @param folderList */ public void addDirs(List folderList) { if (folderList.size() > 0) { ListIterator it = folderList.listIterator(); while (it.hasNext()) { addDir((File) it.next()); } } } /** * Compute slider value. */ private void resetScrollBar() { int n = playlist.getPlaylistSize(); float dx = (n < 1) ? 0 : ((float) topIndex / (n - 1)) * (100); ui.getAcPlSlider().setValue(100 - (int) dx); } public void paintList() { if (!isVisible()) return; else repaint(); } /* (non-Javadoc) * @see javax.swing.JComponent#paintComponent(java.awt.Graphics) */ public void paintComponent(Graphics g) { ui.getPlaylistPanel().paintBackground(g); ui.getPlaylistPanel().paintList(g); } /** * Add all files under this directory to play list. * @param fsFile */ private void addDir(File fsFile) { // Put all music file extension in a Vector String ext = config.getExtensions(); StringTokenizer st = new StringTokenizer(ext, ", "); if (exts == null) { exts = new Vector(); while (st.hasMoreTokens()) { exts.add("." + st.nextElement()); } } // recursive Thread addThread = new AddThread(fsFile); addThread.start(); // Refresh thread Thread refresh = new Thread("Refresh") { public void run() { while (isSearching) { resetScrollBar(); repaint(); try { Thread.sleep(4000); } catch (Exception ex) { } } } }; refresh.start(); } class AddThread extends Thread { private File fsFile; public AddThread(File fsFile) { super("Add"); this.fsFile = fsFile; } public void run() { isSearching = true; addMusicRecursive(fsFile, 0); isSearching = false; resetScrollBar(); repaint(); } } private void addMusicRecursive(File rootDir, int depth) { // We do not want waste time if (rootDir == null || depth > MAXDEPTH) return; String[] list = rootDir.list(); if (list == null) return; for (int i = 0; i < list.length; i++) { File ff = new File(rootDir, list[i]); if (ff.isDirectory()) addMusicRecursive(ff, depth + 1); else { if (isMusicFile(list[i])) { PlaylistItem pli = new PlaylistItem(list[i], rootDir + File.separator + list[i], -1, true); playlist.appendItem(pli); } } } } private boolean isMusicFile(String ff) { int sz = exts.size(); for (int i = 0; i < sz; i++) { String ext = exts.elementAt(i).toString().toLowerCase(); // TODO : Improve if (ext.equalsIgnoreCase(".wsz") || ext.equalsIgnoreCase(".m3u") || ext.equalsIgnoreCase(".pls")) continue; if (ff.toLowerCase().endsWith(exts.elementAt(i).toString().toLowerCase())) return true; } return false; } }
Java
/* * SpectrumTimeAnalyzer. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp.visual.ui; import java.awt.Color; import java.awt.Cursor; import java.awt.Graphics; import java.awt.Image; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; import javax.sound.sampled.SourceDataLine; import javax.swing.JPanel; import javazoom.jlgui.player.amp.skin.AbsoluteConstraints; import kj.dsp.KJDigitalSignalProcessingAudioDataConsumer; import kj.dsp.KJDigitalSignalProcessor; import kj.dsp.KJFFT; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class SpectrumTimeAnalyzer extends JPanel implements KJDigitalSignalProcessor { private static Log log = LogFactory.getLog(SpectrumTimeAnalyzer.class); public static final int DISPLAY_MODE_SCOPE = 0; public static final int DISPLAY_MODE_SPECTRUM_ANALYSER = 1; public static final int DISPLAY_MODE_OFF = 2; public static final int DEFAULT_WIDTH = 256; public static final int DEFAULT_HEIGHT = 128; public static final int DEFAULT_FPS = 50; public static final int DEFAULT_SPECTRUM_ANALYSER_FFT_SAMPLE_SIZE = 512; public static final int DEFAULT_SPECTRUM_ANALYSER_BAND_COUNT = 19; public static final float DEFAULT_SPECTRUM_ANALYSER_DECAY = 0.05f; public static final int DEFAULT_SPECTRUM_ANALYSER_PEAK_DELAY = 20; public static final float DEFAULT_SPECTRUM_ANALYSER_PEAK_DELAY_FPS_RATIO = 0.4f; public static final float DEFAULT_SPECTRUM_ANALYSER_PEAK_DELAY_FPS_RATIO_RANGE = 0.1f; public static final float MIN_SPECTRUM_ANALYSER_DECAY = 0.02f; public static final float MAX_SPECTRUM_ANALYSER_DECAY = 0.08f; public static final Color DEFAULT_BACKGROUND_COLOR = new Color(0, 0, 128); public static final Color DEFAULT_SCOPE_COLOR = new Color(255, 192, 0); public static final float DEFAULT_VU_METER_DECAY = 0.02f; private Image bi; private int displayMode = DISPLAY_MODE_SCOPE; private Color scopeColor = DEFAULT_SCOPE_COLOR; private Color[] spectrumAnalyserColors = getDefaultSpectrumAnalyserColors(); private KJDigitalSignalProcessingAudioDataConsumer dsp = null; private boolean dspStarted = false; private Color peakColor = null; private int[] peaks = new int[DEFAULT_SPECTRUM_ANALYSER_BAND_COUNT]; private int[] peaksDelay = new int[DEFAULT_SPECTRUM_ANALYSER_BAND_COUNT]; private int peakDelay = DEFAULT_SPECTRUM_ANALYSER_PEAK_DELAY; private boolean peaksEnabled = true; private List visColors = null; private int barOffset = 1; private int width; private int height; private int height_2; // -- Spectrum analyser variables. private KJFFT fft; private float[] old_FFT; private int saFFTSampleSize; private int saBands; private float saColorScale; private float saMultiplier; private float saDecay = DEFAULT_SPECTRUM_ANALYSER_DECAY; private float sad; private SourceDataLine m_line = null; // -- VU Meter private float oldLeft; private float oldRight; // private float vuAverage; // private float vuSamples; private float vuDecay = DEFAULT_VU_METER_DECAY; private float vuColorScale; // -- FPS calulations. private long lfu = 0; private int fc = 0; private int fps = DEFAULT_FPS; private boolean showFPS = false; private AbsoluteConstraints constraints = null; // private Runnable PAINT_SYNCHRONIZER = new AWTPaintSynchronizer(); public SpectrumTimeAnalyzer() { setOpaque(false); initialize(); } public void setConstraints(AbsoluteConstraints cnts) { constraints = cnts; } public AbsoluteConstraints getConstraints() { return constraints; } public boolean isPeaksEnabled() { return peaksEnabled; } public void setPeaksEnabled(boolean peaksEnabled) { this.peaksEnabled = peaksEnabled; } public int getFps() { return fps; } public void setFps(int fps) { this.fps = fps; } /** * Starts DSP. * @param line */ public void startDSP(SourceDataLine line) { if (displayMode == DISPLAY_MODE_OFF) return; if (line != null) m_line = line; if (dsp == null) { dsp = new KJDigitalSignalProcessingAudioDataConsumer(2048, fps); dsp.add(this); } if ((dsp != null) && (m_line != null)) { if (dspStarted == true) { stopDSP(); } dsp.start(m_line); dspStarted = true; log.debug("DSP started"); } } /** * Stop DSP. */ public void stopDSP() { if (dsp != null) { dsp.stop(); dspStarted = false; log.debug("DSP stopped"); } } /** * Close DSP */ public void closeDSP() { if (dsp != null) { stopDSP(); dsp = null; log.debug("DSP closed"); } } /** * Setup DSP. * @param line */ public void setupDSP(SourceDataLine line) { if (dsp != null) { int channels = line.getFormat().getChannels(); if (channels == 1) dsp.setChannelMode(KJDigitalSignalProcessingAudioDataConsumer.CHANNEL_MODE_MONO); else dsp.setChannelMode(KJDigitalSignalProcessingAudioDataConsumer.CHANNEL_MODE_STEREO); int bits = line.getFormat().getSampleSizeInBits(); if (bits == 8) dsp.setSampleType(KJDigitalSignalProcessingAudioDataConsumer.SAMPLE_TYPE_EIGHT_BIT); else dsp.setSampleType(KJDigitalSignalProcessingAudioDataConsumer.SAMPLE_TYPE_SIXTEEN_BIT); } } /** * Write PCM data to DSP. * @param pcmdata */ public void writeDSP(byte[] pcmdata) { if ((dsp != null) && (dspStarted == true)) dsp.writeAudioData(pcmdata); } /** * Return DSP. * @return */ public KJDigitalSignalProcessingAudioDataConsumer getDSP() { return dsp; } /** * Set visual colors from skin. * @param viscolor */ public void setVisColor(String viscolor) { ArrayList visColors = new ArrayList(); viscolor = viscolor.toLowerCase(); ByteArrayInputStream in = new ByteArrayInputStream(viscolor.getBytes()); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); try { String line = null; while ((line = bin.readLine()) != null) { visColors.add(getColor(line)); } Color[] colors = new Color[visColors.size()]; visColors.toArray(colors); Color[] specColors = new Color[15]; System.arraycopy(colors, 2, specColors, 0, 15); List specList = Arrays.asList(specColors); Collections.reverse(specList); specColors = (Color[]) specList.toArray(specColors); setSpectrumAnalyserColors(specColors); setBackground((Color) visColors.get(0)); if (visColors.size()>23) setPeakColor((Color) visColors.get(23)); if (visColors.size()>18) setScopeColor((Color) visColors.get(18)); } catch (IOException ex) { log.warn("Cannot parse viscolors", ex); } finally { try { if (bin != null) bin.close(); } catch (IOException e) { } } } /** * Set visual peak color. * @param c */ public void setPeakColor(Color c) { peakColor = c; } /** * Set peak falloff delay. * @param framestowait */ public void setPeakDelay(int framestowait) { int min = (int) Math.round((DEFAULT_SPECTRUM_ANALYSER_PEAK_DELAY_FPS_RATIO - DEFAULT_SPECTRUM_ANALYSER_PEAK_DELAY_FPS_RATIO_RANGE) * fps); int max = (int) Math.round((DEFAULT_SPECTRUM_ANALYSER_PEAK_DELAY_FPS_RATIO + DEFAULT_SPECTRUM_ANALYSER_PEAK_DELAY_FPS_RATIO_RANGE) * fps); if ((framestowait >= min) && (framestowait <= max)) { peakDelay = framestowait; } else { peakDelay = (int) Math.round(DEFAULT_SPECTRUM_ANALYSER_PEAK_DELAY_FPS_RATIO * fps); } } /** * Return peak falloff delay * @return int framestowait */ public int getPeakDelay() { return peakDelay; } /** * Convert string to color. * @param linecolor * @return */ public Color getColor(String linecolor) { Color color = Color.BLACK; StringTokenizer st = new StringTokenizer(linecolor, ","); int red = 0, green = 0, blue = 0; try { if (st.hasMoreTokens()) red = Integer.parseInt(st.nextToken().trim()); if (st.hasMoreTokens()) green = Integer.parseInt(st.nextToken().trim()); if (st.hasMoreTokens()) { String blueStr = st.nextToken().trim(); if (blueStr.length() > 3) blueStr = (blueStr.substring(0, 3)).trim(); blue = Integer.parseInt(blueStr); } color = new Color(red, green, blue); } catch (NumberFormatException e) { log.debug("Cannot parse viscolor : "+e.getMessage()); } return color; } private void computeColorScale() { saColorScale = ((float) spectrumAnalyserColors.length / height) * barOffset * 1.0f; vuColorScale = ((float) spectrumAnalyserColors.length / (width - 32)) * 2.0f; } private void computeSAMultiplier() { saMultiplier = (saFFTSampleSize / 2) / saBands; } private void drawScope(Graphics pGrp, float[] pSample) { pGrp.setColor(scopeColor); int wLas = (int) (pSample[0] * (float) height_2) + height_2; int wSt = 2; for (int a = wSt, c = 0; c < width; a += wSt, c++) { int wAs = (int) (pSample[a] * (float) height_2) + height_2; pGrp.drawLine(c, wLas, c + 1, wAs); wLas = wAs; } } private void drawSpectrumAnalyser(Graphics pGrp, float[] pSample, float pFrrh) { float c = 0; float[] wFFT = fft.calculate(pSample); float wSadfrr = (saDecay * pFrrh); float wBw = ((float) width / (float) saBands); for (int a = 0, bd = 0; bd < saBands; a += saMultiplier, bd++) { float wFs = 0; // -- Average out nearest bands. for (int b = 0; b < saMultiplier; b++) { wFs += wFFT[a + b]; } // -- Log filter. wFs = (wFs * (float) Math.log(bd + 2)); if (wFs > 1.0f) { wFs = 1.0f; } // -- Compute SA decay... if (wFs >= (old_FFT[a] - wSadfrr)) { old_FFT[a] = wFs; } else { old_FFT[a] -= wSadfrr; if (old_FFT[a] < 0) { old_FFT[a] = 0; } wFs = old_FFT[a]; } drawSpectrumAnalyserBar(pGrp, (int) c, height, (int) wBw - 1, (int) (wFs * height), bd); c += wBw; } } private void drawVUMeter(Graphics pGrp, float[] pLeft, float[] pRight, float pFrrh) { if (displayMode == DISPLAY_MODE_OFF) return; float wLeft = 0.0f; float wRight = 0.0f; float wSadfrr = (vuDecay * pFrrh); for (int a = 0; a < pLeft.length; a++) { wLeft += Math.abs(pLeft[a]); wRight += Math.abs(pRight[a]); } wLeft = ((wLeft * 2.0f) / (float) pLeft.length); wRight = ((wRight * 2.0f) / (float) pRight.length); if (wLeft > 1.0f) { wLeft = 1.0f; } if (wRight > 1.0f) { wRight = 1.0f; } // vuAverage += ( ( wLeft + wRight ) / 2.0f ); // vuSamples++; // // if ( vuSamples > 128 ) { // vuSamples /= 2.0f; // vuAverage /= 2.0f; // } if (wLeft >= (oldLeft - wSadfrr)) { oldLeft = wLeft; } else { oldLeft -= wSadfrr; if (oldLeft < 0) { oldLeft = 0; } } if (wRight >= (oldRight - wSadfrr)) { oldRight = wRight; } else { oldRight -= wSadfrr; if (oldRight < 0) { oldRight = 0; } } int wHeight = (height >> 1) - 24; drawVolumeMeterBar(pGrp, 16, 16, (int) (oldLeft * (float) (width - 32)), wHeight); // drawVolumeMeterBar( pGrp, 16, wHeight + 22, (int)( ( vuAverage / vuSamples ) * (float)( width - 32 ) ), 4 ); drawVolumeMeterBar(pGrp, 16, wHeight + 32, (int) (oldRight * (float) (width - 32)), wHeight); // pGrp.fillRect( 16, 16, (int)( oldLeft * (float)( width - 32 ) ), wHeight ); // pGrp.fillRect( 16, 64, (int)( oldRight * (float)( width - 32 ) ), wHeight ); } private void drawSpectrumAnalyserBar(Graphics pGraphics, int pX, int pY, int pWidth, int pHeight, int band) { float c = 0; for (int a = pY; a >= pY - pHeight; a -= barOffset) { c += saColorScale; if (c < spectrumAnalyserColors.length) { pGraphics.setColor(spectrumAnalyserColors[(int) c]); } pGraphics.fillRect(pX, a, pWidth, 1); } if ((peakColor != null) && (peaksEnabled == true)) { pGraphics.setColor(peakColor); if (pHeight > peaks[band]) { peaks[band] = pHeight; peaksDelay[band] = peakDelay; } else { peaksDelay[band]--; if (peaksDelay[band] < 0) peaks[band]--; if (peaks[band] < 0) peaks[band] = 0; } pGraphics.fillRect(pX, pY - peaks[band], pWidth, 1); } } private void drawVolumeMeterBar(Graphics pGraphics, int pX, int pY, int pWidth, int pHeight) { float c = 0; for (int a = pX; a <= pX + pWidth; a += 2) { c += vuColorScale; if (c < 256.0f) { pGraphics.setColor(spectrumAnalyserColors[(int) c]); } pGraphics.fillRect(a, pY, 1, pHeight); } } private synchronized Image getDoubleBuffer() { if (bi == null || (bi.getWidth(null) != getSize().width || bi.getHeight(null) != getSize().height)) { width = getSize().width; height = getSize().height; height_2 = height >> 1; computeColorScale(); bi = getGraphicsConfiguration().createCompatibleVolatileImage(width, height); } return bi; } public static Color[] getDefaultSpectrumAnalyserColors() { Color[] wColors = new Color[256]; for (int a = 0; a < 128; a++) { wColors[a] = new Color(0, (a >> 1) + 192, 0); } for (int a = 0; a < 64; a++) { wColors[a + 128] = new Color(a << 2, 255, 0); } for (int a = 0; a < 64; a++) { wColors[a + 192] = new Color(255, 255 - (a << 2), 0); } return wColors; } /** * @return Returns the current display mode, DISPLAY_MODE_SCOPE or DISPLAY_MODE_SPECTRUM_ANALYSER. */ public int getDisplayMode() { return displayMode; } /** * @return Returns the current number of bands displayed by the spectrum analyser. */ public int getSpectrumAnalyserBandCount() { return saBands; } /** * @return Returns the decay rate of the spectrum analyser's bands. */ public float getSpectrumAnalyserDecay() { return saDecay; } /** * @return Returns the color the scope is rendered in. */ public Color getScopeColor() { return scopeColor; } /** * @return Returns the color scale used to render the spectrum analyser bars. */ public Color[] getSpectrumAnalyserColors() { return spectrumAnalyserColors; } private void initialize() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); setBackground(DEFAULT_BACKGROUND_COLOR); prepareDisplayToggleListener(); setSpectrumAnalyserBandCount(DEFAULT_SPECTRUM_ANALYSER_BAND_COUNT); setSpectrumAnalyserFFTSampleSize(DEFAULT_SPECTRUM_ANALYSER_FFT_SAMPLE_SIZE); } /** * @return Returns 'true' if "Frames Per Second" are being calculated and displayed. */ public boolean isShowingFPS() { return showFPS; } public void paintComponent(Graphics pGraphics) { if (displayMode == DISPLAY_MODE_OFF) return; if (dspStarted) { pGraphics.drawImage(getDoubleBuffer(), 0, 0, null); } else { super.paintComponent(pGraphics); } } private void prepareDisplayToggleListener() { setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent pEvent) { if (pEvent.getButton() == MouseEvent.BUTTON1) { if (displayMode + 1 > 1) { displayMode = 0; } else { displayMode++; } } } }); } /* (non-Javadoc) * @see kj.dsp.KJDigitalSignalProcessor#process(float[], float[], float) */ public synchronized void process(float[] pLeft, float[] pRight, float pFrameRateRatioHint) { if (displayMode == DISPLAY_MODE_OFF) return; Graphics wGrp = getDoubleBuffer().getGraphics(); wGrp.setColor(getBackground()); wGrp.fillRect(0, 0, getSize().width, getSize().height); switch (displayMode) { case DISPLAY_MODE_SCOPE: drawScope(wGrp, stereoMerge(pLeft, pRight)); break; case DISPLAY_MODE_SPECTRUM_ANALYSER: drawSpectrumAnalyser(wGrp, stereoMerge(pLeft, pRight), pFrameRateRatioHint); break; case DISPLAY_MODE_OFF: drawVUMeter(wGrp, pLeft, pRight, pFrameRateRatioHint); break; } // -- Show FPS if necessary. if (showFPS) { // -- Calculate FPS. if (System.currentTimeMillis() >= lfu + 1000) { lfu = System.currentTimeMillis(); fps = fc; fc = 0; } fc++; wGrp.setColor(Color.yellow); wGrp.drawString("FPS: " + fps + " (FRRH: " + pFrameRateRatioHint + ")", 0, height - 1); } if (getGraphics() != null) getGraphics().drawImage(getDoubleBuffer(), 0, 0, null); // repaint(); // try { // EventQueue.invokeLater( new AWTPaintSynchronizer() ); // } catch ( Exception pEx ) { // // -- Ignore exception. // pEx.printStackTrace(); // } } /** * Sets the current display mode. * * @param pMode Must be either DISPLAY_MODE_SCOPE or DISPLAY_MODE_SPECTRUM_ANALYSER. */ public synchronized void setDisplayMode(int pMode) { displayMode = pMode; } /** * Sets the color of the scope. * * @param pColor */ public synchronized void setScopeColor(Color pColor) { scopeColor = pColor; } /** * When 'true' is passed as a parameter, will overlay the "Frames Per Seconds" * achieved by the component. * * @param pState */ public synchronized void setShowFPS(boolean pState) { showFPS = pState; } /** * Sets the numbers of bands rendered by the spectrum analyser. * * @param pCount Cannot be more than half the "FFT sample size". */ public synchronized void setSpectrumAnalyserBandCount(int pCount) { saBands = pCount; peaks = new int[saBands]; peaksDelay = new int[saBands]; computeSAMultiplier(); } /** * Sets the spectrum analyser band decay rate. * * @param pDecay Must be a number between 0.0 and 1.0 exclusive. */ public synchronized void setSpectrumAnalyserDecay(float pDecay) { if ((pDecay >= MIN_SPECTRUM_ANALYSER_DECAY) && (pDecay <= MAX_SPECTRUM_ANALYSER_DECAY)) { saDecay = pDecay; } else saDecay = DEFAULT_SPECTRUM_ANALYSER_DECAY; } /** * Sets the spectrum analyser color scale. * * @param pColors Any amount of colors may be used. Must not be null. */ public synchronized void setSpectrumAnalyserColors(Color[] pColors) { spectrumAnalyserColors = pColors; computeColorScale(); } /** * Sets the FFT sample size to be just for calculating the spectrum analyser * values. The default is 512. * * @param pSize Cannot be more than the size of the sample provided by the DSP. */ public synchronized void setSpectrumAnalyserFFTSampleSize(int pSize) { saFFTSampleSize = pSize; fft = new KJFFT(saFFTSampleSize); old_FFT = new float[saFFTSampleSize]; computeSAMultiplier(); } private float[] stereoMerge(float[] pLeft, float[] pRight) { for (int a = 0; a < pLeft.length; a++) { pLeft[a] = (pLeft[a] + pRight[a]) / 2.0f; } return pLeft; } /*public void update(Graphics pGraphics) { // -- Prevent AWT from clearing background. paint(pGraphics); }*/ }
Java
/* * Loader. * * JavaZOOM : jlgui@javazoom.net * http://www.javazoom.net * *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package javazoom.jlgui.player.amp; import java.awt.Point; public interface Loader { public void loaded(); public void close(); public void minimize(); public Point getLocation(); public void togglePlaylist(boolean enabled); public void toggleEqualizer(boolean enabled); }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package bean; import java.beans.*; import java.io.Serializable; import javazoom.jlgui.basicplayer.BasicPlayer; import javazoom.jlgui.*; import java.io.File; /** * * @author Robert Alvarado */ public class Music implements Serializable { private BasicPlayer player = new BasicPlayer(); public void Play() throws Exception { player.play(); } public void AbrirFichero(String ruta) throws Exception { player.open(new File(ruta)); } public void Pausa() throws Exception { player.pause(); } public void Continuar() throws Exception { player.resume(); } public void Stop() throws Exception { player.stop(); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package bean; import java.io.Serializable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.*; import javax.swing.JLabel; import javax.swing.Timer; /** * * @author Robert Alvarado */ public class Reloj extends JLabel { private Timer timer; int tiempo = 0; int tiempo2 = 0; int tiempo3 = 0; private String MSegundo = "00"; private String Segundo = "0"; private String Minuto = "0"; String Texto = "00:00:00"; public void actualizacion(final JLabel L) { timer = new Timer(1, new ActionListener() { public void actionPerformed(ActionEvent e) { tiempo++; MSegundo = Integer.toString(tiempo); if (tiempo == 59) { tiempo2++; tiempo = 0; Segundo = Integer.toString(tiempo2); if (tiempo2 == 59) { tiempo3++; tiempo2 = 0; Minuto = Integer.toString(tiempo3); } } if (Integer.parseInt(Minuto) <= 9) { Texto = "0" + Minuto + ":"; } else { Texto = Minuto + ":"; } if (Integer.parseInt(Segundo) <= 9) { Texto = Texto + "0" + Segundo + ":"; } else { Texto = Texto + Segundo + ":"; } if (Integer.parseInt(MSegundo) <= 9) { Texto = Texto + "0" + MSegundo; } else { Texto = Texto + MSegundo; } L.setText(Texto); } }); } public void Parar() { timer.stop(); } public void Iniciar(){ timer.start(); } public void Reiniciar(JLabel L){ this.Minuto = "0"; this.Segundo = "0"; this.MSegundo = "0"; tiempo = 0; tiempo2 = 0; tiempo3 = 0; Texto = "00:00:00"; L.setText(Texto); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package bean; import java.beans.*; import java.io.Serializable; import javazoom.jlgui.basicplayer.BasicPlayer; import javazoom.jlgui.*; import java.io.File; /** * * @author Robert Alvarado */ public class Music implements Serializable { private BasicPlayer player = new BasicPlayer(); public void Play() throws Exception { player.play(); } public void AbrirFichero(String ruta) throws Exception { player.open(new File(ruta)); } public void Pausa() throws Exception { player.pause(); } public void Continuar() throws Exception { player.resume(); } public void Stop() throws Exception { player.stop(); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package BD; import bean.Conexion; /** * * @author Robert Alvarado */ public class ConexionDAO { public ConexionDAO() { super(); Conexion.establecerPropiedadesConexion("org.postgresql.Driver", "jdbc:postgresql://localhost:5432/", "BD1-1", "postgres", "postgress"); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Controlador; import Modelo.Jugador; import Modelo.ModPartida; import Vista.VistaPart; import bean.Music; import java.awt.Color; import java.sql.SQLException; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.JLabel; import bean.Reloj; /** * * @author USUARIO */ public class ContPartida { private VistaPart VP; private ModPartida M; private Vector<JLabel> labeles = new Vector<JLabel>(); private Vector Palabras = new Vector(); private Reloj R = new Reloj(); Music Reproducion = new Music(); private int Nivel = 0; ContPartida(VistaPart VP, ModPartida M, int Nivel) throws SQLException, Exception { this.Reproducion.AbrirFichero("C:/Documents and Settings/Robert Alvarado/Escritorio/FINAL_COLOR/1-1-primer-proyecto/src/Musica/1.mp3"); this.Reproducion.Play(); this.VP = VP; this.M = M; this.VP.setVisible(true); this.Nivel = Nivel + 1; this.agregarVectLabel(); R.actualizacion(this.VP.getReloj()); this.IniciarPartida(); } public void IniciarPartida() throws SQLException { R.Parar(); R.Reiniciar(this.VP.getReloj()); R.Iniciar(); this.VP.HablitarRegistro(false); this.M.setError(0); this.M.setAcierto(0); this.Imagenes(); if(this.Nivel == 1){ this.M.BuscarPalabra(); this.LimpiarLabeles(); }else if(this.Nivel == 2){ this.M.BuscarPalabra2(); this.LimpiarLabeles2(); this.LimpiarVacios(" ", " "); }else{ this.M.BuscarPalabra3(); this.LimpiarLabeles2(); this.LimpiarVacios(" ", " "); } this.HabilitarTeclado(true); this.VP.setMensaje("", false, Color.RED); } public Reloj getR() { return R; } public void ContarError() { this.M.ContarError(); this.Imagenes(); } public void Salir() throws Exception{ this.Reproducion.Stop(); this.VP.dispose(); } public void Imagenes() { switch (this.M.getError()) { case 0: this.VP.setAhorcado("Imagenes/Aho00.gif"); break; case 1: this.VP.setAhorcado("Imagenes/Aho01.gif"); break; case 2: this.VP.setAhorcado("Imagenes/Aho0.gif"); break; case 3: this.VP.setAhorcado("Imagenes/Aho2.gif"); break; case 4: this.VP.setAhorcado("Imagenes/Aho3.gif"); break; case 5: this.VP.setAhorcado("Imagenes/Aho4.gif"); break; case 6: this.VP.setAhorcado("Imagenes/Aho5.gif"); break; case 7: this.VP.setAhorcado("Imagenes/Aho6.gif"); break; case 8: this.VP.setAhorcado("Imagenes/Aho7.gif"); break; } } public void agregarVectLabel() { this.labeles.add(this.VP.getjLabel1()); this.labeles.add(this.VP.getjLabel2()); this.labeles.add(this.VP.getjLabel3()); this.labeles.add(this.VP.getjLabel4()); this.labeles.add(this.VP.getjLabel5()); this.labeles.add(this.VP.getjLabel6()); this.labeles.add(this.VP.getjLabel7()); this.labeles.add(this.VP.getjLabel8()); this.labeles.add(this.VP.getjLabel9()); this.labeles.add(this.VP.getjLabel10()); this.labeles.add(this.VP.getjLabel11()); this.labeles.add(this.VP.getjLabel12()); this.labeles.add(this.VP.getjLabel13()); this.labeles.add(this.VP.getjLabel14()); this.labeles.add(this.VP.getjLabel15()); this.labeles.add(this.VP.getjLabel16()); this.labeles.add(this.VP.getjLabel17()); this.labeles.add(this.VP.getjLabel18()); this.labeles.add(this.VP.getjLabel19()); this.labeles.add(this.VP.getjLabel20()); this.labeles.add(this.VP.getjLabel21()); this.labeles.add(this.VP.getjLabel22()); this.labeles.add(this.VP.getjLabel23()); this.labeles.add(this.VP.getjLabel24()); this.labeles.add(this.VP.getjLabel25()); this.labeles.add(this.VP.getjLabel26()); this.labeles.add(this.VP.getjLabel27()); this.labeles.add(this.VP.getjLabel28()); this.labeles.add(this.VP.getjLabel29()); this.labeles.add(this.VP.getjLabel30()); this.labeles.add(this.VP.getjLabel31()); this.labeles.add(this.VP.getjLabel32()); this.labeles.add(this.VP.getjLabel33()); this.labeles.add(this.VP.getjLabel34()); this.labeles.add(this.VP.getjLabel35()); this.labeles.add(this.VP.getjLabel36()); this.labeles.add(this.VP.getjLabel37()); this.labeles.add(this.VP.getjLabel38()); this.labeles.add(this.VP.getjLabel39()); this.labeles.add(this.VP.getjLabel40()); this.labeles.add(this.VP.getjLabel41()); this.labeles.add(this.VP.getjLabel42()); this.labeles.add(this.VP.getjLabel43()); this.labeles.add(this.VP.getjLabel44()); this.labeles.add(this.VP.getjLabel45()); this.labeles.add(this.VP.getjLabel46()); this.labeles.add(this.VP.getjLabel47()); this.labeles.add(this.VP.getjLabel48()); this.labeles.add(this.VP.getjLabel49()); this.labeles.add(this.VP.getjLabel50()); this.labeles.add(this.VP.getjLabel51()); this.labeles.add(this.VP.getjLabel52()); this.labeles.add(this.VP.getjLabel53()); this.labeles.add(this.VP.getjLabel54()); this.labeles.add(this.VP.getjLabel55()); this.labeles.add(this.VP.getjLabel56()); this.labeles.add(this.VP.getjLabel57()); this.labeles.add(this.VP.getjLabel58()); this.labeles.add(this.VP.getjLabel59()); this.labeles.add(this.VP.getjLabel60()); this.labeles.add(this.VP.getjLabel61()); this.labeles.add(this.VP.getjLabel62()); this.labeles.add(this.VP.getjLabel63()); this.labeles.add(this.VP.getjLabel64()); this.labeles.add(this.VP.getjLabel65()); this.labeles.add(this.VP.getjLabel66()); this.labeles.add(this.VP.getjLabel67()); this.labeles.add(this.VP.getjLabel68()); this.labeles.add(this.VP.getjLabel69()); this.labeles.add(this.VP.getjLabel70()); this.labeles.add(this.VP.getjLabel71()); this.labeles.add(this.VP.getjLabel72()); this.labeles.add(this.VP.getjLabel73()); this.labeles.add(this.VP.getjLabel74()); this.labeles.add(this.VP.getjLabel75()); this.labeles.add(this.VP.getjLabel76()); this.labeles.add(this.VP.getjLabel77()); this.labeles.add(this.VP.getjLabel78()); this.labeles.add(this.VP.getjLabel79()); this.labeles.add(this.VP.getjLabel80()); this.labeles.add(this.VP.getjLabel81()); this.labeles.add(this.VP.getjLabel82()); this.labeles.add(this.VP.getjLabel83()); this.labeles.add(this.VP.getjLabel84()); this.labeles.add(this.VP.getjLabel85()); this.labeles.add(this.VP.getjLabel86()); this.labeles.add(this.VP.getjLabel87()); this.labeles.add(this.VP.getjLabel88()); this.labeles.add(this.VP.getjLabel89()); this.labeles.add(this.VP.getjLabel90()); this.labeles.add(this.VP.getjLabel91()); this.labeles.add(this.VP.getjLabel92()); this.labeles.add(this.VP.getjLabel93()); this.labeles.add(this.VP.getjLabel94()); this.labeles.add(this.VP.getjLabel95()); this.labeles.add(this.VP.getjLabel96()); this.labeles.add(this.VP.getjLabel97()); this.labeles.add(this.VP.getjLabel98()); this.labeles.add(this.VP.getjLabel99()); this.labeles.add(this.VP.getjLabel100()); this.labeles.add(this.VP.getjLabel101()); this.labeles.add(this.VP.getjLabel102()); this.labeles.add(this.VP.getjLabel103()); this.labeles.add(this.VP.getjLabel104()); this.labeles.add(this.VP.getjLabel105()); this.labeles.add(this.VP.getjLabel106()); this.labeles.add(this.VP.getjLabel107()); this.labeles.add(this.VP.getjLabel108()); this.labeles.add(this.VP.getjLabel109()); this.labeles.add(this.VP.getjLabel110()); this.labeles.add(this.VP.getjLabel111()); this.labeles.add(this.VP.getjLabel112()); this.labeles.add(this.VP.getjLabel113()); this.labeles.add(this.VP.getjLabel114()); this.labeles.add(this.VP.getjLabel115()); this.labeles.add(this.VP.getjLabel116()); this.labeles.add(this.VP.getjLabel117()); this.labeles.add(this.VP.getjLabel118()); this.labeles.add(this.VP.getjLabel119()); this.labeles.add(this.VP.getjLabel120()); this.labeles.add(this.VP.getjLabel121()); this.labeles.add(this.VP.getjLabel122()); this.labeles.add(this.VP.getjLabel123()); } public void LimpiarLabeles() { for (int a = 0; a < this.labeles.size(); a++) { this.labeles.elementAt(a).setVisible(true); } for (int a = 0; a < this.M.getPalabraOri().size(); a++) { this.labeles.elementAt(a).setText("_"); } for (int a = (this.M.getPalabraOri().size()); a <= 122; a++) { this.labeles.elementAt(a).setVisible(false); } } public void LimpiarLabeles2() { int P = 0; for (int a = 0; a < this.M.getPalabraOri2().size(); a++) { if (this.M.getPalabraOri2().elementAt(a) == " ") { P++; } } P++; this.Palabras.clear(); String Frase = ""; for (int a = 0; a < this.M.getPalabraOri2().size(); a++) { if (this.M.getPalabraOri2().elementAt(a).toString().charAt(0) == ' ') { this.Palabras.add(Frase); Frase = ""; } else if (a == this.M.getPalabraOri2().size() - 1) { Frase = Frase + this.M.getPalabraOri2().elementAt(a); this.Palabras.add(Frase); Frase = ""; } else { Frase = Frase + this.M.getPalabraOri2().elementAt(a); } } for (int a = 0; a < this.labeles.size(); a++) { this.labeles.elementAt(a).setVisible(true); } this.M.getPalabraOri2().clear(); String Frase2 = ""; int Fila1 = 33; int Fila2 = 30; int Fila3 = 30; int Fila4 = 30; boolean R1 = false; boolean R2 = false; boolean R3 = false; boolean R4 = false; for (int u = 0; u < this.Palabras.size(); u++) { Frase2 = ""; Frase2 = this.Palabras.elementAt(u).toString(); if (Frase2.length() <= Fila1) { Fila1 = Fila1 - Frase2.length() - 1; for (int g = 0; g < Frase2.length(); g++) { this.M.getPalabraOri2().add(Frase2.charAt(g)); } this.M.getPalabraOri2().add(" "); } else if (R1 == false) { for (int y = 0; y < Fila1; y++) { this.M.getPalabraOri2().add(" "); this.labeles.elementAt(32 - y).setVisible(false); } if (Frase2.length() <= Fila2) { Fila2 = Fila2 - Frase2.length() - 1; for (int g = 0; g < Frase2.length(); g++) { this.M.getPalabraOri2().add(Frase2.charAt(g)); } this.M.getPalabraOri2().add(" "); } R1 = true; } else if (Frase2.length() <= Fila2) { Fila2 = Fila2 - Frase2.length() - 1; for (int g = 0; g < Frase2.length(); g++) { this.M.getPalabraOri2().add(Frase2.charAt(g)); } this.M.getPalabraOri2().add(" "); } else if (R2 == false) { for (int y = 0; y < Fila2; y++) { this.M.getPalabraOri2().add(" "); this.labeles.elementAt(62 - y).setVisible(false); } if (Frase2.length() <= Fila3) { Fila3 = Fila3 - Frase2.length() - 1; for (int g = 0; g < Frase2.length(); g++) { this.M.getPalabraOri2().add(Frase2.charAt(g)); } this.M.getPalabraOri2().add(" "); } R2 = true; } else if (Frase2.length() <= Fila3) { Fila3 = Fila3 - Frase2.length() - 1; for (int g = 0; g < Frase2.length(); g++) { this.M.getPalabraOri2().add(Frase2.charAt(g)); } this.M.getPalabraOri2().add(" "); } else if (R3 == false) { for (int y = 0; y < Fila3; y++) { this.M.getPalabraOri2().add(" "); this.labeles.elementAt(92 - y).setVisible(false); } if (Frase2.length() <= Fila4) { Fila4 = Fila4 - Frase2.length() - 1; for (int g = 0; g < Frase2.length(); g++) { this.M.getPalabraOri2().add(Frase2.charAt(g)); } this.M.getPalabraOri2().add(" "); R3 = true; } } else if (Frase2.length() <= Fila4) { Fila4 = Fila4 - Frase2.length() - 1; for (int g = 0; g < Frase2.length(); g++) { this.M.getPalabraOri2().add(Frase2.charAt(g)); } this.M.getPalabraOri2().add(" "); } else if (R4 == false) { for (int y = 0; y < Fila4; y++) { this.M.getPalabraOri2().add(" "); this.labeles.elementAt(122 - y).setVisible(false); } R4 = true; } } for (int a = 0; a < this.M.getPalabraOri2().size(); a++) { this.labeles.elementAt(a).setText("_"); } for (int a = (this.M.getPalabraOri2().size()); a <= 122; a++) { this.labeles.elementAt(a).setVisible(false); } } public void PonerLetra(char L, String L2,char L3){ if(this.Nivel == 1){ this.PonerLetra(L, L2); }else{ this.PonerLetra2(L3, L2); } } public void PonerLetra(char L, String L2) { if (this.M.BuscarLetra(L)) { for (int a = 0; a < this.M.getPalabraOri().size(); a++) { for (int b = 0; b < this.M.getPosicion().size(); b++) { if ((a + 1) == this.M.getPosicion().elementAt(b)) { this.labeles.elementAt(a).setText(L2); } } } this.M.LimpiarPosicion(); if (this.M.Gano()) { this.VP.setMensaje("GANASTE", true, Color.GREEN); this.HabilitarTeclado(false); this.M.setAcierto(0); this.VP.HablitarRegistro(true); this.R.Parar(); } } else { this.ContarError(); if (this.M.SeguirJugando() == false) { this.HabilitarTeclado(false); this.VP.setMensaje("PERDISTE", true, Color.RED); this.M.setAcierto(0); this.VP.HablitarRegistro(false); this.R.Parar(); this.R.Reiniciar(this.VP.getReloj()); } } } public void PonerLetra2(char L, String L2) { if (this.M.BuscarLetra2(L)) { for (int a = 0; a < this.M.getPalabraOri2().size(); a++) { for (int b = 0; b < this.M.getPosicion().size(); b++) { if ((a + 1) == this.M.getPosicion().elementAt(b)) { this.labeles.elementAt(a).setText(L2); } } } this.M.LimpiarPosicion(); if (this.M.Gano2()) { this.VP.setMensaje("GANASTE", true, Color.GREEN); this.HabilitarTeclado(false); this.M.setAcierto(0); this.VP.HablitarRegistro(true); this.R.Parar(); } } else { this.ContarError(); if (this.M.SeguirJugando() == false) { this.HabilitarTeclado(false); this.VP.setMensaje("PERDISTE", true, Color.RED); this.M.setAcierto(0); this.VP.HablitarRegistro(false); this.R.Parar(); this.R.Reiniciar(this.VP.getReloj()); } } } public void LimpiarVacios(String L, String L2) { if (this.M.BuscarLetraV(L)) { for (int a = 0; a < this.M.getPalabraOri2().size(); a++) { for (int b = 0; b < this.M.getPosicion().size(); b++) { if ((a + 1) == this.M.getPosicion().elementAt(b)) { this.labeles.elementAt(a).setText(L2); } } } this.M.LimpiarPosicion(); if (this.M.Gano2()) { this.VP.setMensaje("GANASTE", true, Color.GREEN); this.HabilitarTeclado(false); this.M.setAcierto(0); this.VP.HablitarRegistro(true); this.R.Parar(); } } else { this.ContarError(); if (this.M.SeguirJugando() == false) { this.HabilitarTeclado(false); this.VP.setMensaje("PERDISTE", true, Color.RED); this.M.setAcierto(0); this.VP.HablitarRegistro(false); this.R.Parar(); this.R.Reiniciar(this.VP.getReloj()); } } } public void GuardarPuntaje() { if (!this.VP.getJNombre().getText().isEmpty()) { Jugador J = new Jugador(this.VP.getJNombre().getText(), this.Nivel, this.VP.getReloj().getText()); this.R.Reiniciar(this.VP.getReloj()); this.VP.HablitarRegistro(false); }else{ this.VP.MostrarMensaje(); } } public void HabilitarTeclado(boolean a) { this.VP.setjButton1(a); this.VP.setjButton2(a); this.VP.setjButton3(a); this.VP.setjButton4(a); this.VP.setjButton5(a); this.VP.setjButton6(a); this.VP.setjButton7(a); this.VP.setjButton8(a); this.VP.setjButton9(a); this.VP.setjButton10(a); this.VP.setjButton11(a); this.VP.setjButton12(a); this.VP.setjButton13(a); this.VP.setjButton14(a); this.VP.setjButton15(a); this.VP.setjButton16(a); this.VP.setjButton17(a); this.VP.setjButton18(a); this.VP.setjButton19(a); this.VP.setjButton20(a); this.VP.setjButton21(a); this.VP.setjButton22(a); this.VP.setjButton23(a); this.VP.setjButton24(a); this.VP.setjButton25(a); this.VP.setjButton26(a); this.VP.setjButton27(a); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Controlador; import Modelo.ModPartida; import Modelo.Record; import Modelo.Registrar; import Vista.VRecord; import Vista.VRegistrar; import Vista.VistaMenu; import Vista.VistaPart; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.SQLException; import bean.Music; import java.io.File; import javax.swing.WindowConstants; /** * * @author USUARIO */ public class ContMenu{ private VistaMenu V; public ContMenu(VistaMenu V) throws Exception { this.V = V; V.setVisible(true); } public void ActivarCampos(){ V.setNivel(true); V.setIniP(true); } public void Salir(){ System.exit(0); } public void ComenzarPartida() throws SQLException, Exception{ ModPartida M = new ModPartida(); VistaPart VP = new VistaPart(); ContPartida C = new ContPartida(VP,M,this.V.getNivel().getSelectedIndex()); VP.setControlador(C); } public void RegistrarFrase(){ Registrar F = new Registrar(); VRegistrar VR = new VRegistrar(); ContRegistrar CR = new ContRegistrar(F,VR); VR.setControlador(CR); } public void MostrarRecords() throws SQLException { VRecord VRd = new VRecord(); Record MRd = new Record(); ContRecord CRd = new ContRecord(MRd,VRd); VRd.setVisible(true); VRd.setControlador(CRd); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Controlador; import Modelo.Record; import Vista.VRecord; import java.sql.SQLException; /** * * @author USUARIO */ public class ContRecord { private Record R; private VRecord VR; ContRecord(Record MRd, VRecord VRd) throws SQLException { this.R = MRd; this.VR = VRd; } public void MostrarRecord() throws SQLException{ this.R.MostrarRecordN1(); for(int a = 0; a < 5; a++){ this.VR.getNivel1().setValueAt(this.R.getNombre().elementAt(a), a, 0); this.VR.getNivel1().setValueAt(this.R.getTiempo().elementAt(a), a, 1); } this.R.MostrarRecordN2(); for(int a = 0; a < 5; a++){ this.VR.getNivel2().setValueAt(this.R.getNombre().elementAt(a), a, 0); this.VR.getNivel2().setValueAt(this.R.getTiempo().elementAt(a), a, 1); } this.R.MostrarRecordN3(); for(int a = 0; a < 5; a++){ this.VR.getNivel3().setValueAt(this.R.getNombre().elementAt(a), a, 0); this.VR.getNivel3().setValueAt(this.R.getTiempo().elementAt(a), a, 1); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Controlador; import Modelo.Registrar; import Modelo.RegistrarDAO; import Vista.VRegistrar; import javax.swing.JOptionPane; /** * * @author Robert Alvarado */ public class ContRegistrar { private Registrar F; private VRegistrar VR; private int Numero_Palabras; ContRegistrar(Registrar F, VRegistrar VR) { this.F = F; this.VR = VR; this.VR.setVisible(true); } public void Contar(String F){ this.Numero_Palabras = this.F.Contar(F); if(this.Numero_Palabras == 1){ RegistrarDAO RD = new RegistrarDAO("Palabra_1",this.VR.getFrase().getText()); JOptionPane.showMessageDialog(null, "Palabra registrada Exitosamente"); this.VR.getFrase().setText(""); }else if(this.Numero_Palabras >= 2 && this.Numero_Palabras <= 5){ RegistrarDAO RD = new RegistrarDAO("Palabra_2",this.VR.getFrase().getText()); JOptionPane.showMessageDialog(null, "Frase registrada Exitosamente"); this.VR.getFrase().setText(""); }else if(this.Numero_Palabras >= 6 && this.Numero_Palabras <= 10){ RegistrarDAO RD = new RegistrarDAO("Palabra_3",this.VR.getFrase().getText()); JOptionPane.showMessageDialog(null, "Frase registrada Exitosamente"); this.VR.getFrase().setText(""); }else{ JOptionPane.showMessageDialog(null, "Frase muy grande, no debe exceder de 10 palabras"); this.VR.getFrase().setText(""); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * El juego se ha realizado en netbeans 7.0.1 Alvarado Robert C.I. 18.052.474 Mendez Maryelis C.I. 19.887.067 Pernalete Alfa C.I. 19.164.564 Rivero Mayilde C.I. 18.430.469 */ package pkg4.pkg1.primer.proyecto; import Controlador.ContMenu; import Vista.VistaMenu; /** * * @author USUARIO */ public class PrimerProyecto { /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { // TODO code application logic here VistaMenu V = new VistaMenu(); ContMenu C = new ContMenu(V); V.setControlador(C); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * VistaMenu.java * * Created on 18-oct-2011, 19:50:35 */ package Vista; import Controlador.ContMenu; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JTextField; /** * * @author USUARIO */ public class VistaMenu extends javax.swing.JFrame { private ContMenu C; /** Creates new form VistaMenu */ public VistaMenu() { initComponents(); this.Nivel.setSelectedIndex(0); Pixelado.setIcon(new ImageIcon(getClass().getClassLoader().getResource("Imagenes/ahorcado1.JPG"))); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel3 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); Pixelado = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); Iniciar = new javax.swing.JButton(); Registrar = new javax.swing.JButton(); Records = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); Nivel = new javax.swing.JComboBox(); IniP = new javax.swing.JButton(); Salir = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(204, 204, 204)); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); setForeground(new java.awt.Color(255, 255, 255)); jPanel3.setBackground(new java.awt.Color(204, 255, 204)); jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder(java.awt.Color.lightGray, java.awt.Color.lightGray)); jLabel3.setFont(new java.awt.Font("Gill Sans Ultra Bold", 1, 45)); jLabel3.setForeground(new java.awt.Color(51, 102, 255)); jLabel3.setText("¿..AHORCADO..?"); Pixelado.setIcon(new javax.swing.ImageIcon("C:\\Documents and Settings\\Robert Alvarado\\Escritorio\\FINAL_COLOR\\1-1-primer-proyecto\\src\\Imagenes\\ahorcado1.JPG")); // NOI18N javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 482, Short.MAX_VALUE) .addContainerGap()) .addComponent(Pixelado, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 460, javax.swing.GroupLayout.PREFERRED_SIZE))) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(Pixelado, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 277, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2.setBackground(new java.awt.Color(255, 255, 153)); Iniciar.setFont(new java.awt.Font("Agency FB", 1, 14)); Iniciar.setText("Jugar"); Iniciar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { IniciarActionPerformed(evt); } }); Registrar.setFont(new java.awt.Font("Agency FB", 1, 14)); Registrar.setText("Registrar Palabra"); Registrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RegistrarActionPerformed(evt); } }); Records.setFont(new java.awt.Font("Agency FB", 1, 14)); Records.setText("Records"); Records.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RecordsActionPerformed(evt); } }); jPanel1.setBackground(new java.awt.Color(235, 242, 249)); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "<<Datos del Juego>>", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Agency FB", 1, 18), new java.awt.Color(0, 0, 0))); // NOI18N jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel2.setFont(new java.awt.Font("Tw Cen MT", 0, 14)); jLabel2.setText("Nivel del Juego:"); jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 30, 100, -1)); Nivel.setFont(new java.awt.Font("Tw Cen MT", 0, 12)); Nivel.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Nivel Basico", "Nivel Intermedio", "Nivel Avanzado" })); Nivel.setEnabled(false); Nivel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NivelActionPerformed(evt); } }); jPanel1.add(Nivel, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 30, 130, 20)); IniP.setFont(new java.awt.Font("Agency FB", 1, 14)); IniP.setText("Iniciar Partida"); IniP.setEnabled(false); IniP.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { IniPActionPerformed(evt); } }); jPanel1.add(IniP, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 60, 130, 20)); Salir.setFont(new java.awt.Font("Agency FB", 1, 14)); Salir.setText("Salir"); Salir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SalirActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Iniciar, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Registrar, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE) .addComponent(Records, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(Salir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 312, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(30, 30, 30)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(25, 25, 25) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(7, 7, 7) .addComponent(Iniciar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Registrar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Records)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(13, 13, 13) .addComponent(Salir))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 454, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void IniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_IniciarActionPerformed // TODO add your handling code here: C.ActivarCampos(); }//GEN-LAST:event_IniciarActionPerformed private void SalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SalirActionPerformed // TODO add your handling code here: C.Salir(); }//GEN-LAST:event_SalirActionPerformed private void IniPActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_IniPActionPerformed try { C.ComenzarPartida(); } catch (Exception ex) { Logger.getLogger(VistaMenu.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_IniPActionPerformed private void NivelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NivelActionPerformed // TODO add your handling code here: }//GEN-LAST:event_NivelActionPerformed private void RegistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RegistrarActionPerformed // TODO add your handling code here: this.C.RegistrarFrase(); }//GEN-LAST:event_RegistrarActionPerformed private void RecordsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RecordsActionPerformed try { this.C.MostrarRecords(); } catch (SQLException ex) { Logger.getLogger(VistaMenu.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_RecordsActionPerformed public void setControlador(ContMenu C){ this.C = C; } public void setIniP(boolean a) { this.IniP = IniP; this.IniP.setEnabled(a); } public void setNivel(boolean a) { this.Nivel = Nivel; this.Nivel.setEnabled(a); } public JButton getSalir() { return Salir; } public JComboBox getNivel() { return Nivel; } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(VistaMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VistaMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VistaMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VistaMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new VistaMenu().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton IniP; private javax.swing.JButton Iniciar; private javax.swing.JComboBox Nivel; private javax.swing.JLabel Pixelado; private javax.swing.JButton Records; private javax.swing.JButton Registrar; private javax.swing.JButton Salir; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * VRegistrar.java * * Created on 23/10/2011, 12:05:48 AM */ package Vista; import Controlador.ContRegistrar; import javax.swing.JTextField; /** * * @author Robert Alvarado */ public class VRegistrar extends javax.swing.JFrame { private ContRegistrar R; /** Creates new form VRegistrar */ public VRegistrar() { initComponents(); } public void setControlador(ContRegistrar R){ this.R = R; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { Frase = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); Frase.setFont(new java.awt.Font("Tw Cen MT", 0, 14)); // NOI18N getContentPane().add(Frase, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, 591, 20)); jButton1.setFont(new java.awt.Font("Agency FB", 1, 14)); // NOI18N jButton1.setText("Aceptar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 70, -1, -1)); jButton2.setFont(new java.awt.Font("Agency FB", 1, 14)); // NOI18N jButton2.setText("Salir"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 70, 68, -1)); jLabel1.setFont(new java.awt.Font("Tw Cen MT", 1, 14)); // NOI18N jLabel1.setText("Por favor Introduzca La(s) Palabra(s) que desea Registrar:"); getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 20, 350, -1)); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: this.R.Contar(this.Frase.getText()); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: dispose(); }//GEN-LAST:event_jButton2ActionPerformed public JTextField getFrase() { return Frase; } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(VRegistrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VRegistrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VRegistrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VRegistrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new VRegistrar().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField Frase; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * VRecord.java * * Created on 23-oct-2011, 19:45:45 */ package Vista; import Controlador.ContRecord; import java.sql.SQLException; import javax.swing.JTable; /** * * @author USUARIO */ public class VRecord extends javax.swing.JFrame { private ContRecord C; /** Creates new form VRecord */ public VRecord() { initComponents(); } public void setControlador(ContRecord C) throws SQLException{ this.C = C; this.C.MostrarRecord(); } public JTable getNivel1() { return Nivel1; } public JTable getNivel2() { return Nivel2; } public JTable getNivel3() { return Nivel3; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jButton1 = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jScrollPane4 = new javax.swing.JScrollPane(); Nivel1 = new javax.swing.JTable(); jPanel3 = new javax.swing.JPanel(); jScrollPane5 = new javax.swing.JScrollPane(); Nivel2 = new javax.swing.JTable(); jPanel1 = new javax.swing.JPanel(); jScrollPane3 = new javax.swing.JScrollPane(); Nivel3 = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jButton1.setFont(new java.awt.Font("Agency FB", 1, 14)); jButton1.setText("SALIR"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 590, 150, -1)); jPanel2.setBackground(new java.awt.Color(255, 255, 153)); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "<<Nivel Basico>>", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Agency FB", 1, 24), new java.awt.Color(0, 0, 0))); // NOI18N Nivel1.setFont(new java.awt.Font("Tw Cen MT", 0, 14)); Nivel1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null}, {null, null}, {null, null}, {null, null}, {null, null} }, new String [] { "Nombre", "Tiempo" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jScrollPane4.setViewportView(Nivel1); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 414, Short.MAX_VALUE) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 450, 190)); jPanel3.setBackground(new java.awt.Color(204, 255, 204)); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "<<Nivel Intermedio>>", javax.swing.border.TitledBorder.RIGHT, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Agency FB", 1, 24), new java.awt.Color(0, 0, 0))); // NOI18N Nivel2.setFont(new java.awt.Font("Tw Cen MT", 0, 14)); Nivel2.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null}, {null, null}, {null, null}, {null, null}, {null, null} }, new String [] { "Nombre", "Tiempo" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jScrollPane5.setViewportView(Nivel2); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 414, Short.MAX_VALUE) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE) .addContainerGap()) ); getContentPane().add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 190, 450, -1)); jPanel1.setBackground(new java.awt.Color(255, 255, 153)); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "<<Nivel Avanzado>>", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Agency FB", 1, 24), new java.awt.Color(0, 0, 0))); // NOI18N Nivel3.setFont(new java.awt.Font("Tw Cen MT", 0, 14)); Nivel3.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null}, {null, null}, {null, null}, {null, null}, {null, null} }, new String [] { "Nombre", "Tiempo" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jScrollPane3.setViewportView(Nivel3); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 414, Short.MAX_VALUE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE) .addContainerGap()) ); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 380, 450, -1)); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: dispose(); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(VRecord.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VRecord.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VRecord.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VRecord.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new VRecord().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTable Nivel1; private javax.swing.JTable Nivel2; private javax.swing.JTable Nivel3; private javax.swing.JButton jButton1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JScrollPane jScrollPane5; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * VistaPart.java * * Created on 18-oct-2011, 20:48:54 */ package Vista; import Controlador.ContPartida; import bean.Music; import java.awt.Color; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; /** * * @author USUARIO */ public class VistaPart extends javax.swing.JFrame { private ContPartida C; /** Creates new form VistaPart */ public VistaPart() { initComponents(); } public void setControlador(ContPartida C){ this.C = C; } public void setAhorcado(String Ruta) { ImagenLabel.setIcon(new ImageIcon(getClass().getClassLoader().getResource(Ruta))); } public void setjLabel1(boolean a) { this.jLabel1.setEnabled(a); } public void setjLabel10(boolean a) { this.jLabel10.setEnabled(a); } public void setjLabel11(boolean a) { this.jLabel11.setEnabled(a); } public void setjLabel12(boolean a) { this.jLabel12.setEnabled(a); } public void setjLabel13(boolean a) { this.jLabel13.setEnabled(a); } public void setjLabel14(boolean a) { this.jLabel14.setEnabled(a); } public void setjLabel15(boolean a) { this.jLabel15.setEnabled(a); } public void setjLabel16(boolean a) { this.jLabel16.setEnabled(a); } public void setjLabel17(boolean a) { this.jLabel17.setEnabled(a); } public void setjLabel18(boolean a) { this.jLabel18.setEnabled(a); } public void setjLabel2(boolean a) { this.jLabel2.setEnabled(a); } public void setjLabel3(boolean a) { this.jLabel3.setEnabled(a); } public void setjLabel4(boolean a) { this.jLabel4.setEnabled(a); } public void setjLabel5(boolean a) { this.jLabel5.setEnabled(a); } public void setjLabel6(boolean a) { this.jLabel6.setEnabled(a); } public void setjLabel7(boolean a) { this.jLabel7.setEnabled(a); } public void setjLabel8(boolean a) { this.jLabel8.setEnabled(a); } public void setjLabel9(boolean a) { this.jLabel9.setEnabled(a); } public JLabel getjLabel1() { return jLabel1; } public JLabel getjLabel10() { return jLabel10; } public JLabel getjLabel11() { return jLabel11; } public JLabel getjLabel12() { return jLabel12; } public JLabel getjLabel13() { return jLabel13; } public JLabel getjLabel14() { return jLabel14; } public JLabel getjLabel15() { return jLabel15; } public JLabel getjLabel16() { return jLabel16; } public JLabel getjLabel17() { return jLabel17; } public JLabel getjLabel18() { return jLabel18; } public JLabel getjLabel2() { return jLabel2; } public JLabel getjLabel3() { return jLabel3; } public JLabel getjLabel4() { return jLabel4; } public JLabel getjLabel5() { return jLabel5; } public JLabel getjLabel6() { return jLabel6; } public JLabel getjLabel7() { return jLabel7; } public JLabel getjLabel8() { return jLabel8; } public JLabel getjLabel9() { return jLabel9; } public JLabel getjLabel100() { return jLabel100; } public JLabel getjLabel101() { return jLabel101; } public JLabel getjLabel102() { return jLabel102; } public JLabel getjLabel103() { return jLabel103; } public JLabel getjLabel104() { return jLabel104; } public JLabel getjLabel105() { return jLabel105; } public JLabel getjLabel106() { return jLabel106; } public JLabel getjLabel107() { return jLabel107; } public JLabel getjLabel108() { return jLabel108; } public JLabel getjLabel109() { return jLabel109; } public JLabel getjLabel110() { return jLabel110; } public JLabel getjLabel111() { return jLabel111; } public JLabel getjLabel112() { return jLabel112; } public JLabel getjLabel113() { return jLabel113; } public JLabel getjLabel114() { return jLabel114; } public JLabel getjLabel115() { return jLabel115; } public JLabel getjLabel116() { return jLabel116; } public JLabel getjLabel117() { return jLabel117; } public JLabel getjLabel118() { return jLabel118; } public JLabel getjLabel119() { return jLabel119; } public JLabel getjLabel120() { return jLabel120; } public JLabel getjLabel121() { return jLabel121; } public JLabel getjLabel122() { return jLabel122; } public JLabel getjLabel123() { return jLabel123; } public JLabel getjLabel19() { return jLabel19; } public JLabel getjLabel20() { return jLabel20; } public JLabel getjLabel21() { return jLabel21; } public JLabel getjLabel22() { return jLabel22; } public JLabel getjLabel23() { return jLabel23; } public JLabel getjLabel24() { return jLabel24; } public JLabel getjLabel25() { return jLabel25; } public JLabel getjLabel26() { return jLabel26; } public JLabel getjLabel27() { return jLabel27; } public JLabel getjLabel28() { return jLabel28; } public JLabel getjLabel29() { return jLabel29; } public JLabel getjLabel30() { return jLabel30; } public JLabel getjLabel31() { return jLabel31; } public JLabel getjLabel32() { return jLabel32; } public JLabel getjLabel33() { return jLabel33; } public JLabel getjLabel34() { return jLabel34; } public JLabel getjLabel35() { return jLabel35; } public JLabel getjLabel36() { return jLabel36; } public JLabel getjLabel37() { return jLabel37; } public JLabel getjLabel38() { return jLabel38; } public JLabel getjLabel39() { return jLabel39; } public JLabel getjLabel40() { return jLabel40; } public JLabel getjLabel41() { return jLabel41; } public JLabel getjLabel42() { return jLabel42; } public JLabel getjLabel43() { return jLabel43; } public JLabel getjLabel44() { return jLabel44; } public JLabel getjLabel45() { return jLabel45; } public JLabel getjLabel46() { return jLabel46; } public JLabel getjLabel47() { return jLabel47; } public JLabel getjLabel48() { return jLabel48; } public JLabel getjLabel49() { return jLabel49; } public JLabel getjLabel50() { return jLabel50; } public JLabel getjLabel51() { return jLabel51; } public JLabel getjLabel52() { return jLabel52; } public JLabel getjLabel53() { return jLabel53; } public JLabel getjLabel54() { return jLabel54; } public JLabel getjLabel55() { return jLabel55; } public JLabel getjLabel56() { return jLabel56; } public JLabel getjLabel57() { return jLabel57; } public JLabel getjLabel58() { return jLabel58; } public JLabel getjLabel59() { return jLabel59; } public JLabel getjLabel60() { return jLabel60; } public JLabel getjLabel61() { return jLabel61; } public JLabel getjLabel62() { return jLabel62; } public JLabel getjLabel63() { return jLabel63; } public JLabel getjLabel64() { return jLabel64; } public JLabel getjLabel65() { return jLabel65; } public JLabel getjLabel66() { return jLabel66; } public JLabel getjLabel67() { return jLabel67; } public JLabel getjLabel68() { return jLabel68; } public JLabel getjLabel69() { return jLabel69; } public JLabel getjLabel70() { return jLabel70; } public JLabel getjLabel71() { return jLabel71; } public JLabel getjLabel72() { return jLabel72; } public JLabel getjLabel73() { return jLabel73; } public JLabel getjLabel74() { return jLabel74; } public JLabel getjLabel75() { return jLabel75; } public JLabel getjLabel76() { return jLabel76; } public JLabel getjLabel77() { return jLabel77; } public JLabel getjLabel78() { return jLabel78; } public JLabel getjLabel79() { return jLabel79; } public JLabel getjLabel80() { return jLabel80; } public JLabel getjLabel81() { return jLabel81; } public JLabel getjLabel82() { return jLabel82; } public JLabel getjLabel83() { return jLabel83; } public JLabel getjLabel84() { return jLabel84; } public JLabel getjLabel85() { return jLabel85; } public JLabel getjLabel86() { return jLabel86; } public JLabel getjLabel87() { return jLabel87; } public JLabel getjLabel88() { return jLabel88; } public JLabel getjLabel89() { return jLabel89; } public JLabel getjLabel90() { return jLabel90; } public JLabel getjLabel91() { return jLabel91; } public JLabel getjLabel92() { return jLabel92; } public JLabel getjLabel93() { return jLabel93; } public JLabel getjLabel94() { return jLabel94; } public JLabel getjLabel95() { return jLabel95; } public JLabel getjLabel96() { return jLabel96; } public JLabel getjLabel97() { return jLabel97; } public JLabel getjLabel98() { return jLabel98; } public JLabel getjLabel99() { return jLabel99; } public void setjButton1(boolean a) { this.jButton1.setEnabled(a); } public void setjButton10(boolean a) { this.jButton10.setEnabled(a); } public void setjButton11(boolean a) { this.jButton11.setEnabled(a); } public void setjButton12(boolean a) { this.jButton12.setEnabled(a); } public void setjButton13(boolean a) { this.jButton13.setEnabled(a); } public void setjButton14(boolean a) { this.jButton14.setEnabled(a); } public void setjButton15(boolean a) { this.jButton15.setEnabled(a); } public void setjButton16(boolean a) { this.jButton16.setEnabled(a); } public void setjButton17(boolean a) { this.jButton17.setEnabled(a); } public void setjButton18(boolean a) { this.jButton18.setEnabled(a); } public void setjButton19(boolean a) { this.jButton19.setEnabled(a); } public void setjButton2(boolean a) { this.jButton2.setEnabled(a); } public void setjButton20(boolean a) { this.jButton20.setEnabled(a); } public void setjButton21(boolean a) { this.jButton21.setEnabled(a); } public void setjButton22(boolean a) { this.jButton22.setEnabled(a); } public void setjButton23(boolean a) { this.jButton23.setEnabled(a); } public void setjButton24(boolean a) { this.jButton24.setEnabled(a); } public void setjButton25(boolean a) { this.jButton25.setEnabled(a); } public void setjButton26(boolean a) { this.jButton26.setEnabled(a); } public void setjButton27(boolean a) { this.jButton27.setEnabled(a); } public void setjButton3(boolean a) { this.jButton3.setEnabled(a); } public void setjButton4(boolean a) { this.jButton4.setEnabled(a); } public void setjButton5(boolean a) { this.jButton5.setEnabled(a); } public void setjButton6(boolean a) { this.jButton6.setEnabled(a); } public void setjButton7(boolean a) { this.jButton7.setEnabled(a); } public void setjButton8(boolean a) { this.jButton8.setEnabled(a); } public void setjButton9(boolean a) { this.jButton9.setEnabled(a); } public void setMensaje(String Men, boolean a, Color b) { this.Mensaje.setText(Men); this.Mensaje.setVisible(a); this.Mensaje.setForeground(b); } public void HablitarRegistro(boolean a){ this.Aceptar.setVisible(a); this.Nombre.setVisible(a); this.JNombre.setVisible(a); } public JLabel getReloj() { return Reloj; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel2 = new javax.swing.JPanel(); Reiniciar = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); jButton7 = new javax.swing.JButton(); jButton8 = new javax.swing.JButton(); jButton9 = new javax.swing.JButton(); jButton10 = new javax.swing.JButton(); jButton11 = new javax.swing.JButton(); jButton12 = new javax.swing.JButton(); jButton13 = new javax.swing.JButton(); jButton14 = new javax.swing.JButton(); jButton15 = new javax.swing.JButton(); jButton16 = new javax.swing.JButton(); jButton17 = new javax.swing.JButton(); jButton18 = new javax.swing.JButton(); jButton19 = new javax.swing.JButton(); jButton20 = new javax.swing.JButton(); jButton21 = new javax.swing.JButton(); jButton22 = new javax.swing.JButton(); jButton23 = new javax.swing.JButton(); jButton24 = new javax.swing.JButton(); jButton25 = new javax.swing.JButton(); jButton26 = new javax.swing.JButton(); jButton27 = new javax.swing.JButton(); jButton28 = new javax.swing.JButton(); Ahorcado = new javax.swing.JPanel(); ImagenLabel = new javax.swing.JLabel(); Mensaje = new javax.swing.JLabel(); Nombre = new javax.swing.JLabel(); JNombre = new javax.swing.JTextField(); Aceptar = new javax.swing.JButton(); Reloj = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); jLabel18 = new javax.swing.JLabel(); jLabel19 = new javax.swing.JLabel(); jLabel20 = new javax.swing.JLabel(); jLabel21 = new javax.swing.JLabel(); jLabel22 = new javax.swing.JLabel(); jLabel23 = new javax.swing.JLabel(); jLabel24 = new javax.swing.JLabel(); jLabel25 = new javax.swing.JLabel(); jLabel26 = new javax.swing.JLabel(); jLabel27 = new javax.swing.JLabel(); jLabel28 = new javax.swing.JLabel(); jLabel29 = new javax.swing.JLabel(); jLabel30 = new javax.swing.JLabel(); jLabel31 = new javax.swing.JLabel(); jLabel32 = new javax.swing.JLabel(); jLabel33 = new javax.swing.JLabel(); jLabel34 = new javax.swing.JLabel(); jLabel35 = new javax.swing.JLabel(); jLabel36 = new javax.swing.JLabel(); jLabel37 = new javax.swing.JLabel(); jLabel38 = new javax.swing.JLabel(); jLabel39 = new javax.swing.JLabel(); jLabel40 = new javax.swing.JLabel(); jLabel41 = new javax.swing.JLabel(); jLabel42 = new javax.swing.JLabel(); jLabel43 = new javax.swing.JLabel(); jLabel44 = new javax.swing.JLabel(); jLabel45 = new javax.swing.JLabel(); jLabel46 = new javax.swing.JLabel(); jLabel47 = new javax.swing.JLabel(); jLabel48 = new javax.swing.JLabel(); jLabel49 = new javax.swing.JLabel(); jLabel50 = new javax.swing.JLabel(); jLabel51 = new javax.swing.JLabel(); jLabel52 = new javax.swing.JLabel(); jLabel53 = new javax.swing.JLabel(); jLabel54 = new javax.swing.JLabel(); jLabel55 = new javax.swing.JLabel(); jLabel56 = new javax.swing.JLabel(); jLabel57 = new javax.swing.JLabel(); jLabel58 = new javax.swing.JLabel(); jLabel59 = new javax.swing.JLabel(); jLabel60 = new javax.swing.JLabel(); jLabel61 = new javax.swing.JLabel(); jLabel62 = new javax.swing.JLabel(); jLabel63 = new javax.swing.JLabel(); jLabel64 = new javax.swing.JLabel(); jLabel65 = new javax.swing.JLabel(); jLabel66 = new javax.swing.JLabel(); jLabel67 = new javax.swing.JLabel(); jLabel68 = new javax.swing.JLabel(); jLabel69 = new javax.swing.JLabel(); jLabel70 = new javax.swing.JLabel(); jLabel71 = new javax.swing.JLabel(); jLabel72 = new javax.swing.JLabel(); jLabel73 = new javax.swing.JLabel(); jLabel74 = new javax.swing.JLabel(); jLabel75 = new javax.swing.JLabel(); jLabel76 = new javax.swing.JLabel(); jLabel77 = new javax.swing.JLabel(); jLabel78 = new javax.swing.JLabel(); jLabel79 = new javax.swing.JLabel(); jLabel80 = new javax.swing.JLabel(); jLabel81 = new javax.swing.JLabel(); jLabel82 = new javax.swing.JLabel(); jLabel83 = new javax.swing.JLabel(); jLabel84 = new javax.swing.JLabel(); jLabel85 = new javax.swing.JLabel(); jLabel86 = new javax.swing.JLabel(); jLabel87 = new javax.swing.JLabel(); jLabel88 = new javax.swing.JLabel(); jLabel89 = new javax.swing.JLabel(); jLabel90 = new javax.swing.JLabel(); jLabel91 = new javax.swing.JLabel(); jLabel92 = new javax.swing.JLabel(); jLabel93 = new javax.swing.JLabel(); jLabel94 = new javax.swing.JLabel(); jLabel95 = new javax.swing.JLabel(); jLabel96 = new javax.swing.JLabel(); jLabel97 = new javax.swing.JLabel(); jLabel98 = new javax.swing.JLabel(); jLabel99 = new javax.swing.JLabel(); jLabel100 = new javax.swing.JLabel(); jLabel101 = new javax.swing.JLabel(); jLabel102 = new javax.swing.JLabel(); jLabel103 = new javax.swing.JLabel(); jLabel104 = new javax.swing.JLabel(); jLabel105 = new javax.swing.JLabel(); jLabel106 = new javax.swing.JLabel(); jLabel107 = new javax.swing.JLabel(); jLabel108 = new javax.swing.JLabel(); jLabel109 = new javax.swing.JLabel(); jLabel110 = new javax.swing.JLabel(); jLabel111 = new javax.swing.JLabel(); jLabel112 = new javax.swing.JLabel(); jLabel113 = new javax.swing.JLabel(); jLabel114 = new javax.swing.JLabel(); jLabel115 = new javax.swing.JLabel(); jLabel116 = new javax.swing.JLabel(); jLabel117 = new javax.swing.JLabel(); jLabel118 = new javax.swing.JLabel(); jLabel119 = new javax.swing.JLabel(); jLabel120 = new javax.swing.JLabel(); jLabel121 = new javax.swing.JLabel(); jLabel122 = new javax.swing.JLabel(); jLabel123 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(255, 255, 255)); jPanel2.setBackground(new java.awt.Color(204, 255, 51)); jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder(java.awt.Color.lightGray, java.awt.Color.lightGray)); jPanel2.setForeground(new java.awt.Color(255, 255, 255)); Reiniciar.setFont(new java.awt.Font("Agency FB", 1, 13)); Reiniciar.setText("Reiniciar"); Reiniciar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ReiniciarActionPerformed(evt); } }); jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204), 2)); jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jButton1.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton1.setForeground(new java.awt.Color(1, 1, 1)); jButton1.setText("A"); jButton1.setMaximumSize(new java.awt.Dimension(43, 23)); jButton1.setMinimumSize(new java.awt.Dimension(43, 23)); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel3.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 50, 50, 40)); jButton2.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton2.setText("B"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jPanel3.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 90, 50, 40)); jButton3.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton3.setText("K"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jPanel3.add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 50, 50, 40)); jButton4.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton4.setText("C"); jButton4.setMaximumSize(new java.awt.Dimension(43, 23)); jButton4.setMinimumSize(new java.awt.Dimension(43, 23)); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jPanel3.add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 90, 50, 40)); jButton5.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton5.setText("L"); jButton5.setMaximumSize(new java.awt.Dimension(43, 23)); jButton5.setMinimumSize(new java.awt.Dimension(43, 23)); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); jPanel3.add(jButton5, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 50, 50, 40)); jButton6.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton6.setText("J"); jButton6.setMaximumSize(new java.awt.Dimension(43, 23)); jButton6.setMinimumSize(new java.awt.Dimension(43, 23)); jButton6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton6ActionPerformed(evt); } }); jPanel3.add(jButton6, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 50, 50, 40)); jButton7.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton7.setText("D"); jButton7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton7ActionPerformed(evt); } }); jPanel3.add(jButton7, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 50, 50, 40)); jButton8.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton8.setText("E"); jButton8.setMaximumSize(new java.awt.Dimension(43, 23)); jButton8.setMinimumSize(new java.awt.Dimension(43, 23)); jButton8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton8ActionPerformed(evt); } }); jPanel3.add(jButton8, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 10, 50, 40)); jButton9.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton9.setText("F"); jButton9.setMaximumSize(new java.awt.Dimension(43, 23)); jButton9.setMinimumSize(new java.awt.Dimension(43, 23)); jButton9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton9ActionPerformed(evt); } }); jPanel3.add(jButton9, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 50, 50, 40)); jButton10.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton10.setText("G"); jButton10.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton10ActionPerformed(evt); } }); jPanel3.add(jButton10, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 50, 50, 40)); jButton11.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton11.setText("M"); jButton11.setMaximumSize(new java.awt.Dimension(43, 23)); jButton11.setMinimumSize(new java.awt.Dimension(43, 23)); jButton11.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton11ActionPerformed(evt); } }); jPanel3.add(jButton11, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 90, 50, 40)); jButton12.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton12.setText("H"); jButton12.setMaximumSize(new java.awt.Dimension(43, 23)); jButton12.setMinimumSize(new java.awt.Dimension(43, 23)); jButton12.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton12ActionPerformed(evt); } }); jPanel3.add(jButton12, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 50, 50, 40)); jButton13.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton13.setText("N"); jButton13.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton13ActionPerformed(evt); } }); jPanel3.add(jButton13, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 90, 50, 40)); jButton14.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton14.setText("Ñ"); jButton14.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton14ActionPerformed(evt); } }); jPanel3.add(jButton14, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 90, 50, 40)); jButton15.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton15.setText("O"); jButton15.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton15ActionPerformed(evt); } }); jPanel3.add(jButton15, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 10, 50, 40)); jButton16.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton16.setText("P"); jButton16.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton16ActionPerformed(evt); } }); jPanel3.add(jButton16, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 10, 50, 40)); jButton17.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton17.setText("R"); jButton17.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton17ActionPerformed(evt); } }); jPanel3.add(jButton17, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 10, 50, 40)); jButton18.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton18.setText("S"); jButton18.setMaximumSize(new java.awt.Dimension(43, 23)); jButton18.setMinimumSize(new java.awt.Dimension(43, 23)); jButton18.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton18ActionPerformed(evt); } }); jPanel3.add(jButton18, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 50, 50, 40)); jButton19.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton19.setText("T"); jButton19.setMaximumSize(new java.awt.Dimension(43, 23)); jButton19.setMinimumSize(new java.awt.Dimension(43, 23)); jButton19.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton19ActionPerformed(evt); } }); jPanel3.add(jButton19, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 10, 50, 40)); jButton20.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton20.setText("U"); jButton20.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton20ActionPerformed(evt); } }); jPanel3.add(jButton20, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 10, 50, 40)); jButton21.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton21.setText("V"); jButton21.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton21ActionPerformed(evt); } }); jPanel3.add(jButton21, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 90, 50, 40)); jButton22.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton22.setText("W"); jButton22.setPreferredSize(new java.awt.Dimension(43, 43)); jButton22.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton22ActionPerformed(evt); } }); jPanel3.add(jButton22, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 10, 50, 40)); jButton23.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton23.setText("X"); jButton23.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton23ActionPerformed(evt); } }); jPanel3.add(jButton23, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 90, 50, 40)); jButton24.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton24.setText("Y"); jButton24.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton24ActionPerformed(evt); } }); jPanel3.add(jButton24, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 10, 50, 40)); jButton25.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton25.setText("Z"); jButton25.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton25ActionPerformed(evt); } }); jPanel3.add(jButton25, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 90, 50, 40)); jButton26.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton26.setText("Q"); jButton26.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton26ActionPerformed(evt); } }); jPanel3.add(jButton26, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 50, 40)); jButton27.setFont(new java.awt.Font("Gill Sans Ultra Bold", 0, 12)); jButton27.setText("I"); jButton27.setMaximumSize(new java.awt.Dimension(43, 23)); jButton27.setMinimumSize(new java.awt.Dimension(43, 23)); jButton27.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton27ActionPerformed(evt); } }); jPanel3.add(jButton27, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 10, 50, 40)); jButton28.setFont(new java.awt.Font("Agency FB", 1, 13)); jButton28.setText("Salir"); jButton28.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton28ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(Reiniciar, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 519, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton28, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(22, 22, 22) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton28, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Reiniciar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(27, Short.MAX_VALUE)) ); Ahorcado.setBackground(new java.awt.Color(255, 255, 255)); Ahorcado.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204))); ImagenLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Aho0.gif"))); // NOI18N ImagenLabel.setMaximumSize(new java.awt.Dimension(100, 100)); ImagenLabel.setMinimumSize(new java.awt.Dimension(100, 100)); Mensaje.setFont(new java.awt.Font("Agency FB", 1, 70)); Nombre.setFont(new java.awt.Font("Tw Cen MT", 0, 14)); Nombre.setText("Ingrese su Nombre:"); JNombre.setFont(new java.awt.Font("Tw Cen MT", 0, 14)); Aceptar.setFont(new java.awt.Font("Agency FB", 1, 14)); Aceptar.setText("Aceptar"); Aceptar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AceptarActionPerformed(evt); } }); Reloj.setFont(new java.awt.Font("Gill Sans Ultra Bold", 1, 28)); Reloj.setText("00:00:00"); javax.swing.GroupLayout AhorcadoLayout = new javax.swing.GroupLayout(Ahorcado); Ahorcado.setLayout(AhorcadoLayout); AhorcadoLayout.setHorizontalGroup( AhorcadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(AhorcadoLayout.createSequentialGroup() .addGap(23, 23, 23) .addComponent(ImagenLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(AhorcadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(AhorcadoLayout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Reloj, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(AhorcadoLayout.createSequentialGroup() .addGap(41, 41, 41) .addComponent(Mensaje, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 60, Short.MAX_VALUE) .addGroup(AhorcadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(AhorcadoLayout.createSequentialGroup() .addGap(23, 23, 23) .addComponent(Nombre, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(JNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, AhorcadoLayout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Aceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(27, 27, 27))))) .addContainerGap()) ); AhorcadoLayout.setVerticalGroup( AhorcadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(AhorcadoLayout.createSequentialGroup() .addContainerGap() .addGroup(AhorcadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ImagenLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 197, Short.MAX_VALUE) .addGroup(AhorcadoLayout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(Reloj, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(AhorcadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(AhorcadoLayout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(JNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Aceptar)) .addComponent(Nombre) .addComponent(Mensaje, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(34, 34, 34))) .addContainerGap()) ); jPanel4.setBackground(new java.awt.Color(255, 255, 102)); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "<<Frase>>", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Agency FB", 1, 24), new java.awt.Color(0, 0, 0))); // NOI18N jPanel1.setForeground(new java.awt.Color(241, 243, 248)); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel1.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel1.setText("_"); jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 40, -1, -1)); jLabel2.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel2.setText("_"); jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 40, -1, -1)); jLabel3.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel3.setText("_"); jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 40, -1, -1)); jLabel4.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel4.setText("_"); jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 40, -1, -1)); jLabel5.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel5.setText("_"); jPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 40, -1, -1)); jLabel6.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel6.setText("_"); jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 40, -1, -1)); jLabel7.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel7.setText("_"); jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 40, -1, -1)); jLabel8.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel8.setText("_"); jPanel1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 40, -1, -1)); jLabel9.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel9.setText("_"); jPanel1.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 40, -1, -1)); jLabel10.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel10.setText("_"); jPanel1.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 40, -1, -1)); jLabel11.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel11.setText("_"); jPanel1.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 40, -1, -1)); jLabel12.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel12.setText("_"); jPanel1.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 40, -1, -1)); jLabel13.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel13.setText("_"); jPanel1.add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 40, -1, -1)); jLabel14.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel14.setText("_"); jPanel1.add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 40, -1, -1)); jLabel15.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel15.setText("_"); jPanel1.add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 40, -1, -1)); jLabel16.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel16.setText("_"); jPanel1.add(jLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 40, -1, -1)); jLabel17.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel17.setText("_"); jPanel1.add(jLabel17, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 40, -1, -1)); jLabel18.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel18.setText("_"); jPanel1.add(jLabel18, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 40, -1, -1)); jLabel19.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel19.setText("_"); jPanel1.add(jLabel19, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 40, -1, -1)); jLabel20.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel20.setText("_"); jPanel1.add(jLabel20, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 40, -1, -1)); jLabel21.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel21.setText("_"); jPanel1.add(jLabel21, new org.netbeans.lib.awtextra.AbsoluteConstraints(420, 40, -1, -1)); jLabel22.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel22.setText("_"); jPanel1.add(jLabel22, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 40, -1, -1)); jLabel23.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel23.setText("_"); jPanel1.add(jLabel23, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 40, -1, -1)); jLabel24.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel24.setText("_"); jPanel1.add(jLabel24, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 40, -1, -1)); jLabel25.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel25.setText("_"); jPanel1.add(jLabel25, new org.netbeans.lib.awtextra.AbsoluteConstraints(500, 40, -1, -1)); jLabel26.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel26.setText("_"); jPanel1.add(jLabel26, new org.netbeans.lib.awtextra.AbsoluteConstraints(520, 40, -1, -1)); jLabel27.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel27.setText("_"); jPanel1.add(jLabel27, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 40, -1, -1)); jLabel28.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel28.setText("_"); jPanel1.add(jLabel28, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 40, -1, -1)); jLabel29.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel29.setText("_"); jPanel1.add(jLabel29, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 40, -1, -1)); jLabel30.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel30.setText("_"); jPanel1.add(jLabel30, new org.netbeans.lib.awtextra.AbsoluteConstraints(600, 40, -1, -1)); jLabel31.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel31.setText("_"); jPanel1.add(jLabel31, new org.netbeans.lib.awtextra.AbsoluteConstraints(620, 40, -1, -1)); jLabel32.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel32.setText("_"); jPanel1.add(jLabel32, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 40, -1, -1)); jLabel33.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel33.setText("_"); jPanel1.add(jLabel33, new org.netbeans.lib.awtextra.AbsoluteConstraints(660, 40, -1, -1)); jLabel34.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel34.setText("_"); jPanel1.add(jLabel34, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 70, -1, -1)); jLabel35.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel35.setText("_"); jPanel1.add(jLabel35, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 70, -1, -1)); jLabel36.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel36.setText("_"); jPanel1.add(jLabel36, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 70, -1, -1)); jLabel37.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel37.setText("_"); jPanel1.add(jLabel37, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 70, -1, -1)); jLabel38.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel38.setText("_"); jPanel1.add(jLabel38, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 70, -1, -1)); jLabel39.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel39.setText("_"); jPanel1.add(jLabel39, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 70, -1, -1)); jLabel40.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel40.setText("_"); jPanel1.add(jLabel40, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 70, -1, -1)); jLabel41.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel41.setText("_"); jPanel1.add(jLabel41, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 70, -1, -1)); jLabel42.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel42.setText("_"); jPanel1.add(jLabel42, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 70, -1, -1)); jLabel43.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel43.setText("_"); jPanel1.add(jLabel43, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 70, -1, -1)); jLabel44.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel44.setText("_"); jPanel1.add(jLabel44, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 70, -1, -1)); jLabel45.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel45.setText("_"); jPanel1.add(jLabel45, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 70, -1, -1)); jLabel46.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel46.setText("_"); jPanel1.add(jLabel46, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 70, -1, -1)); jLabel47.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel47.setText("_"); jPanel1.add(jLabel47, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 70, -1, -1)); jLabel48.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel48.setText("_"); jPanel1.add(jLabel48, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 70, -1, -1)); jLabel49.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel49.setText("_"); jPanel1.add(jLabel49, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 70, -1, -1)); jLabel50.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel50.setText("_"); jPanel1.add(jLabel50, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 70, -1, -1)); jLabel51.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel51.setText("_"); jPanel1.add(jLabel51, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 70, -1, -1)); jLabel52.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel52.setText("_"); jPanel1.add(jLabel52, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 70, -1, -1)); jLabel53.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel53.setText("_"); jPanel1.add(jLabel53, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 70, -1, -1)); jLabel54.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel54.setText("_"); jPanel1.add(jLabel54, new org.netbeans.lib.awtextra.AbsoluteConstraints(420, 70, -1, -1)); jLabel55.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel55.setText("_"); jPanel1.add(jLabel55, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 70, -1, -1)); jLabel56.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel56.setText("_"); jPanel1.add(jLabel56, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 70, -1, -1)); jLabel57.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel57.setText("_"); jPanel1.add(jLabel57, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 70, -1, -1)); jLabel58.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel58.setText("_"); jPanel1.add(jLabel58, new org.netbeans.lib.awtextra.AbsoluteConstraints(500, 70, -1, -1)); jLabel59.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel59.setText("_"); jPanel1.add(jLabel59, new org.netbeans.lib.awtextra.AbsoluteConstraints(520, 70, -1, -1)); jLabel60.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel60.setText("_"); jPanel1.add(jLabel60, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 70, -1, -1)); jLabel61.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel61.setText("_"); jPanel1.add(jLabel61, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 70, -1, -1)); jLabel62.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel62.setText("_"); jPanel1.add(jLabel62, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 70, -1, -1)); jLabel63.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel63.setText("_"); jPanel1.add(jLabel63, new org.netbeans.lib.awtextra.AbsoluteConstraints(600, 70, -1, -1)); jLabel64.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel64.setText("_"); jPanel1.add(jLabel64, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 100, -1, -1)); jLabel65.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel65.setText("_"); jPanel1.add(jLabel65, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 100, -1, -1)); jLabel66.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel66.setText("_"); jPanel1.add(jLabel66, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 100, -1, -1)); jLabel67.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel67.setText("_"); jPanel1.add(jLabel67, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 100, -1, -1)); jLabel68.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel68.setText("_"); jPanel1.add(jLabel68, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 100, -1, -1)); jLabel69.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel69.setText("_"); jPanel1.add(jLabel69, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 100, -1, -1)); jLabel70.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel70.setText("_"); jPanel1.add(jLabel70, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 100, -1, -1)); jLabel71.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel71.setText("_"); jPanel1.add(jLabel71, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 100, -1, -1)); jLabel72.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel72.setText("_"); jPanel1.add(jLabel72, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 100, -1, -1)); jLabel73.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel73.setText("_"); jPanel1.add(jLabel73, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 100, -1, -1)); jLabel74.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel74.setText("_"); jPanel1.add(jLabel74, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 100, -1, -1)); jLabel75.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel75.setText("_"); jPanel1.add(jLabel75, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 100, -1, -1)); jLabel76.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel76.setText("_"); jPanel1.add(jLabel76, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 100, -1, -1)); jLabel77.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel77.setText("_"); jPanel1.add(jLabel77, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 100, -1, -1)); jLabel78.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel78.setText("_"); jPanel1.add(jLabel78, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 100, -1, -1)); jLabel79.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel79.setText("_"); jPanel1.add(jLabel79, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 100, -1, -1)); jLabel80.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel80.setText("_"); jPanel1.add(jLabel80, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 100, -1, -1)); jLabel81.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel81.setText("_"); jPanel1.add(jLabel81, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 100, -1, -1)); jLabel82.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel82.setText("_"); jPanel1.add(jLabel82, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 100, -1, -1)); jLabel83.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel83.setText("_"); jPanel1.add(jLabel83, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 100, -1, -1)); jLabel84.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel84.setText("_"); jPanel1.add(jLabel84, new org.netbeans.lib.awtextra.AbsoluteConstraints(420, 100, -1, -1)); jLabel85.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel85.setText("_"); jPanel1.add(jLabel85, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 100, -1, -1)); jLabel86.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel86.setText("_"); jPanel1.add(jLabel86, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 100, -1, -1)); jLabel87.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel87.setText("_"); jPanel1.add(jLabel87, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 100, -1, -1)); jLabel88.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel88.setText("_"); jPanel1.add(jLabel88, new org.netbeans.lib.awtextra.AbsoluteConstraints(500, 100, -1, -1)); jLabel89.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel89.setText("_"); jPanel1.add(jLabel89, new org.netbeans.lib.awtextra.AbsoluteConstraints(520, 100, -1, -1)); jLabel90.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel90.setText("_"); jPanel1.add(jLabel90, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 100, -1, -1)); jLabel91.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel91.setText("_"); jPanel1.add(jLabel91, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 100, -1, -1)); jLabel92.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel92.setText("_"); jPanel1.add(jLabel92, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 100, -1, -1)); jLabel93.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel93.setText("_"); jPanel1.add(jLabel93, new org.netbeans.lib.awtextra.AbsoluteConstraints(600, 100, -1, -1)); jLabel94.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel94.setText("_"); jPanel1.add(jLabel94, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 130, -1, -1)); jLabel95.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel95.setText("_"); jPanel1.add(jLabel95, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 130, -1, -1)); jLabel96.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel96.setText("_"); jPanel1.add(jLabel96, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 130, -1, -1)); jLabel97.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel97.setText("_"); jPanel1.add(jLabel97, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 130, -1, -1)); jLabel98.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel98.setText("_"); jPanel1.add(jLabel98, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 130, -1, -1)); jLabel99.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel99.setText("_"); jPanel1.add(jLabel99, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 130, -1, -1)); jLabel100.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel100.setText("_"); jPanel1.add(jLabel100, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 130, -1, -1)); jLabel101.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel101.setText("_"); jPanel1.add(jLabel101, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 130, -1, -1)); jLabel102.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel102.setText("_"); jPanel1.add(jLabel102, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 130, -1, -1)); jLabel103.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel103.setText("_"); jPanel1.add(jLabel103, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 130, -1, -1)); jLabel104.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel104.setText("_"); jPanel1.add(jLabel104, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 130, -1, -1)); jLabel105.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel105.setText("_"); jPanel1.add(jLabel105, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 130, -1, -1)); jLabel106.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel106.setText("_"); jPanel1.add(jLabel106, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 130, -1, -1)); jLabel107.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel107.setText("_"); jPanel1.add(jLabel107, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 130, -1, -1)); jLabel108.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel108.setText("_"); jPanel1.add(jLabel108, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 130, -1, -1)); jLabel109.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel109.setText("_"); jPanel1.add(jLabel109, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 130, 10, -1)); jLabel110.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel110.setText("_"); jPanel1.add(jLabel110, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 130, 10, -1)); jLabel111.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel111.setText("_"); jPanel1.add(jLabel111, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 130, 10, -1)); jLabel112.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel112.setText("_"); jPanel1.add(jLabel112, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 130, 10, -1)); jLabel113.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel113.setText("_"); jPanel1.add(jLabel113, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 130, 10, -1)); jLabel114.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel114.setText("_"); jPanel1.add(jLabel114, new org.netbeans.lib.awtextra.AbsoluteConstraints(420, 130, 10, -1)); jLabel115.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel115.setText("_"); jPanel1.add(jLabel115, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 130, 10, -1)); jLabel116.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel116.setText("_"); jPanel1.add(jLabel116, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 130, 10, -1)); jLabel117.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel117.setText("_"); jPanel1.add(jLabel117, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 130, 10, -1)); jLabel118.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel118.setText("_"); jPanel1.add(jLabel118, new org.netbeans.lib.awtextra.AbsoluteConstraints(500, 130, 10, -1)); jLabel119.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel119.setText("_"); jPanel1.add(jLabel119, new org.netbeans.lib.awtextra.AbsoluteConstraints(520, 130, 10, -1)); jLabel120.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel120.setText("_"); jPanel1.add(jLabel120, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 130, 10, -1)); jLabel121.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel121.setText("_"); jPanel1.add(jLabel121, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 130, 10, -1)); jLabel122.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel122.setText("_"); jPanel1.add(jLabel122, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 130, 10, -1)); jLabel123.setFont(new java.awt.Font("Agency FB", 0, 24)); jLabel123.setText("_"); jPanel1.add(jLabel123, new org.netbeans.lib.awtextra.AbsoluteConstraints(600, 130, 10, -1)); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 709, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(23, 23, 23) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(21, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(Ahorcado, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Ahorcado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed this.jButton1.setEnabled(false); this.C.PonerLetra(this.jButton1.getText().charAt(0),this.jButton1.getText(),this.jButton1.getText().charAt(0)); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: this.jButton2.setEnabled(false); this.C.PonerLetra(this.jButton2.getText().charAt(0),this.jButton2.getText(),this.jButton2.getText().charAt(0)); }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed // TODO add your handling code here: this.jButton3.setEnabled(false); this.C.PonerLetra(this.jButton3.getText().charAt(0),this.jButton3.getText(),this.jButton3.getText().charAt(0)); }//GEN-LAST:event_jButton3ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed this.jButton4.setEnabled(false); // TODO add your handling code here: this.C.PonerLetra(this.jButton4.getText().charAt(0),this.jButton4.getText(),this.jButton4.getText().charAt(0)); }//GEN-LAST:event_jButton4ActionPerformed private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed // TODO add your handling code here: this.jButton5.setEnabled(false); this.C.PonerLetra(this.jButton5.getText().charAt(0),this.jButton5.getText(),this.jButton5.getText().charAt(0)); }//GEN-LAST:event_jButton5ActionPerformed private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed // TODO add your handling code here: this.jButton6.setEnabled(false); this.C.PonerLetra(this.jButton6.getText().charAt(0),this.jButton6.getText(),this.jButton6.getText().charAt(0)); }//GEN-LAST:event_jButton6ActionPerformed private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed this.jButton7.setEnabled(false); // TODO add your handling code here: this.C.PonerLetra(this.jButton7.getText().charAt(0),this.jButton7.getText(),this.jButton7.getText().charAt(0)); }//GEN-LAST:event_jButton7ActionPerformed private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed this.jButton8.setEnabled(false); this.C.PonerLetra(this.jButton8.getText().charAt(0),this.jButton8.getText(),this.jButton8.getText().charAt(0)); }//GEN-LAST:event_jButton8ActionPerformed private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed this.jButton9.setEnabled(false); this.C.PonerLetra(this.jButton9.getText().charAt(0),this.jButton9.getText(),this.jButton9.getText().charAt(0)); }//GEN-LAST:event_jButton9ActionPerformed private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed this.jButton10.setEnabled(false); this.C.PonerLetra(this.jButton10.getText().charAt(0),this.jButton10.getText(),this.jButton10.getText().charAt(0)); }//GEN-LAST:event_jButton10ActionPerformed private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed // TODO add your handling code here: this.jButton11.setEnabled(false); this.C.PonerLetra(this.jButton11.getText().charAt(0),this.jButton11.getText(),this.jButton11.getText().charAt(0)); }//GEN-LAST:event_jButton11ActionPerformed private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed this.jButton12.setEnabled(false); this.C.PonerLetra(this.jButton12.getText().charAt(0),this.jButton12.getText(),this.jButton12.getText().charAt(0)); }//GEN-LAST:event_jButton12ActionPerformed private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton13ActionPerformed // TODO add your handling code here: this.jButton13.setEnabled(false); this.C.PonerLetra(this.jButton13.getText().charAt(0),this.jButton13.getText(),this.jButton13.getText().charAt(0)); }//GEN-LAST:event_jButton13ActionPerformed private void jButton14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton14ActionPerformed // TODO add your handling code here: this.jButton14.setEnabled(false); this.C.PonerLetra(this.jButton14.getText().charAt(0),this.jButton14.getText(),this.jButton14.getText().charAt(0)); }//GEN-LAST:event_jButton14ActionPerformed private void jButton15ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton15ActionPerformed // TODO add your handling code here: this.jButton15.setEnabled(false); this.C.PonerLetra(this.jButton15.getText().charAt(0),this.jButton15.getText(),this.jButton15.getText().charAt(0)); }//GEN-LAST:event_jButton15ActionPerformed private void jButton16ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton16ActionPerformed // TODO add your handling code here: this.jButton16.setEnabled(false); this.C.PonerLetra(this.jButton16.getText().charAt(0),this.jButton16.getText(),this.jButton16.getText().charAt(0)); }//GEN-LAST:event_jButton16ActionPerformed private void jButton17ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton17ActionPerformed // TODO add your handling code here: this.jButton17.setEnabled(false); this.C.PonerLetra(this.jButton17.getText().charAt(0),this.jButton17.getText(),this.jButton17.getText().charAt(0)); }//GEN-LAST:event_jButton17ActionPerformed private void jButton18ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton18ActionPerformed // TODO add your handling code here: this.jButton18.setEnabled(false); this.C.PonerLetra(this.jButton18.getText().charAt(0),this.jButton18.getText(),this.jButton18.getText().charAt(0)); }//GEN-LAST:event_jButton18ActionPerformed private void jButton19ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton19ActionPerformed // TODO add your handling code here: this.jButton19.setEnabled(false); this.C.PonerLetra(this.jButton19.getText().charAt(0),this.jButton19.getText(),this.jButton19.getText().charAt(0)); }//GEN-LAST:event_jButton19ActionPerformed private void jButton20ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton20ActionPerformed // TODO add your handling code here: this.jButton20.setEnabled(false); this.C.PonerLetra(this.jButton20.getText().charAt(0),this.jButton20.getText(),this.jButton20.getText().charAt(0)); }//GEN-LAST:event_jButton20ActionPerformed private void jButton21ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton21ActionPerformed // TODO add your handling code here: this.jButton21.setEnabled(false); this.C.PonerLetra(this.jButton21.getText().charAt(0),this.jButton21.getText(),this.jButton21.getText().charAt(0)); }//GEN-LAST:event_jButton21ActionPerformed private void jButton22ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton22ActionPerformed // TODO add your handling code here: this.jButton22.setEnabled(false); this.C.PonerLetra(this.jButton22.getText().charAt(0),this.jButton22.getText(),this.jButton22.getText().charAt(0)); }//GEN-LAST:event_jButton22ActionPerformed private void jButton23ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton23ActionPerformed // TODO add your handling code here: this.jButton23.setEnabled(false); this.C.PonerLetra(this.jButton23.getText().charAt(0),this.jButton23.getText(),this.jButton23.getText().charAt(0)); }//GEN-LAST:event_jButton23ActionPerformed private void jButton24ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton24ActionPerformed // TODO add your handling code here: this.jButton24.setEnabled(false); this.C.PonerLetra(this.jButton24.getText().charAt(0),this.jButton24.getText(),this.jButton24.getText().charAt(0)); }//GEN-LAST:event_jButton24ActionPerformed private void jButton25ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton25ActionPerformed // TODO add your handling code here: this.jButton25.setEnabled(false); this.C.PonerLetra(this.jButton25.getText().charAt(0),this.jButton25.getText(),this.jButton25.getText().charAt(0)); }//GEN-LAST:event_jButton25ActionPerformed private void jButton26ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton26ActionPerformed // TODO add your handling code here: this.jButton26.setEnabled(false); this.C.PonerLetra(this.jButton26.getText().charAt(0),this.jButton26.getText(),this.jButton26.getText().charAt(0)); }//GEN-LAST:event_jButton26ActionPerformed private void jButton27ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton27ActionPerformed // TODO add your handling code here: this.jButton27.setEnabled(false); this.C.PonerLetra(this.jButton27.getText().charAt(0),this.jButton27.getText(),this.jButton27.getText().charAt(0)); }//GEN-LAST:event_jButton27ActionPerformed private void ReiniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ReiniciarActionPerformed try { this.C.IniciarPartida(); } catch (SQLException ex) { Logger.getLogger(VistaPart.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_ReiniciarActionPerformed private void jButton28ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton28ActionPerformed try { // TODO add your handling code here: this.C.Salir(); } catch (Exception ex) { Logger.getLogger(VistaPart.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton28ActionPerformed private void AceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AceptarActionPerformed // TODO add your handling code here: this.C.GuardarPuntaje(); }//GEN-LAST:event_AceptarActionPerformed public JTextField getJNombre() { return JNombre; } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(VistaPart.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VistaPart.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VistaPart.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VistaPart.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new VistaPart().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton Aceptar; private javax.swing.JPanel Ahorcado; private javax.swing.JLabel ImagenLabel; private javax.swing.JTextField JNombre; private javax.swing.JLabel Mensaje; private javax.swing.JLabel Nombre; private javax.swing.JButton Reiniciar; private javax.swing.JLabel Reloj; private javax.swing.JButton jButton1; private javax.swing.JButton jButton10; private javax.swing.JButton jButton11; private javax.swing.JButton jButton12; private javax.swing.JButton jButton13; private javax.swing.JButton jButton14; private javax.swing.JButton jButton15; private javax.swing.JButton jButton16; private javax.swing.JButton jButton17; private javax.swing.JButton jButton18; private javax.swing.JButton jButton19; private javax.swing.JButton jButton2; private javax.swing.JButton jButton20; private javax.swing.JButton jButton21; private javax.swing.JButton jButton22; private javax.swing.JButton jButton23; private javax.swing.JButton jButton24; private javax.swing.JButton jButton25; private javax.swing.JButton jButton26; private javax.swing.JButton jButton27; private javax.swing.JButton jButton28; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JButton jButton7; private javax.swing.JButton jButton8; private javax.swing.JButton jButton9; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel100; private javax.swing.JLabel jLabel101; private javax.swing.JLabel jLabel102; private javax.swing.JLabel jLabel103; private javax.swing.JLabel jLabel104; private javax.swing.JLabel jLabel105; private javax.swing.JLabel jLabel106; private javax.swing.JLabel jLabel107; private javax.swing.JLabel jLabel108; private javax.swing.JLabel jLabel109; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel110; private javax.swing.JLabel jLabel111; private javax.swing.JLabel jLabel112; private javax.swing.JLabel jLabel113; private javax.swing.JLabel jLabel114; private javax.swing.JLabel jLabel115; private javax.swing.JLabel jLabel116; private javax.swing.JLabel jLabel117; private javax.swing.JLabel jLabel118; private javax.swing.JLabel jLabel119; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel120; private javax.swing.JLabel jLabel121; private javax.swing.JLabel jLabel122; private javax.swing.JLabel jLabel123; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel22; private javax.swing.JLabel jLabel23; private javax.swing.JLabel jLabel24; private javax.swing.JLabel jLabel25; private javax.swing.JLabel jLabel26; private javax.swing.JLabel jLabel27; private javax.swing.JLabel jLabel28; private javax.swing.JLabel jLabel29; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel30; private javax.swing.JLabel jLabel31; private javax.swing.JLabel jLabel32; private javax.swing.JLabel jLabel33; private javax.swing.JLabel jLabel34; private javax.swing.JLabel jLabel35; private javax.swing.JLabel jLabel36; private javax.swing.JLabel jLabel37; private javax.swing.JLabel jLabel38; private javax.swing.JLabel jLabel39; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel40; private javax.swing.JLabel jLabel41; private javax.swing.JLabel jLabel42; private javax.swing.JLabel jLabel43; private javax.swing.JLabel jLabel44; private javax.swing.JLabel jLabel45; private javax.swing.JLabel jLabel46; private javax.swing.JLabel jLabel47; private javax.swing.JLabel jLabel48; private javax.swing.JLabel jLabel49; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel50; private javax.swing.JLabel jLabel51; private javax.swing.JLabel jLabel52; private javax.swing.JLabel jLabel53; private javax.swing.JLabel jLabel54; private javax.swing.JLabel jLabel55; private javax.swing.JLabel jLabel56; private javax.swing.JLabel jLabel57; private javax.swing.JLabel jLabel58; private javax.swing.JLabel jLabel59; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel60; private javax.swing.JLabel jLabel61; private javax.swing.JLabel jLabel62; private javax.swing.JLabel jLabel63; private javax.swing.JLabel jLabel64; private javax.swing.JLabel jLabel65; private javax.swing.JLabel jLabel66; private javax.swing.JLabel jLabel67; private javax.swing.JLabel jLabel68; private javax.swing.JLabel jLabel69; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel70; private javax.swing.JLabel jLabel71; private javax.swing.JLabel jLabel72; private javax.swing.JLabel jLabel73; private javax.swing.JLabel jLabel74; private javax.swing.JLabel jLabel75; private javax.swing.JLabel jLabel76; private javax.swing.JLabel jLabel77; private javax.swing.JLabel jLabel78; private javax.swing.JLabel jLabel79; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel80; private javax.swing.JLabel jLabel81; private javax.swing.JLabel jLabel82; private javax.swing.JLabel jLabel83; private javax.swing.JLabel jLabel84; private javax.swing.JLabel jLabel85; private javax.swing.JLabel jLabel86; private javax.swing.JLabel jLabel87; private javax.swing.JLabel jLabel88; private javax.swing.JLabel jLabel89; private javax.swing.JLabel jLabel9; private javax.swing.JLabel jLabel90; private javax.swing.JLabel jLabel91; private javax.swing.JLabel jLabel92; private javax.swing.JLabel jLabel93; private javax.swing.JLabel jLabel94; private javax.swing.JLabel jLabel95; private javax.swing.JLabel jLabel96; private javax.swing.JLabel jLabel97; private javax.swing.JLabel jLabel98; private javax.swing.JLabel jLabel99; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; // End of variables declaration//GEN-END:variables public void MostrarMensaje() { JOptionPane.showMessageDialog(null, "Debe ingresar un Nombre para el Registro"); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Modelo; import BD.ConexionDAO; import bean.Conexion; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Vector; /** * * @author USUARIO */ public class Record extends ConexionDAO{ private Vector Nombre; private Vector Tiempo; public Record() { Nombre = new Vector(); Tiempo = new Vector(); } public void MostrarRecordN1() throws SQLException { int a =0; this.Nombre.clear(); this.Tiempo.clear(); ResultSet Resultado1; Resultado1 = Conexion.consultar("SELECT *FROM \"Jugador\" where \"Nivel\" = 1 order by \"Tiempo\" " ); while(Resultado1.next()){ this.Nombre.add(Resultado1.getString("Nombre")); this.Tiempo.add(Resultado1.getString("Tiempo")); } } public void MostrarRecordN2() throws SQLException { int a =0; this.Nombre.clear(); this.Tiempo.clear(); ResultSet Resultado1; Resultado1 = Conexion.consultar("SELECT *FROM \"Jugador\" where \"Nivel\" = 2 order by \"Tiempo\" "); while(Resultado1.next()){ this.Nombre.add(Resultado1.getString("Nombre")); this.Tiempo.add(Resultado1.getString("Tiempo")); } } public void MostrarRecordN3() throws SQLException { int a =0; this.Nombre.clear(); this.Tiempo.clear(); ResultSet Resultado1; Resultado1 = Conexion.consultar("SELECT *FROM \"Jugador\" where \"Nivel\" = 3 order by \"Tiempo\" "); while(Resultado1.next()){ this.Nombre.add(Resultado1.getString("Nombre")); this.Tiempo.add(Resultado1.getString("Tiempo")); } } public Vector getNombre() { return Nombre; } public Vector getTiempo() { return Tiempo; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Modelo; import BD.ConexionDAO; import bean.Conexion; /** * * @author USUARIO */ public class RegistrarDAO extends ConexionDAO{ public RegistrarDAO(String Tabla, String Texto) { boolean Resultado = Conexion.ejecutar(" INSERT INTO \""+Tabla+"\"( \"Id\", \"Texto\") VALUES (nextval('nombre_sequencia'), \'"+Texto+"\'); "); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Modelo; import BD.ConexionDAO; import bean.Conexion; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Random; /** * * @author Robert Alvarado */ public class ModPartidaDAO extends ConexionDAO { private Random R = new Random(); public ModPartidaDAO() { super(); } public String BuscarPalabra_1() throws SQLException{ ResultSet Resultado1,Resultado2; int Numero = 0; Resultado1 = Conexion.consultar("SELECT *FROM \"Palabra_1\" "); while(Resultado1.next()){ Numero++; } int Numero2 = R.nextInt(Numero)+1; Resultado2 = Conexion.consultar(" SELECT *FROM \"Palabra_1\" "); for (int h = 1; h <= Numero2; h++) { Resultado2.next(); } String Palabra_1 = Resultado2.getString("Texto"); return Palabra_1.toUpperCase(); } public String BuscarPalabra_2() throws SQLException{ ResultSet Resultado1,Resultado2; int Numero = 0; Resultado1 = Conexion.consultar("SELECT *FROM \"Palabra_2\" "); while(Resultado1.next()){ Numero++; } int Numero2 = R.nextInt(Numero)+1; Resultado2 = Conexion.consultar(" SELECT *FROM \"Palabra_2\" "); for (int h = 1; h <= Numero2; h++) { Resultado2.next(); } String Palabra_1 = Resultado2.getString("Texto"); return Palabra_1.toUpperCase(); } public String BuscarPalabra_3() throws SQLException{ ResultSet Resultado1,Resultado2; int Numero = 0; Resultado1 = Conexion.consultar("SELECT *FROM \"Palabra_3\" "); while(Resultado1.next()){ Numero++; } int Numero2 = R.nextInt(Numero)+1; Resultado2 = Conexion.consultar(" SELECT *FROM \"Palabra_3\" "); for (int h = 1; h <= Numero2; h++) { Resultado2.next(); } String Palabra_1 = Resultado2.getString("Texto"); return Palabra_1.toUpperCase(); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Modelo; import BD.ConexionDAO; import bean.Conexion; import java.sql.ResultSet; import javax.swing.Timer; /** * * @author Robert Alvarado */ public class Jugador extends ConexionDAO { private String Tiempo; private int Nivel; private String Nombre; public Jugador(String Nombre, int Nivel, String Tiempo) { this.Nombre = Nombre; this.Nivel = Nivel; this.Tiempo = Tiempo; this.GuardarPuntaje(); } public void GuardarPuntaje(){ boolean Resultado = Conexion.ejecutar(" INSERT INTO \"Jugador\"( \"Id\", \"Nombre\", \"Nivel\", \"Tiempo\") VALUES (nextval('nombre_sequencia'),\' "+this.Nombre+" \' ," + " "+this.Nivel+" , \' "+this.Tiempo+" \'); "); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Modelo; import java.sql.SQLException; import java.util.Vector; /** * * @author USUARIO */ public class ModPartida { private Vector PalabraOri = new Vector(); private Vector PalabraOri2 = new Vector(); private Vector Posicion = new Vector(); private int Error = 0; private int Acierto = 0; private ModPartidaDAO MPD = new ModPartidaDAO(); public ModPartida() throws SQLException { } public void BuscarPalabra() throws SQLException { this.PalabraOri.clear(); String Pal = null; Pal = this.MPD.BuscarPalabra_1(); for (int a = 0; a < Pal.length(); a++) { this.PalabraOri.add(Pal.charAt(a)); } } public void BuscarPalabra2() throws SQLException { this.PalabraOri2.clear(); String Pal = null; Pal = this.MPD.BuscarPalabra_2(); for (int a = 0; a < Pal.length(); a++) { this.PalabraOri2.add(Pal.charAt(a)); } } public void BuscarPalabra3() throws SQLException { this.PalabraOri2.clear(); String Pal = null; Pal = this.MPD.BuscarPalabra_3(); for (int a = 0; a < Pal.length(); a++) { this.PalabraOri2.add(Pal.charAt(a)); } } public Vector getPalabraOri() { return PalabraOri; } public Vector getPalabraOri2() { return PalabraOri2; } public void ContarError(){ this.Error++; } public int getError() { return Error; } public void setError(int Error) { this.Error = Error; } public int getAcierto() { return Acierto; } public void setAcierto(int Acierto) { this.Acierto = Acierto; } public boolean SeguirJugando() { boolean resp = true; if (this.Error < 8) { resp = true; } else { resp = false; } return resp; } public boolean Gano() { boolean resp = false; if (this.PalabraOri.size() == this.Acierto) { resp = true; } return resp; } public boolean Gano2() { boolean resp = false; if (this.PalabraOri2.size() == this.Acierto) { resp = true; } return resp; } public boolean BuscarLetra(char c) { boolean respuesta = false; for (int i = 0; i < PalabraOri.size(); i++) { if (c == PalabraOri.elementAt(i)) { this.Acierto++; this.Posicion.add(i + 1); respuesta = true; } } return respuesta; } public boolean BuscarLetra2(char c) { boolean respuesta = false; for (int i = 0; i < PalabraOri2.size(); i++) { if (c == PalabraOri2.elementAt(i)) { this.Acierto++; this.Posicion.add(i + 1); respuesta = true; } } return respuesta; } public boolean BuscarLetraV(String c) { boolean respuesta = false; for (int i = 0; i < PalabraOri2.size(); i++) { if (c == PalabraOri2.elementAt(i)) { this.Acierto++; this.Posicion.add(i + 1); respuesta = true; } } return respuesta; } public Vector getPosicion() { return Posicion; } public void LimpiarPosicion() { this.Posicion.clear(); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Modelo; /** * * @author Robert Alvarado */ public class Registrar { public Registrar() { } public int Contar(String Frase){ int P = 0; System.out.println(Frase.length()); for(int a = 0; a < Frase.length(); a++){ if(Frase.charAt(a) == ' '){ P++; } } return P+1; } }
Java
package test; public class test{ public static void main(String[] arg){ System.out.println("ok 1111"); } }
Java
package net.avc.video.cutter.natives; public class Natives { public static native int takePics(); }
Java
package net.avc.video.cutter; import net.avc.video.cutter.natives.Natives; import android.app.Activity; import android.os.Bundle; public class TakePics extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { // Load Lib System.loadLibrary("avformat"); System.loadLibrary("takepics"); Natives.takePics(); } catch (Exception e) { e.printStackTrace(); } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.proofer; import android.os.Handler; import android.view.View; public class SystemUiHider { private int HIDE_DELAY_MILLIS = 2000; private Handler mHandler; private View mView; public SystemUiHider(View view) { mView = view; } public void setup() { hideSystemUi(); mHandler = new Handler(); mView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() { @Override public void onSystemUiVisibilityChange(int visibility) { if (visibility != View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) { delay(); } } }); } private void hideSystemUi() { mView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); } private Runnable mHideRunnable = new Runnable() { public void run() { hideSystemUi(); } }; public void delay() { mHandler.removeCallbacks(mHideRunnable); mHandler.postDelayed(mHideRunnable, HIDE_DELAY_MILLIS); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.proofer; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewTreeObserver; import android.widget.TextView; import java.io.BufferedInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class DesktopViewerActivity extends Activity implements ViewTreeObserver.OnGlobalLayoutListener { private static final String TAG = "DesktopViewerActivity"; private static final int PORT_DEVICE = 7800; private View mTargetView; private TextView mStatusTextView; private boolean mKillServer; private int mOffsetX; private int mOffsetY; private int mWidth; private int mHeight; private final Object mDataSyncObject = new Object(); private byte[] mImageData; private SystemUiHider mSystemUiHider; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mStatusTextView = (TextView) findViewById(R.id.status_text); mTargetView = findViewById(R.id.target); mTargetView.setOnTouchListener(mTouchListener); mTargetView.getViewTreeObserver().addOnGlobalLayoutListener(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mSystemUiHider = new SystemUiHider(mTargetView); mSystemUiHider.setup(); } } @Override public void onResume() { super.onResume(); mKillServer = false; new Thread(mSocketThreadRunnable).start(); } public void onPause() { super.onPause(); mKillServer = true; } private OnTouchListener mTouchListener = new OnTouchListener() { float mDownX; float mDownY; float mDownOffsetX; float mDownOffsetY; @Override public boolean onTouch(View v, MotionEvent event) { if (mSystemUiHider != null) { mSystemUiHider.delay(); } int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: mDownX = event.getX(); mDownY = event.getY(); mDownOffsetX = mOffsetX; mDownOffsetY = mOffsetY; break; case MotionEvent.ACTION_MOVE: mOffsetX = (int) (mDownOffsetX + (mDownX - event.getX())); mOffsetY = (int) (mDownOffsetY + (mDownY - event.getY())); if (mOffsetX < 0) { mOffsetX = 0; } if (mOffsetY < 0) { mOffsetY = 0; } break; } return true; } }; private Handler mHandler = new Handler() { public void handleMessage(Message msg) { Bitmap bm = (Bitmap) msg.obj; mTargetView.setBackgroundDrawable(new BitmapDrawable(bm)); if (bm != null) { mStatusTextView.setVisibility(View.GONE); } else { mStatusTextView.setVisibility(View.VISIBLE); } } }; public void onGlobalLayout() { updateDimensions(); } private void updateDimensions() { synchronized (mDataSyncObject) { mWidth = mTargetView.getWidth(); mHeight = mTargetView.getHeight(); mImageData = new byte[mWidth * mHeight * 3]; } } private int readFully(BufferedInputStream bis, byte[] data, int offset, int len) throws IOException { int count = 0; int got = 0; while (count < len) { got = bis.read(data, count, len - count); if (got >= 0) { count += got; } else { break; } } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Got " + got + " bytes"); } return got; } private Runnable mSocketThreadRunnable = new Runnable() { public void run() { while (true) { ServerSocket server = null; try { Thread.sleep(1000); server = new ServerSocket(PORT_DEVICE); } catch (Exception e) { Log.e(TAG, "Error creating server socket", e); continue; } while (true) { try { Socket socket = server.accept(); Log.i(TAG, "Got connection request"); BufferedInputStream bis = new BufferedInputStream(socket.getInputStream()); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); while (!mKillServer) { Thread.sleep(50); synchronized (mDataSyncObject) { dos.writeInt(mOffsetX); dos.writeInt(mOffsetY); dos.writeInt(mWidth); dos.writeInt(mHeight); dos.flush(); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Wrote request"); } byte[] inlen = new byte[4]; readFully(bis, inlen, 0, 4); int len = ((inlen[0] & 0xFF) << 24) | ((inlen[1] & 0xFF) << 16) | ((inlen[2] & 0xFF) << 8) | (inlen[3] & 0xFF); readFully(bis, mImageData, 0, len); Bitmap bm = BitmapFactory.decodeByteArray(mImageData, 0, len); mHandler.sendMessage(mHandler.obtainMessage(1, bm)); } } bis.close(); dos.close(); socket.close(); server.close(); return; } catch (Exception e) { Log.e(TAG, "Exception transferring data", e); mHandler.sendMessage(mHandler.obtainMessage(1, null)); } } } } }; }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.desktop.proofer; public class Config { public static final String ANDROID_APP_PACKAGE_NAME = "com.google.android.apps.proofer"; public static final int PORT_LOCAL = 6800; public static final int PORT_DEVICE = 7800; }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.desktop.proofer; import com.google.android.desktop.proofer.os.OSBinder; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; public class ControllerForm implements WindowListener, OSBinder.Callbacks, Proofer.ProoferCallbacks, RegionSelector.RegionChangeCallback { private JFrame frame; private JPanel contentPanel; private JButton reinstallButton; private JLabel statusLabel; private JButton regionButton; private OSBinder osBinder = OSBinder.getBinder(this); private RegionSelector regionSelector; private Proofer proofer; public ControllerForm() { setupUI(); setupProofer(); } public static void main(String[] args) { // OSX only //System.setProperty("com.apple.mrj.application.apple.menu.about.name", // "Android Design Preview"); new ControllerForm(); } private void setupProofer() { proofer = new Proofer(this); try { proofer.setupPortForwarding(); } catch (ProoferException e) { // JOptionPane.showMessageDialog(frame, // e.getMessage(), // "Android Design Preview", // JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } try { proofer.installAndroidApp(false); proofer.runAndroidApp(); } catch (ProoferException e) { e.printStackTrace(); } proofer.startConnectionLoop(); proofer.setRequestedRegion(regionSelector.getRegion()); } private void setupUI() { frame = new JFrame(ControllerForm.class.getName()); frame.setTitle("Android Design Preview"); frame.setIconImages(Arrays.asList(Util.getAppIconMipmap())); frame.setAlwaysOnTop(true); frame.setMinimumSize(new Dimension(250, 150)); frame.setLocationByPlatform(true); tryLoadFrameConfig(); frame.setContentPane(contentPanel); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.setVisible(true); frame.addWindowListener(this); reinstallButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { try { proofer.installAndroidApp(true); proofer.runAndroidApp(); } catch (ProoferException e) { JOptionPane.showMessageDialog(frame, "Couldn't install the app: " + e.getMessage() + "\n" + "\nPlease make sure your device is connected over USB and " + "\nthat USB debugging is enabled on your device under " + "\nSettings > Applications > Development or" + "\nSettings > Developer options.", "Android Design Preview", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } }); regionSelector = new RegionSelector(this); regionButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { regionSelector.toggleWindow(); } }); } void trySaveFrameConfig() { try { Properties props = new Properties(); props.setProperty("x", String.valueOf(frame.getX())); props.setProperty("y", String.valueOf(frame.getY())); props.storeToXML(new FileOutputStream( new File(Util.getCacheDirectory(), "config.xml")), null); } catch (IOException e) { e.printStackTrace(); } } void tryLoadFrameConfig() { try { Properties props = new Properties(); props.loadFromXML( new FileInputStream(new File(Util.getCacheDirectory(), "config.xml"))); frame.setLocation( Integer.parseInt(props.getProperty("x", String.valueOf(frame.getX()))), Integer.parseInt(props.getProperty("y", String.valueOf(frame.getY())))); } catch (FileNotFoundException e) { } catch (IOException e) { e.printStackTrace(); } } public void windowClosing(WindowEvent windowEvent) { onQuit(); } public void onQuit() { try { proofer.killAndroidApp(); } catch (ProoferException e) { e.printStackTrace(); } trySaveFrameConfig(); frame.dispose(); System.exit(0); } public void windowOpened(WindowEvent windowEvent) { } public void windowClosed(WindowEvent windowEvent) { } public void windowIconified(WindowEvent windowEvent) { } public void windowDeiconified(WindowEvent windowEvent) { } public void windowActivated(WindowEvent windowEvent) { } public void windowDeactivated(WindowEvent windowEvent) { } public void onStateChange(Proofer.State newState) { switch (newState) { case ConnectedActive: statusLabel.setText("Connected, active"); break; case ConnectedIdle: statusLabel.setText("Connected, inactive"); break; case Disconnected: statusLabel.setText("Disconnected"); break; case Unknown: statusLabel.setText("N/A"); break; } } public void onRequestedSizeChanged(int width, int height) { regionSelector.requestSize(width, height); } public void onRegionChanged(Rectangle region) { if (proofer != null) { proofer.setRequestedRegion(region); } } { // GUI initializer generated by IntelliJ IDEA GUI Designer // >>> IMPORTANT!! <<< // DO NOT EDIT OR ADD ANY CODE HERE! $$$setupUI$$$(); } /** * Method generated by IntelliJ IDEA GUI Designer >>> IMPORTANT!! <<< DO NOT edit this method OR * call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { contentPanel = new JPanel(); contentPanel.setLayout(new GridBagLayout()); reinstallButton = new JButton(); reinstallButton.setText("Re-install App"); reinstallButton.setMnemonic('R'); reinstallButton.setDisplayedMnemonicIndex(0); GridBagConstraints gbc; gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 2; gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.insets = new Insets(8, 8, 8, 8); contentPanel.add(reinstallButton, gbc); final JPanel panel1 = new JPanel(); panel1.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.fill = GridBagConstraints.BOTH; gbc.insets = new Insets(8, 8, 8, 8); contentPanel.add(panel1, gbc); final JLabel label1 = new JLabel(); label1.setText("Status:"); panel1.add(label1); statusLabel = new JLabel(); statusLabel.setFont(new Font(statusLabel.getFont().getName(), Font.BOLD, statusLabel.getFont().getSize())); statusLabel.setText("N/A"); panel1.add(statusLabel); regionButton = new JButton(); regionButton.setText("Select Mirror Region"); regionButton.setMnemonic('M'); regionButton.setDisplayedMnemonicIndex(7); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.insets = new Insets(8, 8, 8, 8); contentPanel.add(regionButton, gbc); } /** * @noinspection ALL */ public JComponent $$$getRootComponent$$$() { return contentPanel; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.desktop.proofer; import java.awt.*; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.File; import java.io.IOException; import java.net.Socket; import javax.imageio.ImageIO; public class Proofer { private boolean debug = Util.isDebug(); private AdbRunner adbRunner; private ProoferClient client; private State state = State.Unknown; private ProoferCallbacks prooferCallbacks; public static interface ProoferCallbacks { public void onStateChange(State newState); public void onRequestedSizeChanged(int width, int height); } public static enum State { ConnectedActive, ConnectedIdle, Disconnected, Unknown, } public Proofer(ProoferCallbacks prooferCallbacks) { this.adbRunner = new AdbRunner(); this.client = new ProoferClient(); this.prooferCallbacks = prooferCallbacks; } public void startConnectionLoop() { new Thread(new Runnable() { public void run() { while (true) { try { client.connectAndWaitForRequests(); } catch (CannotConnectException e) { // Can't connect to device, try re-setting up port forwarding. // If no devices are connected, this will fail. try { setupPortForwarding(); } catch (ProoferException e2) { // If we get an error here, we're disconnected. updateState(State.Disconnected); } } try { Thread.sleep(1000); } catch (InterruptedException e) { break; } } } }).start(); } public void runAndroidApp() throws ProoferException { adbRunner.adb(new String[]{ "shell", "am", "start", "-a", "android.intent.action.MAIN", "-c", "android.intent.category.LAUNCHER", "-n", Config.ANDROID_APP_PACKAGE_NAME + "/.DesktopViewerActivity" }); } public void killAndroidApp() throws ProoferException { adbRunner.adb(new String[]{ "shell", "am", "force-stop", Config.ANDROID_APP_PACKAGE_NAME }); } public void uninstallAndroidApp() throws ProoferException { adbRunner.adb(new String[]{ "uninstall", Config.ANDROID_APP_PACKAGE_NAME }); } public void installAndroidApp(boolean force) throws ProoferException { if (force || !isAndroidAppInstalled()) { File apkPath = new File(Util.getCacheDirectory(), "Proofer.apk"); if (Util.extractResource("assets/Proofer.apk", apkPath)) { adbRunner.adb(new String[]{ "install", "-r", apkPath.toString() }); } else { throw new ProoferException("Error extracting Android APK."); } } } public void setupPortForwarding() throws ProoferException { try { adbRunner.adb(new String[]{ "forward", "tcp:" + Config.PORT_LOCAL, "tcp:" + Config.PORT_DEVICE }); } catch (ProoferException e) { throw new ProoferException("Couldn't automatically setup port forwarding. " + "You'll need to " + "manually run " + "\"adb forward tcp:" + Config.PORT_LOCAL + " " + "tcp:" + Config.PORT_DEVICE + "\" " + "on the command line.", e); } } public boolean isAndroidAppInstalled() throws ProoferException { String out = adbRunner.adb(new String[]{ "shell", "pm", "list", "packages" }); return out.contains(Config.ANDROID_APP_PACKAGE_NAME); } public void setRequestedRegion(Rectangle region) { client.setRequestedRegion(region); } public State getState() { return state; } private void updateState(State newState) { if (this.state != newState && debug) { switch (newState) { case ConnectedActive: System.out.println("State: Connected and active"); break; case ConnectedIdle: System.out.println("State: Connected and idle"); break; case Disconnected: System.out.println("State: Disconnected"); break; } } if (this.state != newState && prooferCallbacks != null) { prooferCallbacks.onStateChange(newState); } this.state = newState; } public static class CannotConnectException extends ProoferException { public CannotConnectException(Throwable throwable) { super(throwable); } } public class ProoferClient { private Rectangle requestedRegion = new Rectangle(0, 0, 0, 0); private Robot robot; private Rectangle screenBounds; private int curWidth = 0; private int curHeight = 0; public ProoferClient() { try { this.robot = new Robot(); } catch (AWTException e) { System.err.println("Error getting robot."); e.printStackTrace(); System.exit(1); } GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] screenDevices = environment.getScreenDevices(); Rectangle2D tempBounds = new Rectangle(); for (GraphicsDevice screenDevice : screenDevices) { tempBounds = tempBounds.createUnion( screenDevice.getDefaultConfiguration().getBounds()); } screenBounds = tempBounds.getBounds(); } public void setRequestedRegion(Rectangle region) { requestedRegion = region; } public void connectAndWaitForRequests() throws CannotConnectException { Socket socket; // Establish the connection. try { socket = new Socket("localhost", Config.PORT_LOCAL); } catch (IOException e) { throw new CannotConnectException(e); } if (debug) { System.out.println( "Local socket established " + socket.getRemoteSocketAddress().toString()); } // Wait for requests. try { DataInputStream dis = new DataInputStream(socket.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream()); while (true) { // Try processing a request. int x = dis.readInt(); int y = dis.readInt(); int width = dis.readInt(); int height = dis.readInt(); // If we reach this point, we didn't hit an IOException and we've received // a request from the device. x = requestedRegion.x; y = requestedRegion.y; if ((width != curWidth || height != curHeight) && prooferCallbacks != null) { prooferCallbacks.onRequestedSizeChanged(width, height); } curWidth = width; curHeight = height; updateState(State.ConnectedActive); if (debug) { System.out.println( "Got request: [" + x + ", " + y + ", " + width + ", " + height + "]"); } if (width > 1 && height > 1) { BufferedImage bi = capture(x, y, width, height); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bi, "PNG", baos); byte[] out = baos.toByteArray(); int len = out.length; byte[] outlen = new byte[4]; outlen[0] = (byte) ((len >> 24) & 0xFF); outlen[1] = (byte) ((len >> 16) & 0xFF); outlen[2] = (byte) ((len >> 8) & 0xFF); outlen[3] = (byte) (len & 0xFF); if (debug) { System.out.println("Writing " + len + " bytes."); } bos.write(outlen, 0, 4); bos.write(out, 0, len); bos.flush(); } // This loop will exit only when an IOException is thrown, indicating there's // nothing further to read. } } catch (IOException e) { // If we're not "connected", this just means we haven't received any requests yet // on the socket, so there's no error to log. if (debug) { System.out.println("No activity."); } } // No (or no more) requests. updateState(State.ConnectedIdle); } private BufferedImage capture(int x, int y, int width, int height) { x = Math.max(screenBounds.x, x); y = Math.max(screenBounds.y, y); if (x + width > screenBounds.x + screenBounds.width) { x = screenBounds.x + screenBounds.width - width; } if (y + height > screenBounds.y + screenBounds.height) { y = screenBounds.y + screenBounds.height - height; } Rectangle rect = new Rectangle(x, y, width, height); long before = System.currentTimeMillis(); BufferedImage bi = robot.createScreenCapture(rect); long after = System.currentTimeMillis(); if (debug) { System.out.println("Capture time: " + (after - before) + " msec"); } return bi; } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.desktop.proofer; import java.awt.Image; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.imageio.ImageIO; public class Util { public static boolean isDebug() { return "1".equals(System.getenv("PROOFER_DEBUG")); } public static boolean extractResource(String path, File to) { try { InputStream in = Util.class.getClassLoader().getResourceAsStream(path); if (in == null) { throw new FileNotFoundException(path); } OutputStream out = new FileOutputStream(to); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } return true; } public static Image[] getAppIconMipmap() { try { return new Image[]{ ImageIO.read( Util.class.getClassLoader().getResourceAsStream("assets/icon_16.png")), ImageIO.read( Util.class.getClassLoader().getResourceAsStream("assets/icon_32.png")), ImageIO.read( Util.class.getClassLoader().getResourceAsStream("assets/icon_128.png")), ImageIO.read( Util.class.getClassLoader().getResourceAsStream("assets/icon_512.png")), }; } catch (IOException e) { return new Image[]{}; } } // Cache directory code private static File cacheDirectory; static { // Determine/create cache directory // Default to root in user's home directory File rootDir = new File(System.getProperty("user.home")); if (!rootDir.exists() && rootDir.canWrite()) { // If not writable, root in current working directory rootDir = new File(System.getProperty("user.dir")); if (!rootDir.exists() && rootDir.canWrite()) { // TODO: create temporary directory somewhere if this fails System.err.println("No home directory and can't write to current directory."); System.exit(1); } } // The actual cache directory will be ${ROOT}/.android/proofer cacheDirectory = new File(new File(rootDir, ".android"), "proofer"); if (!cacheDirectory.exists()) { cacheDirectory.mkdirs(); } cacheDirectory.setWritable(true); } public static File getCacheDirectory() { return cacheDirectory; } // Which OS are we running on? (used to unpack different ADB binaries) public enum OS { Windows("windows"), Linux("linux"), Mac("mac"), Other(null); public String id; OS(String id) { this.id = id; } } private static OS currentOS; static { String osName = System.getProperty("os.name", "").toLowerCase(); if (osName.contains("windows")) { currentOS = OS.Windows; } else if (osName.contains("linux")) { currentOS = OS.Linux; } else if (osName.contains("mac") || osName.contains("darwin")) { currentOS = OS.Mac; } else { currentOS = OS.Other; } } public static OS getCurrentOS() { return currentOS; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.desktop.proofer; public class ProoferException extends Exception { public ProoferException() { super(); } public ProoferException(String s) { super(s); } public ProoferException(String s, Throwable throwable) { super(s, throwable); } public ProoferException(Throwable throwable) { super(throwable); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.desktop.proofer.os; import com.google.android.desktop.proofer.Util; import java.lang.reflect.InvocationTargetException; public abstract class OSBinder { protected Callbacks callbacks; public static interface Callbacks { public void onQuit(); } public static OSBinder getBinder(Callbacks callbacks) { try { switch (Util.getCurrentOS()) { case Mac: return (OSBinder) MacBinder.class.getConstructor(Callbacks.class) .newInstance(callbacks); } } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return new DefaultBinder(callbacks); } protected OSBinder(Callbacks callbacks) { this.callbacks = callbacks; } private static class DummyBinder extends OSBinder { private DummyBinder(Callbacks callbacks) { super(callbacks); } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.desktop.proofer.os; import com.apple.eawt.AppEvent; import com.apple.eawt.Application; import com.apple.eawt.QuitHandler; import com.apple.eawt.QuitResponse; import com.apple.eawt.QuitStrategy; public class MacBinder extends OSBinder implements QuitHandler { Application application; public MacBinder(Callbacks callbacks) { super(callbacks); application = Application.getApplication(); application.setQuitStrategy(QuitStrategy.SYSTEM_EXIT_0); application.setQuitHandler(this); } public void handleQuitRequestWith(AppEvent.QuitEvent quitEvent, QuitResponse quitResponse) { callbacks.onQuit(); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.desktop.proofer.os; public class DefaultBinder extends OSBinder { protected DefaultBinder(Callbacks callbacks) { super(callbacks); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.desktop.proofer; import com.sun.awt.AWTUtilities; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Frame; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Paint; import java.awt.Point; import java.awt.Rectangle; import java.awt.Stroke; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.font.LineMetrics; import java.awt.geom.Rectangle2D; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import javax.swing.JFrame; public class RegionSelector { private JFrame parentFrame; private JRegionSelectorFrame frame; private Rectangle region = new Rectangle(100, 100, 480, 800); private RegionChangeCallback regionChangeCallback; public static interface RegionChangeCallback { public void onRegionChanged(Rectangle region); } public RegionSelector(RegionChangeCallback regionChangeCallback) { this.regionChangeCallback = regionChangeCallback; setupUI(); } private void setupUI() { // http://java.sun.com/developer/technicalArticles/GUI/translucent_shaped_windows/ if (AWTUtilities.isTranslucencySupported(AWTUtilities.Translucency.TRANSLUCENT)) { //perform translucency operations here GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] devices = env.getScreenDevices(); GraphicsConfiguration translucencyCapableGC = null; for (int i = 0; i < devices.length && translucencyCapableGC == null; i++) { GraphicsConfiguration[] configs = devices[i].getConfigurations(); for (int j = 0; j < configs.length && translucencyCapableGC == null; j++) { if (AWTUtilities.isTranslucencyCapable(configs[j])) { translucencyCapableGC = configs[j]; } } } frame = new JRegionSelectorFrame(translucencyCapableGC); frame.setUndecorated(true); AWTUtilities.setWindowOpaque(frame, false); } else { frame = new JRegionSelectorFrame(null); frame.setUndecorated(true); } frame.setAlwaysOnTop(true); frame.setBounds(region); tryLoadFrameConfig(); frame.setResizable(true); setRegion(frame.getBounds()); } public void showWindow(boolean show) { frame.setVisible(show); } public void toggleWindow() { frame.setVisible(!frame.isVisible()); } public Rectangle getRegion() { return region; } private void setRegion(Rectangle region) { this.region = region; if (regionChangeCallback != null) { regionChangeCallback.onRegionChanged(this.region); } } public void requestSize(int width, int height) { this.region.width = width; this.region.height = height; frame.setSize(width, height); } void trySaveFrameConfig() { try { Properties props = new Properties(); props.setProperty("x", String.valueOf(frame.getX())); props.setProperty("y", String.valueOf(frame.getY())); props.storeToXML(new FileOutputStream( new File(Util.getCacheDirectory(), "region.xml")), null); } catch (IOException e) { e.printStackTrace(); } } private final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor(); private Runnable saveFrameConfigRunnable = new Runnable() { @Override public void run() { trySaveFrameConfig(); } }; private ScheduledFuture<?> saveFrameConfigScheduleHandle; void delayedTrySaveFrameConfig() { if (saveFrameConfigScheduleHandle != null) { saveFrameConfigScheduleHandle.cancel(false); } saveFrameConfigScheduleHandle = worker .schedule(saveFrameConfigRunnable, 1, TimeUnit.SECONDS); } void tryLoadFrameConfig() { try { Properties props = new Properties(); props.loadFromXML( new FileInputStream(new File(Util.getCacheDirectory(), "region.xml"))); frame.setLocation( Integer.parseInt(props.getProperty("x", String.valueOf(frame.getX()))), Integer.parseInt(props.getProperty("y", String.valueOf(frame.getY())))); } catch (FileNotFoundException e) { } catch (IOException e) { e.printStackTrace(); } } private class JRegionSelectorFrame extends Frame implements MouseListener, MouseMotionListener, KeyListener { private Paint strokePaint; private Paint fillPaint; private Stroke stroke; private Font font; private Point startDragPoint; private Point startLocation; private JRegionSelectorFrame(GraphicsConfiguration graphicsConfiguration) { super(graphicsConfiguration); fillPaint = new Color(0, 0, 0, 32); strokePaint = new Color(255, 0, 0, 128); stroke = new BasicStroke(5, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER); font = new Font(Font.DIALOG, Font.BOLD, 30); addMouseListener(this); addMouseMotionListener(this); addKeyListener(this); } @Override public void paint(Graphics graphics) { if (graphics instanceof Graphics2D) { Graphics2D g2d = (Graphics2D) graphics; g2d.setPaint(fillPaint); g2d.fillRect(0, 0, getWidth(), getHeight()); g2d.setPaint(strokePaint); g2d.setStroke(stroke); g2d.drawRect(0, 0, getWidth() - 1, getHeight() - 1); g2d.setFont(font); String s = getWidth() + " x " + getHeight(); Rectangle2D r = font.getStringBounds(s, g2d.getFontRenderContext()); g2d.drawString(s, (int) (getWidth() - r.getWidth()) / 2, getHeight() / 2); int offsY = (int) r.getHeight(); s = "(Double-click or ESC to hide)"; r = font.getStringBounds(s, g2d.getFontRenderContext()); g2d.drawString(s, (int) (getWidth() - r.getWidth()) / 2, getHeight() / 2 + offsY); } else { super.paint(graphics); } } // http://www.java2s.com/Tutorial/Java/0240__Swing/Dragandmoveaframefromitscontentarea.htm public void mousePressed(MouseEvent mouseEvent) { startDragPoint = getScreenLocation(mouseEvent); startLocation = getLocation(); if (mouseEvent.getClickCount() == 2) { showWindow(false); } } public void mouseDragged(MouseEvent mouseEvent) { Point current = getScreenLocation(mouseEvent); Point offset = new Point( (int) current.getX() - (int) startDragPoint.getX(), (int) current.getY() - (int) startDragPoint.getY()); Point newLocation = new Point( (int) (startLocation.getX() + offset.getX()), (int) (startLocation.getY() + offset.getY())); setLocation(newLocation); setRegion(getBounds()); delayedTrySaveFrameConfig(); } private Point getScreenLocation(MouseEvent e) { Point cursor = e.getPoint(); Point targetLocation = getLocationOnScreen(); return new Point( (int) (targetLocation.getX() + cursor.getX()), (int) (targetLocation.getY() + cursor.getY())); } public void mouseMoved(MouseEvent mouseEvent) { } public void mouseClicked(MouseEvent mouseEvent) { } public void mouseReleased(MouseEvent mouseEvent) { } public void mouseEntered(MouseEvent mouseEvent) { } public void mouseExited(MouseEvent mouseEvent) { } public void keyTyped(KeyEvent keyEvent) { } public void keyPressed(KeyEvent keyEvent) { if (keyEvent.getKeyCode() == KeyEvent.VK_ESCAPE) { showWindow(false); return; } Point newLocation = getLocation(); int val = keyEvent.isShiftDown() ? 10 : 1; switch (keyEvent.getKeyCode()) { case KeyEvent.VK_UP: newLocation.y -= val; break; case KeyEvent.VK_LEFT: newLocation.x -= val; break; case KeyEvent.VK_DOWN: newLocation.y += val; break; case KeyEvent.VK_RIGHT: newLocation.x += val; break; default: return; } setLocation(newLocation); setRegion(getBounds()); delayedTrySaveFrameConfig(); } public void keyReleased(KeyEvent keyEvent) { } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.desktop.proofer; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class AdbRunner { private boolean debug = Util.isDebug(); private File adbPath; private boolean ready = false; public AdbRunner() { try { prepareAdb(); } catch (ProoferException e) { e.printStackTrace(); } } private void prepareAdb() throws ProoferException { if (debug) { System.out.println("Preparing ADB"); } Util.OS currentOS = Util.getCurrentOS(); if (currentOS == Util.OS.Other) { throw new ProoferException("Unknown operating system, cannot run ADB."); } switch (currentOS) { case Mac: case Linux: adbPath = extractAssetToCacheDirectory(currentOS.id + "/adb", "adb"); break; case Windows: adbPath = extractAssetToCacheDirectory("windows/adb.exe", "adb.exe"); extractAssetToCacheDirectory("windows/AdbWinApi.dll", "AdbWinApi.dll"); extractAssetToCacheDirectory("windows/AdbWinUsbApi.dll", "AdbWinUsbApi.dll"); break; } if (!adbPath.setExecutable(true)) { throw new ProoferException("Error setting ADB binary as executable."); } ready = true; } private File extractAssetToCacheDirectory(String assetPath, String filename) throws ProoferException { File outFile = new File(Util.getCacheDirectory(), filename); if (!outFile.exists()) { if (!Util.extractResource("assets/" + assetPath, outFile)) { throw new ProoferException("Error extracting to " + outFile.toString()); } } return outFile; } public String adb(String[] args) throws ProoferException { if (debug) { StringBuilder sb = new StringBuilder(); sb.append("Calling ADB: adb"); for (String arg : args) { sb.append(" "); sb.append(arg); } System.out.println(sb.toString()); } List<String> argList = new ArrayList<String>(); argList.add(0, adbPath.getAbsolutePath()); Collections.addAll(argList, args); int returnCode; Runtime runtime = Runtime.getRuntime(); Process pr; StringBuilder sb = new StringBuilder(0); try { pr = runtime.exec(argList.toArray(new String[argList.size()])); // TODO: do something with pr.getErrorStream if needed. BufferedReader reader = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line = ""; while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } returnCode = pr.waitFor(); } catch (InterruptedException e) { throw new ProoferException(e); } catch (IOException e) { throw new ProoferException(e); } String out = sb.toString(); if (debug) { System.out.println("Output:" + out); } if (returnCode != 0) { throw new ProoferException("ADB returned error code " + returnCode); } return out; } }
Java
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import static android.nfc.NfcAdapter.EXTRA_TAG; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.content.IntentFilter; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.nfc.tech.IsoDep; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; final class NfcManager { static boolean hasHCE() { return VERSION.SDK_INT >= VERSION_CODES.KITKAT; } NfcManager(Activity activity) { this.activity = activity; nfcAdapter = NfcAdapter.getDefaultAdapter(activity); pendingIntent = PendingIntent.getActivity(activity, 0, new Intent( activity, activity.getClass()) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); } void onPause() { if (nfcAdapter != null) nfcAdapter.disableForegroundDispatch(activity); } void onResume() { if (nfcAdapter != null) nfcAdapter.enableForegroundDispatch(activity, pendingIntent, TAGFILTERS, TECHLISTS); } boolean isEnabled() { return nfcAdapter != null && nfcAdapter.isEnabled(); } static IsoDep attachCard(Intent intent) { Tag tag = (Tag) intent.getParcelableExtra(EXTRA_TAG); return (tag != null) ? IsoDep.get(tag) : null; } static String getCardId(IsoDep isodep) { if (isodep != null) { byte[] id = isodep.getTag().getId(); if (id != null && id.length > 0) return Logger.toHexString(id, 0, id.length); } return "UNKNOWN"; } static void closeConnect(IsoDep tag) { try { if (tag != null) tag.close(); } catch (Exception e) { } } static byte[] transceiveApdu(IsoDep tag, byte[] cmd) { if (tag != null) { try { if (!tag.isConnected()) { tag.connect(); tag.setTimeout(10000); } return tag.transceive(cmd); } catch (Exception e) { } } return null; } static byte[] transceiveApdu(IsoDep tag, int timeout, byte[] cmd) { if (tag != null) { try { if (tag.isConnected()) tag.close(); tag.connect(); tag.setTimeout(timeout); return tag.transceive(cmd); } catch (Exception e) { } } return null; } private final Activity activity; private NfcAdapter nfcAdapter; private PendingIntent pendingIntent; private static String[][] TECHLISTS; private static IntentFilter[] TAGFILTERS; static { try { TECHLISTS = new String[][] { { IsoDep.class.getName() } }; TAGFILTERS = new IntentFilter[] { new IntentFilter( NfcAdapter.ACTION_TECH_DISCOVERED, "*/*") }; } catch (Exception e) { } } }
Java
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import static com.sinpo.nfcspy.ServiceFactory.STA_FAIL; import static com.sinpo.nfcspy.ServiceFactory.STA_SUCCESS; import static com.sinpo.nfcspy.ServiceFactory.STA_UNKNOWN; import android.net.wifi.p2p.WifiP2pConfig; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pDeviceList; import android.net.wifi.p2p.WifiP2pInfo; import android.net.wifi.p2p.WifiP2pManager.ActionListener; import android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener; import android.net.wifi.p2p.WifiP2pManager.PeerListListener; abstract class WiFiP2PCommand { final static int CMD_DiscoverPeers = 0x01000000; final static int CMD_StopPeerDiscovery = 0x02000000; final static int CMD_RequestPeers = 0x03000000; final static int CMD_ConnectPeer = 0x04000000; final static int CMD_CancelConnect = 0x05000000; final static int CMD_RemoveGroup = 0x06000000; final static int CMD_RequestConnectionInfo = 0x07000000; WiFiP2PCommand(ServiceFactory.SpyCallback cb) { callback = cb; status = STA_UNKNOWN; } void setListener(ServiceFactory.SpyCallback cb) { callback = cb; } boolean isFinished() { return status != STA_UNKNOWN; } boolean isSuccessed() { return status == STA_SUCCESS; } void execute(WiFiP2PManager ctx) { if (!ctx.isInited()) { onFinished(STA_FAIL); } else { executeImp(ctx); } } protected void onFinished(int sta) { status = sta; if (callback != null) callback.handleMessage(id(), sta, null); } protected void onFinished(int sta, Object obj) { status = sta; if (callback != null) callback.handleMessage(id(), sta, obj); } abstract protected int id(); abstract protected void executeImp(WiFiP2PManager ctx); protected int status; protected int error; private ServiceFactory.SpyCallback callback; } abstract class WiFiP2PAction extends WiFiP2PCommand implements ActionListener { WiFiP2PAction(ServiceFactory.SpyCallback callback) { super(callback); } public void onSuccess() { onFinished(STA_SUCCESS); } public void onFailure(int reason) { error = reason; onFinished(STA_FAIL); } } final class Wifip2pRequestConnectionInfo extends WiFiP2PCommand implements ConnectionInfoListener { Wifip2pRequestConnectionInfo(ServiceFactory.SpyCallback callback) { super(callback); } @Override protected void executeImp(WiFiP2PManager ctx) { this.ctx = ctx; ctx.wifip2p.requestConnectionInfo(ctx.channel, this); } @Override public void onConnectionInfoAvailable(WifiP2pInfo info) { if (info.groupFormed) { ctx.groupOwnerAddress = info.groupOwnerAddress; ctx.isGroupOwner = info.isGroupOwner; ctx.isWifiP2pConnected = true; onFinished(STA_SUCCESS, info); } else { ctx.groupOwnerAddress = null; ctx.isGroupOwner = false; ctx.isWifiP2pConnected = false; onFinished(STA_FAIL); } } private WiFiP2PManager ctx; @Override protected int id() { return CMD_RequestConnectionInfo; } } final class Wifip2pDiscoverPeers extends WiFiP2PAction { Wifip2pDiscoverPeers(ServiceFactory.SpyCallback callback) { super(callback); } @Override protected int id() { return CMD_DiscoverPeers; } @Override protected void executeImp(WiFiP2PManager ctx) { ctx.wifip2p.discoverPeers(ctx.channel, this); } } final class Wifip2pStopPeerDiscovery extends WiFiP2PAction { Wifip2pStopPeerDiscovery(ServiceFactory.SpyCallback callback) { super(callback); } @Override protected int id() { return CMD_StopPeerDiscovery; } @Override protected void executeImp(WiFiP2PManager ctx) { ctx.wifip2p.stopPeerDiscovery(ctx.channel, this); } } final class Wifip2pRequestPeers extends WiFiP2PCommand implements PeerListListener { Wifip2pRequestPeers(ServiceFactory.SpyCallback callback) { super(callback); } @Override protected int id() { return CMD_RequestPeers; } @Override protected void executeImp(WiFiP2PManager ctx) { ctx.wifip2p.requestPeers(ctx.channel, this); } @Override public void onPeersAvailable(WifiP2pDeviceList peers) { onFinished(STA_SUCCESS, peers.getDeviceList()); } } final class Wifip2pConnectPeer extends WiFiP2PAction { Wifip2pConnectPeer(WifiP2pDevice peer, ServiceFactory.SpyCallback callback) { super(callback); this.peer = peer; } @Override protected int id() { return CMD_ConnectPeer; } @Override protected void executeImp(WiFiP2PManager ctx) { final WifiP2pConfig config = new WifiP2pConfig(); config.wps.setup = android.net.wifi.WpsInfo.PBC; config.deviceAddress = peer.deviceAddress; ctx.wifip2p.connect(ctx.channel, config, this); } private final WifiP2pDevice peer; } final class Wifip2pCancelConnect extends WiFiP2PAction { Wifip2pCancelConnect(ServiceFactory.SpyCallback callback) { super(callback); } @Override protected int id() { return CMD_CancelConnect; } @Override protected void executeImp(WiFiP2PManager ctx) { ctx.wifip2p.cancelConnect(ctx.channel, this); } } final class Wifip2pRemoveGroup extends WiFiP2PAction { Wifip2pRemoveGroup(ServiceFactory.SpyCallback callback) { super(callback); } @Override protected int id() { return CMD_RemoveGroup; } @Override protected void executeImp(WiFiP2PManager ctx) { ctx.wifip2p.removeGroup(ctx.channel, this); } }
Java
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import static android.net.wifi.p2p.WifiP2pManager.EXTRA_NETWORK_INFO; import static android.net.wifi.p2p.WifiP2pManager.EXTRA_WIFI_STATE; import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION; import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION; import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_STATE_ENABLED; import static com.sinpo.nfcspy.ServiceFactory.ACTION_NFC_ATTACH; import static com.sinpo.nfcspy.ServiceFactory.ACTION_NFC_DETTACH; import static com.sinpo.nfcspy.ServiceFactory.ACTION_SERVER_CHAT; import static com.sinpo.nfcspy.ServiceFactory.ACTION_SERVER_SET; import static com.sinpo.nfcspy.ServiceFactory.ACTION_SERVER_START; import static com.sinpo.nfcspy.ServiceFactory.ACTION_SERVER_STOP; import static com.sinpo.nfcspy.ServiceFactory.ERR_APDU_CMD; import static com.sinpo.nfcspy.ServiceFactory.ERR_APDU_RSP; import static com.sinpo.nfcspy.ServiceFactory.ERR_P2P; import static com.sinpo.nfcspy.ServiceFactory.MSG_CHAT_RECV; import static com.sinpo.nfcspy.ServiceFactory.MSG_CHAT_SEND; import static com.sinpo.nfcspy.ServiceFactory.MSG_HCE_APDU_CMD; import static com.sinpo.nfcspy.ServiceFactory.MSG_HCE_APDU_RSP; import static com.sinpo.nfcspy.ServiceFactory.MSG_HCE_ATTACH; import static com.sinpo.nfcspy.ServiceFactory.MSG_HCE_DEACTIVATED; import static com.sinpo.nfcspy.ServiceFactory.MSG_P2P_CONNECT; import static com.sinpo.nfcspy.ServiceFactory.MSG_P2P_DISCONN; import static com.sinpo.nfcspy.ServiceFactory.MSG_P2P_INIT; import static com.sinpo.nfcspy.ServiceFactory.MSG_P2P_SOCKET; import static com.sinpo.nfcspy.ServiceFactory.MSG_SERVER_KILL; import static com.sinpo.nfcspy.ServiceFactory.MSG_SERVER_VER; import static com.sinpo.nfcspy.ServiceFactory.STA_ERROR; import static com.sinpo.nfcspy.ServiceFactory.STA_FAIL; import static com.sinpo.nfcspy.ServiceFactory.STA_NOTCARE; import static com.sinpo.nfcspy.ServiceFactory.STA_P2P_WATING; import static com.sinpo.nfcspy.ServiceFactory.STA_SUCCESS; import static com.sinpo.nfcspy.WiFiP2PCommand.CMD_RequestConnectionInfo; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.NetworkInfo; import android.net.wifi.p2p.WifiP2pManager.ChannelListener; import android.nfc.tech.IsoDep; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Messenger; import android.os.SystemClock; final class ServiceAgent extends BroadcastReceiver implements ChannelListener, ServiceFactory.SpyCallback { void handleIntent(Intent intent) { final String action = intent.getAction(); if (ACTION_NFC_ATTACH.equals(action)) onCardAttaching(intent); else if (ACTION_NFC_DETTACH.equals(action)) onCardDettached(intent); else if (ACTION_SERVER_START.equals(action)) onStartCommand(intent); else if (ACTION_SERVER_STOP.equals(action)) onStopCommand(intent); else if (ACTION_SERVER_CHAT.equals(action)) onSendChatMessage(intent); else if (ACTION_SERVER_SET.equals(action)) onSetCommand(intent); } @Override public void handleMessage(int type, int status, Object obj) { switch (type) { case MSG_HCE_APDU_CMD: processCommandApdu((byte[]) obj); break; case MSG_HCE_APDU_RSP: processResponseApdu((byte[]) obj); break; case MSG_HCE_ATTACH: Logger.logNfcAttach(new String((byte[]) obj)); sendBinary2Activity(MSG_HCE_ATTACH, (byte[]) obj); break; case MSG_HCE_DEACTIVATED: NfcManager.closeConnect(isodep); Logger.logHceDeactive(); sendStatus2Activity(MSG_HCE_DEACTIVATED, STA_NOTCARE, 0); break; case MSG_SERVER_VER: if (obj == null) sendBinary2Peer(MSG_SERVER_VER, ThisApplication.version() .getBytes()); else sendBinary2Activity(MSG_SERVER_VER, (byte[]) obj); break; case MSG_CHAT_SEND: sendBinary2Activity(MSG_CHAT_RECV, (byte[]) obj); break; case CMD_RequestConnectionInfo: if (lock()) { if (status == STA_SUCCESS) { new SocketConnector(p2p, this).start(); } else { sendStatus2Activity(MSG_P2P_SOCKET, status, 0); unlock(); } } break; case MSG_P2P_CONNECT: if (status == STA_SUCCESS) sendVersion2Peer(); // go through case MSG_P2P_DISCONN: if (status == STA_SUCCESS || status == STA_FAIL) unlock(); sendStatus2Activity(type, status, STA_NOTCARE); break; case MSG_SERVER_KILL: stopSelf(false); break; } } @Override public void onReceive(Context context, Intent i) { delayAction(MSG_SERVER_KILL, 120000); final String action = i.getAction(); if (WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) { if (i.getIntExtra(EXTRA_WIFI_STATE, -1) != WIFI_P2P_STATE_ENABLED) disconnect(); } else if (WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) { if (((NetworkInfo) i.getParcelableExtra(EXTRA_NETWORK_INFO)) .isConnected()) { new Wifip2pRequestConnectionInfo(this).execute(p2p); } } } private void onStartCommand(Intent intent) { Messenger messenger = ServiceFactory.getReplyMessengerExtra(intent); if ((outbox = messenger) != null) { if (p2p.isConnected()) { sendStatus2Activity(MSG_P2P_CONNECT, STA_SUCCESS, STA_NOTCARE); return; } if (!p2p.isInited()) { p2p.init(service, this); service.registerReceiver(this, P2PFILTER); sendStatus2Activity(MSG_P2P_INIT, STA_SUCCESS, STA_NOTCARE); } sendStatus2Activity(MSG_P2P_CONNECT, STA_P2P_WATING, STA_NOTCARE); delayAction(MSG_SERVER_KILL, 90000); new Wifip2pRequestConnectionInfo(this).execute(p2p); } } private void processCommandApdu(byte[] cmd) { final long stampCmd = System.currentTimeMillis(); if (cmd != null && cmd.length > 0) { byte[] rsp = NfcManager.transceiveApdu(isodep, cmd); if (rsp == null) rsp = NfcManager.transceiveApdu(isodep, 20000, cmd); final long stampRsp = System.currentTimeMillis(); final boolean valid = (rsp != null && rsp.length > 0); boolean sent = false; if (valid) sent = sendBinary2Peer(MSG_HCE_APDU_RSP, rsp); final long delayCmd = Logger.logApdu(stampCmd, false, true, cmd); final long delayRsp = Logger.logApdu(stampRsp, false, false, rsp); if (!highSpeed) { sendBinary2Activity(MSG_HCE_APDU_CMD, (int) delayCmd, cmd); if (valid) sendBinary2Activity(MSG_HCE_APDU_RSP, (int) delayRsp, rsp); } if (!valid) sendStatus2Activity(MSG_HCE_APDU_RSP, STA_ERROR, ERR_APDU_RSP); if (!sent) sendStatus2Activity(MSG_HCE_APDU_RSP, STA_ERROR, ERR_P2P); } else { Logger.logApdu(stampCmd, false, true, null); sendStatus2Activity(MSG_HCE_APDU_CMD, STA_ERROR, ERR_APDU_CMD); } } private void processResponseApdu(byte[] rsp) { ((ServiceFactory.SpyService) service).processResponseApdu(rsp); Logger.logApdu(System.currentTimeMillis(), true, false, rsp); } private void onCardAttaching(Intent intent) { isodep = NfcManager.attachCard(intent); if (isodep != null) { String id = NfcManager.getCardId(isodep); Logger.logNfcAttach(id); byte[] raw = id.getBytes(); sendBinary2Peer(MSG_HCE_ATTACH, raw); sendBinary2Activity(MSG_HCE_ATTACH, raw); } } private void onSetCommand(Intent intent) { highSpeed = ServiceFactory.getHighSpeedSettingExtra(intent); } private void onSendChatMessage(Intent intent) { byte[] msg = ServiceFactory.getChatMessageExtra(intent).getBytes(); if (sendBinary2Peer(MSG_CHAT_SEND, msg)) sendBinary2Activity(MSG_CHAT_SEND, msg); } private void onStopCommand(Intent intent) { stopSelf(true); } private void onCardDettached(Intent intent) { isodep = null; } void onDeactivated(int reason) { sendBinary2Peer(MSG_HCE_DEACTIVATED, new byte[1]); Logger.logHceDeactive(); if (!highSpeed) sendStatus2Activity(MSG_HCE_DEACTIVATED, STA_NOTCARE, 0); } byte[] processCommandApdu(byte[] apdu, Bundle ignore) { sendBinary2Peer(MSG_HCE_APDU_CMD, apdu); Logger.logApdu(System.currentTimeMillis(), true, true, apdu); return null; } void onDestroy() { service.unregisterReceiver(this); onCardDettached(null); disconnect(); } private void stopSelf(boolean force) { if (force || !p2p.isConnected()) service.stopSelf(); } @Override public void onChannelDisconnected() { disconnect(); } private void disconnect() { p2p.reset(); } private void sendVersion2Peer() { // random delay between a few seconds int delay = (int) (SystemClock.uptimeMillis() & 0x3FF); delayAction(MSG_SERVER_VER, delay + 1000); } private boolean sendBinary2Peer(int type, byte[] raw) { return p2p.sendData(type, raw); } private void sendBinary2Activity(int type, byte[] raw) { sendBinary2Activity(type, STA_NOTCARE, raw); } private void sendBinary2Activity(int type, int arg, byte[] raw) { try { Message msg = Message.obtain(null, type, raw.length, arg); ServiceFactory.setDataToMessage(msg, raw); outbox.send(msg); } catch (Exception e) { } } private void sendStatus2Activity(int type, int status, int detail) { try { outbox.send(Message.obtain(null, type, status, detail)); } catch (Exception e) { } } private void delayAction(int type, long millis) { handler.postDelayed(new Action(this, type, STA_NOTCARE), millis); } ServiceAgent(Service service) { this.service = service; this.handler = new Handler(); this.p2p = new WiFiP2PManager(); outbox = null; Logger.open(); } synchronized boolean lock() { if (!lock) { lock = true; return true; } return false; } synchronized void unlock() { lock = false; } private final static class Action implements Runnable { private final ServiceFactory.SpyCallback callback; private final int type, status; @Override public void run() { callback.handleMessage(type, status, null); } Action(ServiceFactory.SpyCallback cback, int type, int status) { this.callback = cback; this.type = type; this.status = status; } } private final Service service; private final WiFiP2PManager p2p; private final Handler handler; private IsoDep isodep; private Messenger outbox; private boolean lock; private static boolean highSpeed; private final static IntentFilter P2PFILTER; static { P2PFILTER = new IntentFilter(); P2PFILTER.addAction(WIFI_P2P_STATE_CHANGED_ACTION); P2PFILTER.addAction(WIFI_P2P_CONNECTION_CHANGED_ACTION); } }
Java
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import android.app.Activity; import android.os.Handler; abstract class ActivityBase extends Activity { @Override public void onBackPressed() { if (!safeExit.isLocked()) super.onBackPressed(); } @Override public void onWindowFocusChanged(boolean hasFocus) { if (hasFocus) safeExit.unlockDelayed(800); else safeExit.setLock(true); } private final SafeExitLock safeExit = new SafeExitLock(); private final static class SafeExitLock extends Handler implements Runnable { private boolean lock; @Override public void run() { setLock(false); } boolean isLocked() { return lock; } void setLock(boolean lock) { this.lock = lock; } void unlockDelayed(long delayMillis) { postDelayed(this, delayMillis); } SafeExitLock() { setLock(true); } } }
Java
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import android.app.Service; import android.content.Intent; import android.os.Bundle; import android.os.IBinder; public final class ServiceLite extends Service implements ServiceFactory.SpyService { private ServiceAgent agent; @Override public void onCreate() { super.onCreate(); agent = new ServiceAgent(this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { agent.handleIntent(intent); return START_NOT_STICKY; } @Override public void onDestroy() { agent.onDestroy(); agent = null; super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return null; } @Override public void processResponseApdu(byte[] apdu) { } @Override public byte[] processCommandApdu(byte[] commandApdu, Bundle extras) { return null; } }
Java
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import android.annotation.SuppressLint; import android.content.Intent; import android.nfc.cardemulation.HostApduService; import android.os.Bundle; @SuppressLint("NewApi") public final class ServiceFull extends HostApduService implements ServiceFactory.SpyService { private ServiceAgent agent; @Override public void onCreate() { super.onCreate(); agent = new ServiceAgent(this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { agent.handleIntent(intent); return START_NOT_STICKY; } @Override public void onDestroy() { agent.onDestroy(); agent = null; super.onDestroy(); } @Override public void onDeactivated(int reason) { if (DEACTIVATION_LINK_LOSS == reason) agent.onDeactivated(reason); } @Override public byte[] processCommandApdu(byte[] commandApdu, Bundle extras) { return agent.processCommandApdu(commandApdu, extras); } @Override public void processResponseApdu(byte[] apdu) { sendResponseApdu(apdu); } }
Java
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Message; import android.os.Messenger; final class ServiceFactory { final static String ACTION_SERVER_START = "ACTION_SERVER_START"; final static String ACTION_SERVER_STOP = "ACTION_SERVER_STOP"; final static String ACTION_SERVER_SET = "ACTION_SERVER_SET"; final static String ACTION_SERVER_CHAT = "ACTION_SERVER_CHAT"; final static String ACTION_NFC_ATTACH = "ACTION_NFC_ATTACH"; final static String ACTION_NFC_DETTACH = "ACTION_NFC_DETTACH"; final static int MSG_P2P_INIT = 0x11; final static int MSG_P2P_SOCKET = 0x12; final static int MSG_P2P_CONNECT = 0x13; final static int MSG_P2P_DISCONN = 0x14; final static int MSG_SERVER_KILL = 0x21; final static int MSG_SERVER_START = 0x22; final static int MSG_SERVER_STOP = 0x23; final static int MSG_SERVER_VER = 0x24; final static int MSG_HCE_ATTACH = 0x31; final static int MSG_HCE_DETTACH = 0x32; final static int MSG_HCE_DEACTIVATED = 0x33; final static int MSG_HCE_APDU_CMD = 0x34; final static int MSG_HCE_APDU_RSP = 0x35; final static int MSG_CHAT_SEND = 0x41; final static int MSG_CHAT_RECV = 0x42; final static int STA_NOTCARE = 0xFFFFFFFF; final static int STA_UNKNOWN = 0x00; final static int STA_SUCCESS = 0x01; final static int STA_FAIL = 0x02; final static int STA_ERROR = 0x03; final static int STA_P2P_UNINIT = 0x00; final static int STA_P2P_INITED = 0x10; final static int STA_P2P_WATING = 0x11; final static int STA_P2P_ACCEPT = 0x12; final static int STA_P2P_CLIENT = 0x13; final static int ERR_APDU_RSP = 0x21; final static int ERR_APDU_CMD = 0x22; final static int ERR_P2P = 0x23; interface SpyService { void processResponseApdu(byte[] apdu); byte[] processCommandApdu(byte[] commandApdu, Bundle extras); } interface SpyCallback { void handleMessage(int type, int status, Object obj); } static void startServer(Context ctx, Messenger reply) { final Intent i = newServerIntent(ctx, ACTION_SERVER_START); ctx.startService(i.putExtra(KEY_REPLY, reply)); } static void setTag2Server(Context ctx, Intent nfc) { final Intent i = newServerIntent(ctx, ACTION_NFC_ATTACH); ctx.startService(i.replaceExtras(nfc)); } static void resetTag2Server(Context ctx) { ctx.startService(newServerIntent(ctx, ACTION_NFC_DETTACH)); } static void setHighSpeed2Server(Context ctx, boolean set) { final Intent i = newServerIntent(ctx, ACTION_SERVER_SET); ctx.startService(i.putExtra(KEY_HISPD, set)); } static void sendChatMessage2Server(Context ctx, String msg) { final Intent i = newServerIntent(ctx, ACTION_SERVER_CHAT); ctx.startService(i.putExtra(KEY_CHAT, msg)); } static void stopServer(Context ctx) { ctx.stopService(newServerIntent(ctx, ACTION_SERVER_STOP)); } static Messenger getReplyMessengerExtra(Intent intent) { return (Messenger) intent.getParcelableExtra(KEY_REPLY); } static String getChatMessageExtra(Intent intent) { return intent.getStringExtra(KEY_CHAT); } static boolean getHighSpeedSettingExtra(Intent intent) { return intent.getBooleanExtra(KEY_HISPD, false); } static byte[] extractDataFromMessage(Message msg) { Bundle data = msg.getData(); return (data != null) ? data.getByteArray(KEY_BLOB) : null; } static void setDataToMessage(Message msg, byte[] raw) { Bundle data = new Bundle(); data.putByteArray(KEY_BLOB, raw); msg.setData(data); } private static Intent newServerIntent(Context ctx, String action) { Class<?> clazz = ServiceLite.class; if (NfcManager.hasHCE()) { try { clazz = Class.forName("com.sinpo.nfcspy.ServiceFull"); } catch (Exception e) { clazz = ServiceLite.class; } } return new Intent(action, null, ctx, clazz); } private final static String KEY_REPLY = "KEY_REPLY"; private final static String KEY_HISPD = "KEY_HISPD"; private final static String KEY_CHAT = "KEY_CHAT"; private final static String KEY_BLOB = "KEY_BLOB"; }
Java
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import static android.net.wifi.p2p.WifiP2pManager.EXTRA_WIFI_P2P_DEVICE; import static android.net.wifi.p2p.WifiP2pManager.EXTRA_WIFI_STATE; import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION; import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION; import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION; import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION; import java.util.ArrayList; import java.util.Collection; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.IntentFilter; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pManager; import android.net.wifi.p2p.WifiP2pManager.ChannelListener; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class ActivityManageP2P extends ActivityBase { public void startDiscover(View v) { resetPeers(); if (!WiFiP2PManager.isWiFiEnabled(this)) { showMessage(R.string.status_no_wifi); return; } new CommandHelper(new Wifip2pDiscoverPeers(eventHelper), p2p, getString(R.string.info_discovering)).execute(); } public void disconnectPeer(View v) { new Wifip2pCancelConnect(eventHelper).execute(p2p); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_manage_p2p); peerdevs = new ArrayList<WifiP2pDevice>(); peers = new ArrayAdapter<CharSequence>(this, R.layout.listitem_peer); eventHelper = new EventHelper(); ListView lv = ((ListView) findViewById(R.id.list)); lv.setAdapter(peers); lv.setOnItemClickListener(eventHelper); thisDevice = (TextView) findViewById(R.id.txtThisdevice); } @Override protected void onResume() { p2p = new WiFiP2PManager(); p2p.init(this, eventHelper); registerReceiver(eventHelper, getWiFiP2PIntentFilter()); super.onResume(); } @Override protected void onPause() { closeProgressDialog(); new Wifip2pStopPeerDiscovery(null).execute(p2p); unregisterReceiver(eventHelper); p2p.reset(); p2p = null; resetPeers(); super.onPause(); } @SuppressWarnings("unchecked") boolean handleMessage(int type, int status, Object obj) { if (type == WiFiP2PCommand.CMD_RequestPeers) { resetPeers(); if (obj != null) { for (WifiP2pDevice dev : (Collection<WifiP2pDevice>) obj) { peerdevs.add(dev); peers.add(getWifiP2pDeviceInfo(dev)); } } return true; } if (type == WiFiP2PCommand.CMD_CancelConnect) { new Wifip2pRemoveGroup(eventHelper).execute(p2p); return true; } if (type == WiFiP2PCommand.CMD_RemoveGroup) { new Wifip2pDiscoverPeers(eventHelper).execute(p2p); return true; } return true; } void handlePeerListClick(int index) { WifiP2pDevice dev = peerdevs.get(index); if (dev.status == WifiP2pDevice.CONNECTED || dev.status == WifiP2pDevice.INVITED) { disconnectPeer(dev); } else if (dev.status != WifiP2pDevice.UNAVAILABLE) { connectPeer(dev); } } void handleBroadcast(Intent intent) { closeProgressDialog(); final String action = intent.getAction(); if (WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) { int state = intent.getIntExtra(EXTRA_WIFI_STATE, -1); if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) { p2p.isWifiP2pEnabled = true; } else { showMessage(R.string.event_p2p_disable); resetData(); } } else if (WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) { new Wifip2pRequestPeers(eventHelper).execute(p2p); } else if (WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) { WifiP2pDevice me = (WifiP2pDevice) intent .getParcelableExtra(EXTRA_WIFI_P2P_DEVICE); thisDevice.setText(getWifiP2pDeviceInfo(me)); } } void showMessage(int resId) { showMessage(getString(resId)); } void showMessage(CharSequence msg) { Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); } void showProgressDialog(CharSequence msg) { closeProgressDialog(); ProgressDialog pd = new ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT); progressDialog = pd; pd.setMessage(msg); pd.setProgressStyle(ProgressDialog.STYLE_SPINNER); pd.setIndeterminate(true); pd.setCancelable(true); pd.setCanceledOnTouchOutside(false); pd.show(); } void closeProgressDialog() { if (progressDialog != null) { progressDialog.dismiss(); progressDialog = null; } } void onChannelDisconnected() { showMessage(R.string.event_p2p_disable); resetData(); p2p.reset(); } private void connectPeer(WifiP2pDevice peer) { CharSequence dev = getWifiP2pDeviceInfo2(peer); CharSequence msg = Logger.fmt(getString(R.string.info_connect), dev); CharSequence msg2 = Logger .fmt(getString(R.string.info_connecting), dev); CommandHelper cmd = new CommandHelper(new Wifip2pConnectPeer(peer, eventHelper), p2p, msg2); new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT) .setTitle(R.string.lab_p2p_connect).setMessage(msg) .setNegativeButton(R.string.action_cancel, cmd) .setPositiveButton(R.string.action_ok, cmd).show(); } private void disconnectPeer(WifiP2pDevice peer) { CharSequence dev = getWifiP2pDeviceInfo2(peer); CharSequence msg = Logger.fmt(getString(R.string.info_disconnect), dev); CommandHelper cmd = new CommandHelper(new Wifip2pCancelConnect( eventHelper), p2p, null); new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT) .setTitle(R.string.lab_p2p_disconnect).setMessage(msg) .setNegativeButton(R.string.action_cancel, cmd) .setPositiveButton(R.string.action_ok, cmd).show(); } private void resetPeers() { peerdevs.clear(); peers.clear(); } private void resetData() { p2p.isWifiP2pEnabled = false; thisDevice.setText(null); resetPeers(); } private CharSequence getWifiP2pDeviceInfo(WifiP2pDevice dev) { CharSequence sta = getWifiP2pDeviceStatus(dev); return Logger.fmt("%s [%s] [%s]", dev.deviceName, dev.deviceAddress, sta); } private CharSequence getWifiP2pDeviceInfo2(WifiP2pDevice dev) { return Logger.fmt("%s [%s]", dev.deviceName, dev.deviceAddress); } private CharSequence getWifiP2pDeviceStatus(WifiP2pDevice dev) { switch (dev.status) { case WifiP2pDevice.CONNECTED: return getString(R.string.status_p2p_connected); case WifiP2pDevice.INVITED: return getString(R.string.status_p2p_invited); case WifiP2pDevice.FAILED: return getString(R.string.status_p2p_failed); case WifiP2pDevice.AVAILABLE: return getString(R.string.status_p2p_available); case WifiP2pDevice.UNAVAILABLE: default: return getString(R.string.status_p2p_unavailable); } } private ArrayAdapter<CharSequence> peers; private ArrayList<WifiP2pDevice> peerdevs; private TextView thisDevice; private ProgressDialog progressDialog; private EventHelper eventHelper; private WiFiP2PManager p2p; private final class CommandHelper implements OnClickListener { private final WiFiP2PCommand command; private final WiFiP2PManager ctx; private final CharSequence message; CommandHelper(WiFiP2PCommand cmd, WiFiP2PManager p2p, CharSequence msg) { ctx = p2p; command = cmd; message = msg; } void execute() { command.execute(ctx); if (message != null) showProgressDialog(message); } @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (which == DialogInterface.BUTTON_POSITIVE) execute(); } } private final class EventHelper extends BroadcastReceiver implements ServiceFactory.SpyCallback, ChannelListener, OnItemClickListener { @Override public void handleMessage(int type, int status, Object obj) { ActivityManageP2P.this.handleMessage(type, status, obj); } @Override public void onReceive(Context context, Intent intent) { ActivityManageP2P.this.handleBroadcast(intent); } @Override public void onChannelDisconnected() { ActivityManageP2P.this.onChannelDisconnected(); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ActivityManageP2P.this.handlePeerListClick(position); } } private final IntentFilter getWiFiP2PIntentFilter() { final IntentFilter ret = new IntentFilter(); ret.addAction(WIFI_P2P_STATE_CHANGED_ACTION); ret.addAction(WIFI_P2P_CONNECTION_CHANGED_ACTION); ret.addAction(WIFI_P2P_PEERS_CHANGED_ACTION); ret.addAction(WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); return ret; } }
Java
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import java.lang.Thread.UncaughtExceptionHandler; import android.app.Application; import android.content.res.XmlResourceParser; public final class ThisApplication extends Application implements UncaughtExceptionHandler { final static int PRIORITY_HIGH = android.os.Process.THREAD_PRIORITY_URGENT_AUDIO; final static int PRIORITY_NORMAL = android.os.Process.THREAD_PRIORITY_FOREGROUND; final static int PRIORITY_LOW = android.os.Process.THREAD_PRIORITY_DEFAULT; @Override public void uncaughtException(Thread thread, Throwable ex) { System.exit(0); } @Override public void onCreate() { super.onCreate(); //Thread.setDefaultUncaughtExceptionHandler(this); if (getCurrentThreadPriority() > PRIORITY_NORMAL) setCurrentThreadPriority(PRIORITY_NORMAL); instance = this; } static int getCurrentThreadPriority() { try { int tid = android.os.Process.myTid(); return android.os.Process.getThreadPriority(tid); } catch (Exception e) { return PRIORITY_LOW; } } static void setCurrentThreadPriority(int priority) { try { int tid = android.os.Process.myTid(); android.os.Process.setThreadPriority(tid, priority); } catch (Exception e) { } } static String name() { return getStringResource(R.string.app_name); } static String version() { try { return instance.getPackageManager().getPackageInfo( instance.getPackageName(), 0).versionName; } catch (Exception e) { return "1.0"; } } static int getColorResource(int resId) { return instance.getResources().getColor(resId); } static String getStringResource(int resId) { return instance.getString(resId); } static XmlResourceParser getXmlResource(int resId) { return instance.getResources().getXml(resId); } private static ThisApplication instance; }
Java
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import static com.sinpo.nfcspy.ServiceFactory.MSG_P2P_CONNECT; import static com.sinpo.nfcspy.ServiceFactory.MSG_P2P_DISCONN; import static com.sinpo.nfcspy.ServiceFactory.STA_FAIL; import static com.sinpo.nfcspy.ServiceFactory.STA_P2P_ACCEPT; import static com.sinpo.nfcspy.ServiceFactory.STA_P2P_CLIENT; import static com.sinpo.nfcspy.ServiceFactory.STA_SUCCESS; import static com.sinpo.nfcspy.ThisApplication.PRIORITY_HIGH; import static com.sinpo.nfcspy.ThisApplication.setCurrentThreadPriority; import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; final class WiFiP2PSocket extends Thread { static final int BUF_SIZE = 512; ServerSocket server; Socket client; private ServiceFactory.SpyCallback callback; private DataInputStream iStream; private DataOutputStream oStream; WiFiP2PSocket(ServiceFactory.SpyCallback callback) { this.callback = callback; } synchronized boolean isConnected() { if (client == null) return false; return (server != null) ? server.isBound() : client.isConnected(); } boolean sendData(int type, byte[] data) { if (data != null && data.length > 0 && oStream != null) { try { oStream.writeInt(type); oStream.writeInt(data.length); oStream.write(data); oStream.flush(); return true; } catch (Exception e) { return false; } } return false; } synchronized void close() { iStream = null; oStream = null; try { if (client != null && !client.isClosed()) client.close(); } catch (Throwable e) { } client = null; try { if (server != null && !server.isClosed()) server.close(); } catch (Throwable e) { } server = null; } @Override public void run() { synchronized (this) { notifyAll(); } setCurrentThreadPriority(PRIORITY_HIGH); try { iStream = new DataInputStream(client.getInputStream()); oStream = new DataOutputStream(new BufferedOutputStream( client.getOutputStream(), BUF_SIZE)); while (true) { int type = iStream.readInt(); int len = iStream.readInt(); byte[] data = new byte[len]; iStream.readFully(data); callback.handleMessage(type, STA_SUCCESS, data); } } catch (Exception e) { } finally { close(); callback.handleMessage(MSG_P2P_DISCONN, STA_SUCCESS, null); } } } final class SocketConnector extends Thread { private final ServiceFactory.SpyCallback callback; final WiFiP2PManager context; SocketConnector(WiFiP2PManager ctx, ServiceFactory.SpyCallback cb) { callback = cb; context = ctx; } @Override public void run() { final WiFiP2PManager ctx = context; ctx.closeSocket(); WiFiP2PSocket p2p = new WiFiP2PSocket(callback); ctx.p2pSocket = p2p; Socket client = null; ServerSocket server = null; try { if (ctx.isGroupOwner) { fireCallback(STA_P2P_ACCEPT); server = new ServerSocket(WiFiP2PManager.PORT); p2p.server = server; client = server.accept(); p2p.client = client; } else { fireCallback(STA_P2P_CLIENT); server = null; p2p.server = server; client = new Socket(); p2p.client = client; client.bind(null); client.connect(new InetSocketAddress(ctx.groupOwnerAddress, WiFiP2PManager.PORT), 8000); } } catch (Exception e) { safeClose(client); client = null; p2p.client = null; safeClose(server); p2p.server = null; ctx.p2pSocket = null; } if (client != null && client.isConnected()) { try { tuneupSocket(client); p2p.start(); synchronized (p2p) { p2p.wait(); } fireCallback(STA_SUCCESS); } catch (Exception e) { fireCallback(STA_FAIL); } } else { fireCallback(STA_FAIL); } } protected void fireCallback(int sta) { callback.handleMessage(MSG_P2P_CONNECT, sta, null); } private static void tuneupSocket(Socket skt) throws SocketException { skt.setTcpNoDelay(true); skt.setTrafficClass(0x04 | 0x10); if (skt.getSendBufferSize() < WiFiP2PSocket.BUF_SIZE) skt.setSendBufferSize(WiFiP2PSocket.BUF_SIZE); if (skt.getReceiveBufferSize() < WiFiP2PSocket.BUF_SIZE) skt.setReceiveBufferSize(WiFiP2PSocket.BUF_SIZE); } private static void safeClose(Closeable obj) { try { if (obj != null) obj.close(); } catch (Throwable e) { } } }
Java
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import static de.robv.android.xposed.XposedHelpers.findAndHookMethod; import static de.robv.android.xposed.XposedHelpers.findField; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam; public final class XposedModApduRouting implements IXposedHookLoadPackage { @Override public void handleLoadPackage(LoadPackageParam pkg) throws Throwable { if ("com.android.nfc".equals(pkg.packageName)) { final String CLASS = "com.android.nfc.cardemulation.HostEmulationManager"; final String METHOD = "findSelectAid"; try { findAndHookMethod(CLASS, pkg.classLoader, METHOD, byte[].class, findSelectAidHook); } catch (Exception e) { } } } private final static String AID_NFCSPY = "F04E4643535059"; private final XC_MethodHook findSelectAidHook = new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { final byte[] data = (byte[]) param.args[0]; final int len = data.length; if (data != null && len > 0) { try { final Object THIS = param.thisObject; // static final int STATE_W4_SELECT = 1; if (findField(THIS.getClass(), "mState").getInt(THIS) == 1) param.setResult(AID_NFCSPY); else // just bypass orgin call; param.setResult(null); } catch (Exception e) { } } } }; }
Java
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import java.util.ArrayList; import android.os.Build; import android.text.Spannable; import android.text.SpannableString; import android.text.TextUtils; import android.text.format.Time; import android.text.style.ForegroundColorSpan; final class Logger { static CharSequence fmtHeader(CharSequence notes) { final StringBuilder header = new StringBuilder(); final String CMT = "## "; final Time time = new Time(); time.setToNow(); header.append(CMT).append(ThisApplication.name()).append(" Log File v") .append(ThisApplication.version()).append('\n'); header.append(CMT).append("System: Android ") .append(Build.VERSION.RELEASE).append(", ").append(Build.BRAND) .append(' ').append(Build.MODEL).append('\n'); header.append(CMT).append("DateTime: ").append(fmtDate(time)) .append(' ').append(fmtTime(time)).append('\n'); header.append(CMT).append('\n'); if (!TextUtils.isEmpty(notes)) { String[] lines = notes.toString().split("\\n"); for (String line : lines) header.append(CMT).append(line).append('\n'); header.append(CMT).append('\n'); } header.append('\n'); return header; } static CharSequence fmtChatIn(CharSequence msg) { return fmt(R.color.sta_chat_in, fmt(">> %s %s", now(), msg)); } static CharSequence fmtChatOut(CharSequence msg) { return fmt(R.color.sta_chat_out, fmt("<< %s %s", now(), msg)); } static CharSequence fmtMsg(String fm, Object... args) { return fmt(R.color.sta_msg, fmt("!!!! %s %s", now(), fmt(fm, args))); } static CharSequence fmtInfo(String fm, Object... args) { return fmt(R.color.sta_info, fmt("## %s %s", now(), fmt(fm, args))); } static CharSequence fmtWarn(String fm, Object... args) { return fmt(R.color.sta_warn, fmt("!!!! %s %s", now(), fmt(fm, args))); } static CharSequence fmtError(String fm, Object... args) { return fmt(R.color.sta_error, fmt("!!!! %s %s", now(), fmt(fm, args))); } static CharSequence fmtApdu(int delay, boolean isCmd, byte[] apdu) { long stamp = System.currentTimeMillis(); return fmtApdu(currentCardId, stamp, delay, false, isCmd, apdu); } static CharSequence fmtApdu(String id, long stamp, long delay, boolean isHCE, boolean isCmd, byte[] raw) { final StringBuilder info = apduFormatter; info.setLength(0); final CharSequence hex, cmt; if (raw == null || raw.length == 0) { if (raw == ATTACH_MARKER) return fmtNfcAttachMessage(id, stamp); if (raw == DEACTIVE_MARKER) return fmtHceDeactivatedMessage(stamp); hex = "<NULL>"; cmt = "No Data"; } else { hex = toHexString(raw, 0, raw.length); cmt = ApduParser.parse(isCmd, raw); } final Time tm = new Time(); tm.set(stamp); info.append('[').append(isCmd ? 'C' : 'R').append(' '); info.append(id).append(']').append(' '); info.append(fmtTime(tm)).append(' ').append(hex).append(' '); info.append(cmt).append(' ').append(isHCE ? '+' : '~'); if (delay < 0 || delay > MAX_APDUDELAY_MS) info.append('?'); else info.append(delay); info.append('m').append('s'); return fmt(isCmd ? R.color.sta_apdu_in : R.color.sta_apdu_out, info); } static CharSequence fmtNfcAttachMessage(String cardId, long stamp) { Time time = new Time(); time.set(stamp); return fmt( R.color.sta_msg, fmt(ThisApplication .getStringResource(R.string.event_nfc_attach), fmtTime(time), cardId, fmtDate(time))); } static CharSequence fmtHceDeactivatedMessage(long stamp) { Time time = new Time(); time.set(stamp); return fmt( ThisApplication.getStringResource(R.string.status_deactivated), fmtTime(time), fmtDate(time)); } static CharSequence fmt(int colorResId, CharSequence msg) { final int color = ThisApplication.getColorResource(colorResId); final SpannableString ret = new SpannableString(msg); final ForegroundColorSpan span = new ForegroundColorSpan(color); ret.setSpan(span, 0, msg.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); return ret; } static CharSequence fmt(String fm, Object... args) { return String.format(fm, args); } static String now() { Time time = new Time(); time.setToNow(); return fmtTime(time); } static String fmtDate(Time tm) { return String.format("%04d-%02d-%02d", tm.year, tm.month + 1, tm.monthDay); } static String fmtTime(Time tm) { return String.format("%02d:%02d:%02d", tm.hour, tm.minute, tm.second); } static String toHexString(byte[] d, int s, int n) { final char[] ret = new char[n * 2]; final int e = s + n; int x = 0; for (int i = s; i < e; ++i) { final byte v = d[i]; ret[x++] = HEX[0x0F & (v >> 4)]; ret[x++] = HEX[0x0F & v]; } return new String(ret); } private final static byte[] ATTACH_MARKER = new byte[0]; private final static byte[] DEACTIVE_MARKER = new byte[0]; private final static char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; static void logNfcAttach(String cardId) { currentCardId = cardId; logApdu(System.currentTimeMillis(), true, true, ATTACH_MARKER); } static void logHceDeactive() { logApdu(System.currentTimeMillis(), true, true, DEACTIVE_MARKER); } static long logApdu(long stamp, boolean isHCE, boolean isCmd, byte[] apdu) { ApduItem it = new ApduItem(currentCardId, stamp, isHCE, isCmd, apdu); if (isFull()) apduLogs.set(cursor, it); else apduLogs.add(it); if (++cursor == MAX_LOGS) cursor = 0; return it.delay; } static void clearCachedLogs() { apduLogs.clear(); cursor = 0; } static int getCachedLogsCount() { return apduLogs.size(); } static CharSequence getCachedLog(int index) { if (isFull()) index = (index + cursor - 1) % MAX_LOGS; ApduItem i = apduLogs.get(index); return fmtApdu(i.cardId, i.timestamp, i.delay, i.isHCE, i.isCmd, i.apdu); } static String getCurrentLogFileName() { Time t = new Time(); t.setToNow(); return String.format("nfcspy_%04d%02d%02d_%02d%02d%02d.log", t.year, t.month + 1, t.monthDay, t.hour, t.minute, t.second); } static void setCurrentCardId(String id) { currentCardId = id; } static void open() { ApduParser.init(); } private static boolean isFull() { return apduLogs.size() == MAX_LOGS; } private static final long MAX_APDUDELAY_MS = 1999; private static final int MAX_LOGS = 512; private static int cursor = 0; private static String currentCardId = ""; private static final StringBuilder apduFormatter = new StringBuilder(); private static final ArrayList<ApduItem> apduLogs = new ArrayList<ApduItem>( MAX_LOGS); private static final class ApduItem { private static long lastApduStamp = 0; ApduItem(String id, long stamp, boolean isHCE, boolean isCmd, byte[] raw) { this.cardId = id; this.isHCE = isHCE; this.isCmd = isCmd; this.apdu = raw; this.timestamp = stamp; this.delay = stamp - lastApduStamp; lastApduStamp = stamp; } final byte[] apdu; final String cardId; final boolean isHCE; final boolean isCmd; final long timestamp; final long delay; } }
Java
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import android.content.res.XmlResourceParser; final class ApduParser { static String parse(boolean isCmd, byte[] apdu) { if (isCmd) { return CMDS.search(0, apdu).name(); } else { final int len = apdu.length; if (len > 1) return SWS.search(0, apdu[len - 2], apdu[len - 1]).name(); } return ""; } static void init() { if (CMDS != null && SWS != null) return; final XmlResourceParser xml = ThisApplication .getXmlResource(R.xml.apdu7816); try { // START__DOCUMENT xml.next(); if (xml.next() == START_TAG && "apdu".equalsIgnoreCase(xml.getName())) { while (xml.next() != END_DOCUMENT) { Apdu7816 cmds = readTag(Apdu7816.CMDS.class, xml); if (cmds != null) { CMDS = cmds; continue; } Apdu7816 sws = readTag(Apdu7816.SWS.class, xml); if (sws != null) { SWS = sws; continue; } break; } } } catch (Exception e) { } finally { if (xml != null) xml.close(); } if (CMDS == null) CMDS = new Apdu7816.CMDS(); if (SWS == null) SWS = new Apdu7816.SWS(); } @SuppressWarnings("unchecked") static Apdu7816 readTag(Class<? extends Apdu7816> clazz, XmlResourceParser xml) throws Exception { if (xml.getEventType() != START_TAG) return null; final String thisTag = xml.getName(); final String testTag = (String) clazz.getDeclaredField("TAG").get(null); if (!thisTag.equalsIgnoreCase(testTag)) return null; final String apduName = xml.getAttributeValue(null, "name"); final String apduVal = xml.getAttributeValue(null, "val"); final ArrayList<Apdu7816> list = new ArrayList<Apdu7816>(); final Object child = clazz.getDeclaredField("SUB").get(null); while (true) { int event = xml.next(); if (event == END_DOCUMENT) break; if (event == END_TAG && thisTag.equalsIgnoreCase(xml.getName())) break; if (child != null) { Apdu7816 apdu = readTag((Class<? extends Apdu7816>) child, xml); if (apdu != null) list.add(apdu); } } final Apdu7816[] sub; if (list.isEmpty()) sub = null; else sub = list.toArray(new Apdu7816[list.size()]); final Apdu7816 ret = clazz.newInstance(); ret.init(parseValue(apduVal), apduName, sub); return ret; } private static byte parseValue(String strVal) { if (strVal != null && strVal.length() > 0) { try { return (byte) (Integer.parseInt(strVal, 16) & 0xFF); } catch (Exception e) { } } return (byte) 0; } private static Apdu7816 CMDS; private static Apdu7816 SWS; @SuppressWarnings("unused") private static class Apdu7816 implements Comparator<Apdu7816> { final static class CMDS extends Apdu7816 { final static String TAG = "cmds"; final static Object SUB = CLS.class; } final static class SWS extends Apdu7816 { final static String TAG = "sws"; final static Object SUB = SW1.class; } final static class CLS extends Apdu7816 { final static String TAG = "class"; final static Object SUB = INS.class; int compare(Apdu7816 apdu) { if (apdu.getClass() != CLS.class) { final byte val = this.val; final byte oth = apdu.val; if (val == 0) { // class 0XXX XXXXb if ((oth | 0x7F) == 0x7F) return 0; } else if (val == 1) { // class 1XXX XXXXb if ((oth & 0x80) == 0x80) return 0; } else { // class as val if (val == oth) return 0; } } return super.compare(apdu); } } final static class INS extends Apdu7816 { final static String TAG = "ins"; final static Object SUB = P1.class; } final static class P1 extends Apdu7816 { final static String TAG = "p1"; final static Object SUB = P2.class; } final static class P2 extends Apdu7816 { final static String TAG = "p2"; final static Object SUB = null; } final static class SW1 extends Apdu7816 { final static String TAG = "sw1"; final static Object SUB = SW2.class; } final static class SW2 extends Apdu7816 { final static String TAG = "sw2"; final static Object SUB = null; } int compare(Apdu7816 apdu) { return (this.val & 0xFF) - (apdu.val & 0xFF); } String name() { return name == null ? "" : name; } Apdu7816 search(int start, byte... val) { final Apdu7816[] sub = this.sub; if (sub != null && start < val.length) { Apdu7816 cp = comparator; cp.val = val[start]; int i = Arrays.binarySearch(sub, cp, cp); if (i >= 0) return sub[i].search(++start, val); } return this; } @Override public int compare(Apdu7816 lhs, Apdu7816 rhs) { return lhs.compare(rhs); } void init(byte val, String name, Apdu7816[] sub) { this.val = val; this.name = name; this.sub = sub; if (sub != null) Arrays.sort(sub, comparator); } protected Apdu7816[] sub; protected byte val; protected String name; protected static Apdu7816 comparator = new Apdu7816(); } }
Java
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import static com.sinpo.nfcspy.ServiceFactory.ERR_APDU_CMD; import static com.sinpo.nfcspy.ServiceFactory.ERR_APDU_RSP; import static com.sinpo.nfcspy.ServiceFactory.MSG_CHAT_RECV; import static com.sinpo.nfcspy.ServiceFactory.MSG_CHAT_SEND; import static com.sinpo.nfcspy.ServiceFactory.MSG_HCE_APDU_CMD; import static com.sinpo.nfcspy.ServiceFactory.MSG_HCE_APDU_RSP; import static com.sinpo.nfcspy.ServiceFactory.MSG_HCE_ATTACH; import static com.sinpo.nfcspy.ServiceFactory.MSG_HCE_DEACTIVATED; import static com.sinpo.nfcspy.ServiceFactory.MSG_HCE_DETTACH; import static com.sinpo.nfcspy.ServiceFactory.MSG_P2P_CONNECT; import static com.sinpo.nfcspy.ServiceFactory.MSG_P2P_DISCONN; import static com.sinpo.nfcspy.ServiceFactory.MSG_P2P_INIT; import static com.sinpo.nfcspy.ServiceFactory.MSG_P2P_SOCKET; import static com.sinpo.nfcspy.ServiceFactory.MSG_SERVER_VER; import static com.sinpo.nfcspy.ServiceFactory.STA_ERROR; import static com.sinpo.nfcspy.ServiceFactory.STA_FAIL; import static com.sinpo.nfcspy.ServiceFactory.STA_NOTCARE; import static com.sinpo.nfcspy.ServiceFactory.STA_P2P_ACCEPT; import static com.sinpo.nfcspy.ServiceFactory.STA_P2P_CLIENT; import static com.sinpo.nfcspy.ServiceFactory.STA_SUCCESS; import java.io.File; import java.io.FileOutputStream; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.Messenger; import android.text.ClipboardManager; import android.text.Html; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class ActivityMain extends ActivityBase implements Handler.Callback { public ActivityMain() { inbox = new Messenger(new Handler(this)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); messages = new ArrayAdapter<CharSequence>(this, R.layout.listitem_message); ((ListView) findViewById(R.id.list)).setAdapter(messages); messageView = (TextView) findViewById(R.id.txtChatLine); nfc = new NfcManager(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_copy: copyLogs(); return true; case R.id.action_save: saveLogs(); return true; case R.id.action_share: shareLogs(); return true; case R.id.action_settings: startActivity(new Intent(this, ActivityManageP2P.class)); return true; case R.id.action_viewlogs: showHCELogs(); return true; case R.id.action_clearlogs: clearHCELogs(); return true; case R.id.action_about: showHelp(); return true; default: return super.onOptionsItemSelected(item); } } public void startServer(View ignore) { if (!nfc.isEnabled()) { messages.add(Logger.fmtError(getString(R.string.status_no_nfc))); return; } if (!WiFiP2PManager.isWiFiEnabled(this)) { messages.add(Logger.fmtError(getString(R.string.status_no_wifi))); return; } if (!NfcManager.hasHCE()) messages.add(Logger.fmtWarn(getString(R.string.status_no_hce))); ServiceFactory.startServer(this, inbox); } public void stopServer(View ignore) { ServiceFactory.stopServer(this); } public void clearList(View ignore) { messages.clear(); } public void enableHighSpeed(View v) { ServiceFactory.setHighSpeed2Server(this, ((CheckBox) v).isChecked()); } public void sendChatMessage(View ignore) { final String msg = messageView.getText().toString(); if (!TextUtils.isEmpty(msg)) ServiceFactory.sendChatMessage2Server(this, msg); } @Override protected void onResume() { super.onResume(); nfc.onResume(); } @Override protected void onPause() { nfc.onPause(); super.onPause(); } @Override protected void onDestroy() { nfc = null; super.onDestroy(); } @Override protected void onNewIntent(Intent intent) { ServiceFactory.setTag2Server(this, intent); } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case MSG_HCE_APDU_CMD: case MSG_HCE_APDU_RSP: printHceApdu(msg); break; case MSG_HCE_ATTACH: printNfcAttachMessage(msg); break; case MSG_HCE_DEACTIVATED: printHceDeactivatedMessage(); break; case MSG_HCE_DETTACH: printStatusMessage(R.string.event_nfc_lost, STA_ERROR, 0); break; case MSG_CHAT_SEND: case MSG_CHAT_RECV: printChatMessage(msg); break; case MSG_P2P_SOCKET: printStatusMessage(R.string.status_getaddr, msg.arg1, msg.arg2); break; case MSG_P2P_CONNECT: printStatusMessage(R.string.status_connect, msg.arg1, msg.arg2); break; case MSG_P2P_DISCONN: printStatusMessage(R.string.status_disconn, msg.arg1, msg.arg2); break; case MSG_P2P_INIT: printStatusMessage(R.string.status_init, msg.arg1, msg.arg2); break; case MSG_SERVER_VER: printVersionInfo(msg); break; default: return false; } return true; } private void printStatusMessage(int descId, int status, int error) { final CharSequence desc; if (status == STA_NOTCARE) { desc = Logger.fmtInfo(getString(descId)); } else if (status == STA_SUCCESS) { String sta = getString(R.string.status_success); desc = Logger.fmtInfo("%s%s", getString(descId), sta); } else if (status == STA_FAIL) { String sta = getString(R.string.status_failure); desc = Logger.fmtError("%s%s", getString(descId), sta); } else if (status == STA_ERROR) { desc = Logger.fmtError(getString(descId)); } else { if (status == STA_P2P_ACCEPT) descId = R.string.status_p2p_accept; else if (status == STA_P2P_CLIENT) descId = R.string.status_p2p_client; String sta = getString(R.string.status_waitting); desc = Logger.fmtWarn("%s %s", getString(descId), sta); } messages.add(desc); } private void printChatMessage(Message msg) { byte[] raw = ServiceFactory.extractDataFromMessage(msg); if (raw != null && raw.length > 0) { String txt = new String(raw); if (MSG_CHAT_SEND == msg.what) { messages.add(Logger.fmtChatOut(txt)); messageView.setText(null); } else { messages.add(Logger.fmtChatIn(txt)); } } } private void printVersionInfo(Message msg) { byte[] raw = ServiceFactory.extractDataFromMessage(msg); if (raw != null && raw.length > 0) { String peer = new String(raw); String me = ThisApplication.version(); if (me.equals(peer)) { String fmt = getString(R.string.event_p2p_version); messages.add(Logger.fmtInfo(fmt, me)); } else { String fmt = getString(R.string.event_p2p_version2); messages.add(Logger.fmtWarn(fmt, peer, me)); } } } private void printNfcAttachMessage(Message msg) { byte[] raw = ServiceFactory.extractDataFromMessage(msg); if (raw != null && raw.length > 0) { long stamp = System.currentTimeMillis(); messages.add(Logger.fmtNfcAttachMessage(new String(raw), stamp)); } } private void printHceDeactivatedMessage() { long stamp = System.currentTimeMillis(); messages.add(Logger.fmtHceDeactivatedMessage(stamp)); } private void printHceApdu(Message msg) { byte[] apdu = ServiceFactory.extractDataFromMessage(msg); if (apdu != null && apdu.length > 0) { boolean isCmd = (MSG_HCE_APDU_CMD == msg.what); messages.add(Logger.fmtApdu(msg.arg2, isCmd, apdu)); } else { String hint; if (STA_ERROR == msg.arg1) { if (ERR_APDU_CMD == msg.arg2) hint = getString(R.string.event_p2p_connect); else if (ERR_APDU_RSP == msg.arg2) hint = getString(R.string.event_nfc_rsp); else hint = getString(R.string.event_p2p_connect); } else { hint = getString(R.string.event_nfc_lost); } messages.add(Logger.fmtError(hint)); } } private void shareLogs() { CharSequence logs = getAllLogs(); if (!TextUtils.isEmpty(logs)) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_TEXT, logs); intent.setType("text/plain"); startActivity(intent); } } private void copyLogs() { CharSequence logs = getAllLogs(); if (!TextUtils.isEmpty(logs)) { ((ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE)) .setText(logs); Toast.makeText(this, R.string.event_log_copy, Toast.LENGTH_LONG) .show(); } } private void showHCELogs() { int n = Logger.getCachedLogsCount(); for (int i = 0; i < n; ++i) messages.add(Logger.getCachedLog(i)); } private void clearHCELogs() { Logger.clearCachedLogs(); } private void showHelp() { CharSequence title = Logger.fmt("%s v%s", ThisApplication.name(), ThisApplication.version()); CharSequence info = Html.fromHtml(getString(R.string.info_about)); TextView tv = (TextView) getLayoutInflater().inflate( R.layout.dialog_message, null); tv.setLinksClickable(true); tv.setMovementMethod(LinkMovementMethod.getInstance()); tv.setText(info); new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT) .setTitle(title).setView(tv) .setNeutralButton(R.string.action_ok, null).show(); } private void saveLogs() { CharSequence logs = getAllLogs(); if (!TextUtils.isEmpty(logs)) { View root = getLayoutInflater().inflate(R.layout.dialog_savelog, null); EditText name = (EditText) root.findViewById(R.id.file); name.setText(Logger.getCurrentLogFileName()); EditText note = (EditText) root.findViewById(R.id.note); SaveLogHelper helper = new SaveLogHelper(logs, name, note); new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT) .setTitle(R.string.action_save).setView(root) .setNegativeButton(R.string.action_cancel, helper) .setPositiveButton(R.string.action_ok, helper).show(); } } private CharSequence getAllLogs() { StringBuilder ret = new StringBuilder(); final ArrayAdapter<CharSequence> messages = this.messages; final int count = messages.getCount(); for (int i = 0; i < count; ++i) { if (i > 0) ret.append("\n\n"); ret.append(messages.getItem(i)); } return ret; } private static final class SaveLogHelper implements DialogInterface.OnClickListener { CharSequence logs; EditText nameView, noteView; SaveLogHelper(CharSequence logs, EditText name, EditText note) { this.logs = logs; this.nameView = name; this.noteView = note; } @Override public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) saveLogs(); dialog.dismiss(); nameView = null; noteView = null; logs = null; } private void saveLogs() { String file = nameView.getText().toString(); if (TextUtils.isEmpty(file)) return; Context ctx = nameView.getContext(); String msg; try { File root = Environment.getExternalStorageDirectory(); File path = new File(root, "/nfcspy/logs"); File logf = new File(path, file); file = logf.getAbsolutePath(); path.mkdirs(); FileOutputStream os = new FileOutputStream(file); CharSequence note = Logger.fmtHeader(noteView.getText()); if (!TextUtils.isEmpty(note)) os.write(note.toString().getBytes()); os.write(logs.toString().getBytes()); os.close(); msg = ctx.getString(R.string.event_log_save); } catch (Exception e) { msg = ctx.getString(R.string.event_log_notsave); } Toast.makeText(ctx, Logger.fmt(msg, file), Toast.LENGTH_LONG) .show(); } } private NfcManager nfc; private Messenger inbox; private ArrayAdapter<CharSequence> messages; private TextView messageView; }
Java
/* NFC Spy is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Spy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.nfcspy; import static android.content.Context.WIFI_P2P_SERVICE; import static com.sinpo.nfcspy.ServiceFactory.STA_P2P_INITED; import static com.sinpo.nfcspy.ServiceFactory.STA_P2P_UNINIT; import java.net.InetAddress; import android.content.Context; import android.net.wifi.WifiManager; import android.net.wifi.p2p.WifiP2pManager; import android.net.wifi.p2p.WifiP2pManager.Channel; import android.net.wifi.p2p.WifiP2pManager.ChannelListener; final class WiFiP2PManager { // TODO maybe choooooose by setting panel final static int PORT = 2013; static boolean isWiFiEnabled(Context ctx) { return ((WifiManager) ctx.getSystemService(Context.WIFI_SERVICE)) .isWifiEnabled(); } WiFiP2PManager() { reset(); } void init(Context ctx, ChannelListener lsn) { wifip2p = (WifiP2pManager) ctx.getSystemService(WIFI_P2P_SERVICE); channel = wifip2p.initialize(ctx, ctx.getMainLooper(), lsn); if (wifip2p != null && channel != null) { isWifiP2pEnabled = true; status = STA_P2P_INITED; } else { isWifiP2pEnabled = false; status = STA_P2P_UNINIT; } } boolean isInited() { return status != STA_P2P_UNINIT; } boolean isConnected() { return (p2pSocket != null) && p2pSocket.isConnected(); } boolean sendData(int type, byte[] data) { return isConnected() ? p2pSocket.sendData(type, data) : false; } void closeSocket() { if (p2pSocket != null) { p2pSocket.close(); p2pSocket = null; } } void reset() { closeSocket(); peerName = null; groupOwnerAddress = null; isGroupOwner = false; isWifiP2pConnected = false; channel = null; status = STA_P2P_UNINIT; } String peerName; InetAddress groupOwnerAddress; boolean isGroupOwner; boolean isWifiP2pConnected; boolean isWifiP2pEnabled; WiFiP2PSocket p2pSocket = null; private int status; WifiP2pManager wifip2p; Channel channel; }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package componentes; import java.io.Serializable; import java.util.*; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; /** * * @author acazares * consulta [scope]: http://anadreamy.wordpress.com/2011/10/25/jsf-2-0-managed-beans-iii/ * consulta [efectos]: http://icefaces-showcase.icesoft.org/showcase.jsf?grp=aceMenu&exp=autoCompleteEntryBean */ @ManagedBean @ViewScoped public class Sistema implements Serializable{ private static final long serialVersionUID = 1L; private String year;// ="2012"; /** * Creates a new instance of Sistema */ public Sistema() throws Exception { Calendar toDay = Calendar.getInstance(); year = toDay.get(Calendar.YEAR)+""; } public String getYear(){ return year; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package componentes; import DTO.Usuario; import com.google.gson.Gson; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.model.SelectItem; import javax.faces.validator.ValidatorException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import tipos.UsuarioStatus; import tipos.UsuarioTipo; import utilidades.Hash; /** * * @author acazares * http://www.primefaces.org/ * http://www.roseindia.net/jsf/validator.shtml * http://jqueryui.com/themeroller/#themeGallery */ @ManagedBean @RequestScoped public class UsuariosBean { private static final long serialVersionUID = 1L; private DAO.UsuarioDAO usuarioDao; //@Size(min=3, max=32) //@NotNull private String username; private String msgUsername; //@Size(min=4, max=32) //@NotNull private String pass1; private String msgPass1; //@NotNull private String pass2; private String msgPass2; //@Size(min=3, max=32) //@NotNull private String nombre; private String msgNombre; private tipos.UsuarioTipo tipo; private SelectItem[] usuariosTipo = new SelectItem[]{ new SelectItem( tipos.UsuarioTipo.usuario, tipos.UsuarioTipo.usuario.toString() ), new SelectItem( tipos.UsuarioTipo.equipo, tipos.UsuarioTipo.equipo.toString() )/*, new SelectItem( tipos.UsuarioTipo.administrador, tipos.UsuarioTipo.administrador.toString() )*/ }; public UsuariosBean() { usuarioDao = new DAO.UsuarioDAO(); } public SelectItem[] getUsuariosStatus() { return usuariosTipo; } public String guardarUsuario(){ System.out.println("Iniciando validacion de elementos"); boolean validacion = nombreValido() & usuarioValido() & passValido(); System.out.println("Resultado: "+validacion); if(!validacion){ return "nuevoUsuario"; } Usuario usr = new Usuario(); usr.setNombre(nombre); usr.setUser(username); usr.setPass( utilidades.Hash.md5(pass1) ); usr.setStatus(UsuarioStatus.nuevo); usr.setTipo(tipo); usr.setCreacion(new Date()); usr.setUltimoAcceso(new Date()); try{ usuarioDao.guardar(usr); System.out.println("usuario id: "+usr.getId() ); login(usr); }catch(Exception e){ System.out.println( "Se presento un problema: "+e ); }finally{ return "index"; } } public void login(Usuario usr){ FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest)context. getExternalContext().getRequest(); HttpSession httpSession = request.getSession(false); System.out.println("usuario: "+usr.getNombre()); if(usr.isValid()){ httpSession.setAttribute("usuario", usr); System.out.println("Se ha establecido login"); }else{ System.out.println("No se completo login, usuario no valido"); } } public void logout(){ FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest)context. getExternalContext().getRequest(); HttpSession httpSession = request.getSession(false); httpSession.invalidate(); System.out.println("logout"); } /* public String actionLogout(){ logout(); Gson gson = new Gson(); return gson.toJson( new Usuario() ); } public String actionLogin(String user, String pass){ Gson gson = new Gson(); Usuario usuario = usuarioDao.getUsuarioByUserPass(user, Hash.md5(pass)); System.out.println("Preparando login: "+user+","+pass); login(usuario); System.out.println("Finalizando login: "+gson.toJson( usuario )); return gson.toJson( usuario ); } */ public boolean nombreValido(){ if(nombre == null || nombre.length() == 0){ msgNombre = "Campo requerido"; return false; } if(nombre.length() <3){ msgNombre = "Al menos debe contener 3 caracteres"; return false; } if(nombre.length() >32){ msgNombre = "Máximo 32 caracteres"; return false; } return true; } public boolean usuarioValido(){ if(username == null || username.length() == 0){ msgUsername = "Campo requerido"; return false; } String regex = "^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(username); if( !matcher.matches() ){ msgUsername = "formato de correo electrónico no válido"; return false; } if( usuarioDao.countByUsername(username) >0 ){ msgUsername ="Alguien mas ya ha usado ["+username +"] como nombre de usuario"; return false; } return true; } public boolean passValido(){ if(pass2 == null || pass2.length() == 0){ msgPass2 = "Campo requerido"; } if(pass1 == null || pass1.length() == 0){ msgPass1 = "Campo requerido"; return false; } String regex = ""; regex += "^(?=.*[A-Z]).{6,}$|^(?=.*[.]).{6,}$";//M6,e6, regex += "|^(?=.*[0-9]).{7,}$|^(?=.*[a-z]).{12,}$";//n7,m12 regex += "|^(?=.*[0-9])(?=.*[A-Z]).{4,}$";//nM4 regex += "|^(?=.*[.])(?=.*[A-Z]).{4,}$";//eM4 regex += "|^(?=.*[.])(?=.*[0-9]).{4,}$";//en4 regex += "|^(?=.*[.])(?=.*[a-z]).{5,}$";//en5 regex += "|^(?=.*[A-Z])(?=.*[a-z]).{6,}$";//Mm6 regex += "|^(?=.*[0-9])(?=.*[a-z]).{7,}$";//nm7 regex += "|^(?=.*[.])(?=.*[a-z])(?=.*[A-Z]).{4,}$";//emM4// regex += "|^(?=.*[.])(?=.*[a-z])(?=.*[0-9]).{4,}$";//emn4// regex += "|^(?=.*[.])(?=.*[A-Z])(?=.*[0-9]).{3,}$";//enM3// regex += "|^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{4,}$";//mMn// regex += "|^(?=.*[.])(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{4,}$";//emMn4// Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(pass1); if( !matcher.matches() ){ //if( !matcher.matches() ){ msgPass1 = "El password no es seguro"; msgPass2 = "Utilice numeros, letras minusculas, letras mayusculas y opcionalmente caracteres especiales."; return false; } if(!pass1.equals(pass2)){ msgPass1 = "Falló la confirmación del password"; return false; } return true; } /////////////////////////////////////////////////////////////////////// public String getMsgUsername() { return msgUsername; } public String getMsgPass1() { return msgPass1; } public String getMsgPass2() { return msgPass2; } public String getMsgNombre() { return msgNombre; } /////////////////////////////////////////////////////////////////////// public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPass1() { return pass1; } public void setPass1(String pass) { this.pass1 = pass; } public String getPass2() { return pass1; } public void setPass2(String pass) { this.pass2 = pass; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public UsuarioTipo getTipo() { return tipo; } public void setTipo(UsuarioTipo tipo) { this.tipo = tipo; } public SelectItem[] getTipos(){ return usuariosTipo; } }
Java
package componentes; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.faces.model.SelectItem; import componentes.Car;//<---------------- public class TableBean implements Serializable { private final static String[] colors; private final static String[] manufacturers; static { colors = new String[10]; colors[0] = "Black"; colors[1] = "White"; colors[2] = "Green"; colors[3] = "Red"; colors[4] = "Blue"; colors[5] = "Orange"; colors[6] = "Silver"; colors[7] = "Yellow"; colors[8] = "Brown"; colors[9] = "Maroon"; manufacturers = new String[10]; manufacturers[0] = "Mercedes"; manufacturers[1] = "BMW"; manufacturers[2] = "Volvo"; manufacturers[3] = "Audi"; manufacturers[4] = "Renault"; manufacturers[5] = "Opel"; manufacturers[6] = "Volkswagen"; manufacturers[7] = "Chrysler"; manufacturers[8] = "Ferrari"; manufacturers[9] = "Ford"; } private SelectItem[] manufacturerOptions; private List<Car> filteredCars; private List<Car> carsSmall; public TableBean() { carsSmall = new ArrayList<Car>(); populateRandomCars(carsSmall, 9); manufacturerOptions = createFilterOptions(manufacturers); } private void populateRandomCars(List<Car> list, int size) { for(int i = 0 ; i < size ; i++) list.add(new Car(getRandomModel(), getRandomYear(), getRandomManufacturer(), getRandomColor())); } public List<Car> getFilteredCars() { return filteredCars; } public void setFilteredCars(List<Car> filteredCars) { this.filteredCars = filteredCars; } public List<Car> getCarsSmall() { return carsSmall; } private int getRandomYear() { return (int) (Math.random() * 50 + 1960); } private String getRandomColor() { return colors[(int) (Math.random() * 10)]; } private String getRandomManufacturer() { return manufacturers[(int) (Math.random() * 10)]; } private String getRandomModel() { return UUID.randomUUID().toString().substring(0, 8); } private SelectItem[] createFilterOptions(String[] data) { SelectItem[] options = new SelectItem[data.length + 1]; options[0] = new SelectItem("", "Select"); for(int i = 0; i < data.length; i++) { options[i + 1] = new SelectItem(data[i], data[i]); } return options; } public SelectItem[] getManufacturerOptions() { return manufacturerOptions; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package componentes; import DTO.Usuario; import com.google.gson.Gson;//http://blog.pontt.com/json-con-java/introduccion-java-y-json-primera-parte-con-ejemplo/ import java.io.IOException; import java.io.PrintWriter; import java.util.*; import javax.faces.application.Application; import javax.faces.context.FacesContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.sound.midi.Soundbank; import tipos.UsuarioStatus; import tipos.UsuarioTipo; import utilidades.Hash; /** * * @author acazares */ @WebServlet(name = "requestController", urlPatterns = {"/requestController.jsf"}) public class RequestController extends HttpServlet { private Gson gson; /** * Processes requests for both HTTP * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //response.setContentType("text/html;charset=UTF-8"); response.setContentType("text/plain;charset=UTF-8"); gson = new Gson(); PrintWriter out = response.getWriter(); try { String opcion = request.getParameter("action"); if( opcion != null ){ if(opcion.equals("login")){ out.print( login(request) ); } if(opcion.equals("logout")) { logout(request); //out.print("ya"); } } } finally { out.close(); } } private String login(HttpServletRequest request){ try{ String user = request.getParameter("user"); String pass = request.getParameter("pass"); if(user!=null && pass!=null && user.length()>0 && pass.length()>0){ HttpSession sesionActual = request.getSession(); DAO.UsuarioDAO dao = new DAO.UsuarioDAO(); Usuario usuario = dao.getUsuarioByUserPass(user, Hash.md5(pass)); if(usuario.isValid()){ sesionActual.setAttribute("usuario", usuario ); dao.updateLastLogin(usuario); System.out.println("login starting: "+usuario.getId()); } return gson.toJson( usuario ); } return gson.toJson( new Usuario() ); }catch(Exception e){ return "error: "+e; } } private void logout(HttpServletRequest request){ // consulta [invalidate]: http://manglar.uninorte.edu.co/bitstream/10584/2206/1/Frameworks%20de%20desarrollo%20sobre%20p%C3%A1ginas%20JSP.pdf HttpSession sesionActual = request.getSession(); sesionActual.invalidate(); System.out.println("logout"); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package componentes; /** * * @author acazares */ import java.util.Date; public class Car { private String model; private int year; private String manufacturer; private String color; public Car(String model, int year, String manufacturer, String color) { this.model = model; this.year = year; this.manufacturer = manufacturer; this.color = color; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public String getManufacturer() { return manufacturer; } public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package componentes; import DTO.Concurso; import DTO.Usuario; import com.sun.xml.registry.uddi.infomodel.ConceptImpl; import java.util.Date; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; import javax.faces.model.SelectItem; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import tipos.ConcursoStatus; import tipos.ConcursoTipo; import tipos.UsuarioStatus; /** * * @author acazares */ @ManagedBean @RequestScoped public class ConcursosBean { private DTO.Concurso concurso; private DAO.ConcursoDAO dao; private HttpServletRequest request; private FacesContext context; private HttpSession httpSession; private boolean esNuevo = false; private String vista; public ConcursosBean() { try{ dao = new DAO.ConcursoDAO(); context = FacesContext.getCurrentInstance(); request = (HttpServletRequest) FacesContext.getCurrentInstance(). getExternalContext().getRequest(); httpSession = request.getSession(false); String id = request.getParameter("id"); vista = (String)request.getParameter("vista"); if(id!=null && id.length()>0){ //DAO.UtilDao dao1 = new DAO.UtilDao( tipos.ComponentesNombre.Concurso ); //System.out.println("Solicitando datos..."); //concurso = (Concurso)dao1.getById(id); concurso = dao.getConcursoById(id); System.out.println("Salida: "); System.out.println(concurso.toString()); concurso.setId(id); esNuevo = false; }else{ concurso = new DTO.Concurso(); esNuevo = true; } }catch(Exception e){ System.out.println("Error: "+e); } } public void setVista(String vista){ this.vista = vista; } public String getVista(){ if(vista!=null && vista.equals("crear")){ System.out.println("Set vista"); return this.vista="elementos/concursos/nuevo.xhtml"; } /* * else{ System.out.println("Nada???"+vista); //this.vista=vista; return this.vista="elementos/concursos/nuevo1.xhtml"; } //return vista;*/ return this.vista="elementos/concursos/default.xhtml"; } /* public String getVistaLL(){ if(vista!=null && vista.equals("crear")){ System.out.println("Ingresando"); return "elementos/concursos/nuevo.xhtml"; }else{ System.out.println("Nada???"); } /* if(vista!=null){ if(vista.equals("crear")) return "elementos/concursos/nuevo.xhtml"; } return "elementos/concursos/usuarios.xhtml"; //return "elementos/concursos/nuevo.xhtml"; }*/ public boolean getEsNuevo(){ return esNuevo; //return true; } public String guardar(){ try{ DTO.Concurso concurso = dao.getConcursoById(this.concurso.getId()); System.out.println("Formulario: "+this.concurso.getNombre() + "Objeto: "+concurso.getNombre()); //falta validar los datos if(concurso.getId()==null){ System.out.println("Guardando datos"); dao = new DAO.ConcursoDAO(); this.concurso.setTipoInscripcion(ConcursoTipo.publico); this.concurso.setStatus(ConcursoStatus.nuevo); DTO.Usuario usr = (DTO.Usuario)httpSession.getAttribute("usuario"); this.concurso.setAutor(usr); System.out.println("objeto construido, administrado por "+usr.getNombre()); dao.guardar(this.concurso); System.out.println("Datos almacenados"); return "index"; }else{ //falta validar los datos concurso.setConvocatoria(this.concurso.getConvocatoria()); concurso.setFinaliza(this.concurso.getFinaliza()); concurso.setInicia(this.concurso.getInicia()); concurso.setNombre(this.concurso.getNombre()); concurso.setPublicidadFin(this.concurso.getPublicidadFin()); concurso.setPublicidadInicio(this.concurso.getPublicidadInicio()); //concurso.setStatus(this.concurso.getStatus()); //concurso.setTipoInscripcion(this.concurso.getTipoInscripcion()); dao.update(concurso); System.out.println("objeto actualizado, administrado por "+concurso.getAutor()); System.out.println("Detalles:"+ concurso.getNombre()); return "index"; } }catch(Exception e){ System.out.println("Error: "+e); return "crear"; } } private SelectItem[] concursosTipo = new SelectItem[]{ new SelectItem( tipos.ConcursoTipo.publico, tipos.ConcursoTipo.publico.toString() ), new SelectItem( tipos.ConcursoTipo.privado, tipos.ConcursoTipo.privado.toString() ), new SelectItem( tipos.ConcursoTipo.bloqueado, tipos.ConcursoTipo.bloqueado.toString() ) }; public SelectItem[] getTipos(){ return concursosTipo; } private SelectItem[] concursosStatus = new SelectItem[]{ new SelectItem( tipos.ConcursoStatus.nuevo, tipos.ConcursoStatus.nuevo.toString() ), new SelectItem( tipos.ConcursoStatus.iniciado, tipos.ConcursoStatus.iniciado.toString() ), new SelectItem( tipos.ConcursoStatus.pausado, tipos.ConcursoStatus.pausado.toString() ), new SelectItem( tipos.ConcursoStatus.finalizado, tipos.ConcursoStatus.finalizado.toString() ) }; public SelectItem[] getStatusConcursos(){ return concursosStatus; } public String msgNombre, msgInicio, msgFinaliza, msgAutor, msgStatus, msgTipoInscripcion, msgPublicidadInicio, msgPublicidadFin; public void setId(String id){ concurso.setId(id); } public void setNombre(String nombre){ concurso.setNombre(nombre); } public void setInicia(Date inicia){ concurso.setInicia(inicia); } public void setFinaliza(Date finaliza){ concurso.setFinaliza(finaliza); } public void setAutor(DTO.Usuario autor){ concurso.setAutor(autor); } public void setStatus(tipos.ConcursoStatus status){ concurso.setStatus(status); } public void setTipoInscripcion(tipos.ConcursoTipo tipo){ concurso.setTipoInscripcion(tipo); } public void setConvocatoria(String convocatoria){ concurso.setConvocatoria(convocatoria); } public void setPublicidadInicio(Date publicidadInicio){ concurso.setPublicidadInicio(publicidadInicio); } public void setPublicidadFin(Date publicidadFin){ concurso.setPublicidadFin(publicidadFin); } public String getId(){ return concurso.getId(); } public String getNombre(){ return concurso.getNombre(); } public Date getInicia(){ return concurso.getInicia(); } public Date getFinaliza(){ return concurso.getFinaliza(); } public DTO.Usuario getAutor(){ DAO.UsuarioDAO dao = new DAO.UsuarioDAO(); return dao.getUsuarioById(concurso.getAutor()); //return concurso.getAutor(); } public tipos.ConcursoStatus getStatus(){ return concurso.getStatus(); } public tipos.ConcursoTipo getTipoInscripcion(){ return concurso.getTipoInscripcion(); } public String getConvocatoria(){ return concurso.getConvocatoria(); } public Date getPublicidadInicio(){ return concurso.getPublicidadInicio(); } public Date getPublicidadFin(){ return concurso.getPublicidadFin(); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tipos; /** * * @author Windows */ public enum CodigoFuenteError { compilacion, ejecucion, incorrecto, tiempo, ninguno; }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tipos; /** * * @author Windows */ public enum RolTipo { participante, juez, observador, administrador; }
Java