This commit is contained in:
Lana Steuck 2008-08-12 17:59:58 -07:00
commit 189c383d48
200 changed files with 7750 additions and 5660 deletions

View File

@ -33,7 +33,7 @@ include $(BUILDDIR)/common/Defs.gmk
# Files
#
include FILES.gmk
AUTO_FILES_JAVA_DIRS = javax/swing sun/swing
AUTO_FILES_JAVA_DIRS = javax/swing sun/swing com/sun/java/swing
AUTO_JAVA_PRUNE = plaf
SUBDIRS = html32dtd plaf

View File

@ -32,7 +32,6 @@ include $(BUILDDIR)/common/Defs.gmk
SUBDIRS = \
addjsum \
auto_multi \
buildmetaindex \
commentchecker \
compile_font_config \

View File

@ -1,43 +0,0 @@
#
# Copyright 1998-2005 Sun Microsystems, Inc. All Rights Reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. Sun designates this
# particular file as subject to the "Classpath" exception as provided
# by Sun in the LICENSE file that accompanied this code.
#
# This code 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
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
# CA 95054 USA or visit www.sun.com if you need additional information or
# have any questions.
#
#
# Makefile for building the automulti tool
#
BUILDDIR = ../..
PACKAGE = build.tools.automulti
PRODUCT = tools
PROGRAM = automulti
include $(BUILDDIR)/common/Defs.gmk
BUILDTOOL_SOURCE_ROOT = $(BUILDDIR)/tools/src
BUILDTOOL_MAIN = $(PKGDIR)/AutoMulti.java
#
# Build tool jar rules.
#
include $(BUILDDIR)/common/BuildToolJar.gmk

View File

@ -1,458 +0,0 @@
/*
* Copyright 1998-2001 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package build.tools.automulti;
import java.lang.reflect.*;
import java.util.*;
import java.io.*;
/**
* Automatically generates the Multiplexing UI classes
* for Swing.
* <p>
* To use, type 'java AutoMulti <plafdir> <prefix>' where <plafdir>
* is the directory containing the source for Swing's UI classes and
* <prefix> is the package prefix to use before ".swing.plaf.multi".
* For example:
*
* <pre>
* cd TEST
* ../../../../build/solaris-sparc/bin/java AutoMulti ../../../../src/share/classes/javax/swing/plaf javax
* </pre>
*
* AutoMulti will scour the plaf directory for *UI.java files and
* generate Multi*UI.java files that do the multiplexing thing.
* <p>
* NOTE: This tool depends upon the existence of <plafdir> and on the
* compiled classes from <plafdir> being somewhere in the class path.
*
* @author Willie Walker
*/
public class AutoMulti {
static String importLines;
/**
* A silly list of parameter names to use. Skips "i" because we use
* it as a 'for' loop counter. If you want to get fancy, please feel
* to change how parameter names are obtained. This will break if
* someone decides to create a UI method that takes more than 8
* parameters. Which one is a bug (this breaking or having a method
* with more than eight parameters) is a subjective thing.
*/
public static String[] paramNames = {"a","b","c","d","e","f","g","h"};
/**
* Removes the package names (e.g., javax.swing) from the name.
*/
public static String unqualifyName(String name) {
StringTokenizer parser = new StringTokenizer(name,".");
String unqualifiedName = null;
while (parser.hasMoreTokens()) {
unqualifiedName = parser.nextToken();
}
return removeDollars(unqualifiedName);
}
/**
* Strips the extension from the filename.
*/
public static String stripExtension(String name) {
StringTokenizer parser = new StringTokenizer(name,".");
return parser.nextToken();
}
/**
* Adds some spaces.
*/
public static void indent(StringBuffer s, int i) {
while (i > 0) {
s.append(" ");
i--;
}
}
/**
* Spits out all the beginning stuff.
*/
public static StringBuffer createPreamble(String prefixName) {
StringBuffer s = new StringBuffer();
s.append("/*\n");
s.append(" *\n");
s.append(" * Copyright 1997-2007 Sun Microsystems, Inc. All Rights Reserved.\n");
s.append(" * \n");
s.append(" * This software is the proprietary information of Sun Microsystems, Inc. \n");
s.append(" * Use is subject to license terms.\n");
s.append(" * \n");
s.append(" */\n");
s.append("package " + prefixName + ".swing.plaf.multi;\n");
s.append("\n");
return s;
}
/**
* Replaces 'Xxx$Yyy' with "Xxx'. Used by addImport because you
* can't import nested classes directly.
*/
public static String removeNestedClassName(String s) {
int dollarPosition = s.indexOf('$');
if (dollarPosition >= 0) { // s contains '$'
StringBuffer sb = new StringBuffer(s);
sb.setLength(dollarPosition);
return sb.toString();
} else { // no '$'
return s;
}
}
/**
* Replaces '$' with ".'. Needed for printing inner class names
* for argument and return types.
*/
public static String removeDollars(String s) {
int dollarPosition = s.indexOf('$');
if (dollarPosition >= 0) { // s contains '$'
StringBuffer sb = new StringBuffer(s);
while (dollarPosition >= 0) {
//XXX: will there ever be more than one '$'?
sb.replace(dollarPosition, dollarPosition+1, ".");
dollarPosition = sb.indexOf("$", dollarPosition);
}
return sb.toString();
} else { // no $
return s;
}
}
/**
* Adds an import line to the String.
*/
public static void addImport(String s, Class theClass) {
if (!theClass.isPrimitive() && (theClass != Object.class)) {
String className = removeNestedClassName(theClass.getName());
String importLine = new String("import " + className + ";\n");
if (importLines.indexOf(importLine) == -1) {
importLines += importLine;
}
}
}
/**
* Spits out the class header information.
*/
public static void addHeader(StringBuffer s, String className) {
s.append("/**\n");
s.append(" * A multiplexing UI used to combine <code>" + className + "</code>s.\n");
s.append(" * \n");
s.append(" * <p>This file was automatically generated by AutoMulti.\n");
s.append(" *\n");
s.append(" * @author Otto Multey\n"); // Get it? I crack myself up.
s.append(" */\n");
s.append("public class Multi" + className + " extends " + className + " {\n");
s.append("\n");
s.append(" /**\n");
s.append(" * The vector containing the real UIs. This is populated \n");
s.append(" * in the call to <code>createUI</code>, and can be obtained by calling\n");
s.append(" * the <code>getUIs</code> method. The first element is guaranteed to be the real UI \n");
s.append(" * obtained from the default look and feel.\n");
s.append(" */\n");
s.append(" protected Vector uis = new Vector();\n");
s.append("\n");
s.append("////////////////////\n");
s.append("// Common UI methods\n");
s.append("////////////////////\n");
s.append("\n");
s.append(" /**\n");
s.append(" * Returns the list of UIs associated with this multiplexing UI. This \n");
s.append(" * allows processing of the UIs by an application aware of multiplexing \n");
s.append(" * UIs on components.\n");
s.append(" */\n");
s.append(" public ComponentUI[] getUIs() {\n");
s.append(" return MultiLookAndFeel.uisToArray(uis);\n");
s.append(" }\n");
}
/**
* Prints out the code for a method. This is pretty specific to the
* Multiplexing UI code, so don't get any fancy ideas.
*/
public static void addMethod(StringBuffer s, Method m, String origName, String className) {
// Get the method name and the return type. Be a little careful about arrays.
//
String methodName = unqualifyName(m.getName());
String returnType;
if (!m.getReturnType().isArray()) {
returnType = unqualifyName(m.getReturnType().toString());
addImport(importLines,m.getReturnType());
} else {
returnType = unqualifyName(m.getReturnType().getComponentType().toString())
+ "[]";
addImport(importLines,m.getReturnType().getComponentType());
}
// Print the javadoc
//
s.append("\n");
if (methodName.equals("createUI")) {
s.append(" /**\n");
s.append(" * Returns a multiplexing UI instance if any of the auxiliary\n");
s.append(" * <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the \n");
s.append(" * UI object obtained from the default <code>LookAndFeel</code>.\n");
s.append(" */\n");
} else if (!returnType.equals("void")) {
s.append(" /**\n");
s.append(" * Invokes the <code>" + methodName + "</code> method on each UI handled by this object.\n");
s.append(" * \n");
s.append(" * @return the value obtained from the first UI, which is\n");
s.append(" * the UI obtained from the default <code>LookAndFeel</code>\n");
s.append(" */\n");
} else {
s.append(" /**\n");
s.append(" * Invokes the <code>" + methodName
+ "</code> method on each UI handled by this object.\n");
s.append(" */\n");
}
// Print the method signature
//
s.append(" public");
if (Modifier.isStatic(m.getModifiers())) {
s.append(" static");
}
s.append(" " + returnType);
s.append(" " + methodName);
s.append("(");
Class[] params = m.getParameterTypes();
Class temp;
String braces;
for (int i = 0; i < params.length; i++) {
if (i > 0) {
s.append(", ");
}
temp = params[i];
braces = new String("");
while (temp.isArray()) {
braces += "[]";
temp = temp.getComponentType();
}
s.append(unqualifyName(temp.getName()) + braces + " " + paramNames[i]);
addImport(importLines,temp);
}
s.append(")");
// Don't forget about exceptions
//
Class exceptions[] = m.getExceptionTypes();
String throwsString = new String("");
if (exceptions.length > 0) {
s.append("\n");
indent(s,12);
s.append("throws ");
for (int i = 0; i < exceptions.length; i++) {
if (i > 0) {
s.append(", ");
}
s.append(unqualifyName(exceptions[i].getName()));
addImport(importLines,exceptions[i]);
}
}
s.append(throwsString + " {\n");
// Now print out the contents of the method. We do a special thing
// for the createUI method, another thing if the method returns 'void'
// and a third thing if we don't do either of the first two. If
// you want to squash this down, feel free.
//
if (methodName.equals("createUI")) {
indent(s,8);
s.append("ComponentUI mui = new Multi" + origName + "();\n");
indent(s,8);
s.append("return MultiLookAndFeel.createUIs(mui,\n");
indent(s,42);
s.append("((Multi" + origName +") mui).uis,\n");
indent(s,42);
for (int i = 0; i < params.length; i++) {
if (i > 0) {
s.append(",");
}
s.append(paramNames[i]);
}
s.append(");\n");
} else if (!returnType.equals("void")) {
indent(s,8);
s.append(returnType + " returnValue = \n");
indent(s,12);
s.append("((" + className + ") (uis.elementAt(0)))."
+ methodName + "(");
for (int i = 0; i < params.length; i++) {
if (i > 0) {
s.append(",");
}
s.append(paramNames[i]);
}
s.append(");\n");
indent(s,8);
s.append("for (int i = 1; i < uis.size(); i++) {\n");
indent(s,12);
s.append("((" + className + ") (uis.elementAt(i)))."
+ methodName + "(");
for (int i = 0; i < params.length; i++) {
if (i > 0) {
s.append(",");
}
s.append(paramNames[i]);
}
s.append(");\n");
indent(s,8);
s.append("}\n");
indent(s,8);
s.append("return returnValue;\n");
} else {
indent(s,8);
s.append("for (int i = 0; i < uis.size(); i++) {\n");
indent(s,12);
s.append("((" + className + ") (uis.elementAt(i)))."
+ methodName + "(");
for (int i = 0; i < params.length; i++) {
if (i > 0) {
s.append(",");
}
s.append(paramNames[i]);
}
s.append(");\n");
indent(s,8);
s.append("}\n");
}
indent(s,4);
s.append("}\n");
}
/**
* Takes a plaf class name (e.g., "MenuUI") and generates the corresponding
* Multiplexing UI Java source code (e.g., "MultiMenuUI.java").
*/
public static void generateFile(String prefixName, String className) {
try {
FileOutputStream fos;
PrintWriter outFile;
importLines = new String();
importLines += new String("import java.util.Vector;\n");
StringBuffer body = new StringBuffer();
Class wee = Class.forName(prefixName + ".swing.plaf." + className);
String weeName = unqualifyName(wee.getName());
addImport(importLines,wee);
while (!weeName.equals("Object")) {
body.append("\n");
body.append("////////////////////\n");
body.append("// " + weeName + " methods\n");
body.append("////////////////////\n");
Method[] methods = wee.getDeclaredMethods();
for (int i=0; i < methods.length; i++) {
if (Modifier.isPublic(methods[i].getModifiers())) {
addMethod(body,methods[i],className,weeName);
}
}
wee = wee.getSuperclass();
weeName = unqualifyName(wee.getName());
addImport(importLines,wee);
}
fos = new FileOutputStream("Multi" + className + ".java");
outFile = new PrintWriter(fos);
StringBuffer outText = createPreamble(prefixName);
outText.append(importLines.toString() + "\n");
addHeader(outText,className);
outText.append(body.toString());
outText.append("}\n");
outFile.write(outText.toString());
outFile.flush();
outFile.close();
} catch (Exception e) {
System.err.println(e);
}
}
/**
* D'Oh! Something bad happened.
*/
public static void usage(String s) throws IOException {
System.err.println("Usage: AutoMulti <plafdir> [com.sun]");
throw new IllegalArgumentException(s);
}
/**
* Takes the plaf directory name and generates the multiplexing UI
* source code.
*/
public static void main(String[] args) throws IOException {
if (args.length < 1) {
usage("");
}
String dirName = args[0];
File dir = new File(dirName);
if (!dir.isDirectory()) {
System.err.println("No such directory: " + dirName);
usage("");
}
String prefixName;
if (args.length > 1) {
prefixName = args[1];
} else {
prefixName = "com.sun.java";
}
String plafUIs[] = dir.list(new UIJavaFilter());
for (int i = 0; i < plafUIs.length; i++) {
generateFile(prefixName,stripExtension(plafUIs[i]));
}
}
}
/**
* Only accepts file names of the form *UI.java. The one exception
* is not accepting ComponentUI.java because we don't need to generate
* a multiplexing class for it.
*/
class UIJavaFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
if (name.equals("ComponentUI.java")) {
return false;
} else if (name.endsWith("UI.java")) {
return true;
} else {
return false;
}
}
}

View File

@ -1,36 +0,0 @@
AutoMulti is the tool that automatically generates the
Multi*UI classes for the Multiplexing look and feel.
Instructions for using it are in AutoMulti.java.
TestALFGenerator is a tool (a variation of AutoMulti)
that automatically generates an auxiliary look and
feel that you can use to test the Multiplexing look
and feel. The TestALF look and feel implements every
method by printing the message "In the xxx method of
the TextALFYyyUI class." and, except in the case of
createUI, returning something meaningless (since,
except in the case of createUI, the return value is
ignored).
TestALFLookAndFeel.java is the only non-auto-generated
file for the TestALF L&F. If you specify a package
argument to TestALFGenerator, you'll have to change
the code in TestALFLookAndFeel.java to reflect the
package name.
To test any application with the TestALF, make sure the
compiled TestALF classes are in the class path. Then add
this to the <JDK_HOME>/lib/swing.properties file (which
you'll probably have to create):
swing.auxiliarylaf=TestALFLookAndFeel
E.g., if you're running SwingSet2 against your solaris
build, then you'd create/edit the swing.properties file
in <wsdir>/build/solaris-sparc/lib.
Then run any app. You'll see lots of thrilling "In the
Xxxx method of the Yyy class" messages. If you get anything
else (especially an exception), then you've found a bug.
Probably in the default look and feel.

View File

@ -1,401 +0,0 @@
/*
* Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package build.tools.automulti;
import java.lang.reflect.*;
import java.util.*;
import java.io.*;
/**
* Automatically generates an auxiliary look and feel to be
* used for testing the Multiplexing look and feel.
* <p>
* To use, type 'java TestALFGenerator <plafdir> [<package>]' where <plafdir>
* is the directory containing the source for Swing's UI classes.
* <package> is an optional argument that specifies the package
* of the TestALF classes. If it's omitted, the classes are in
* the default package.
* For example:
*
* <pre>
* ../../../../build/solaris-sparc/bin/java TestALFGenerator ../../../../src/share/classes/javax/swing/plaf com.myco.myalaf
* </pre>
*
* TestALFGenerator will scour the plaf directory for *UI.java files and
* generate TestALF*UI.java files.
* <p>
* NOTE: This tool depends upon the existence of <plafdir> and on the
* compiled classes from <plafdir> being somewhere in the class path.
*
* @author Willie Walker
*/
public class TestALFGenerator {
static String importLines;
static String packageName;
static String classPrefix = "TestALF";
/**
* A silly list of parameter names to use. Skips "i" because we use
* it as a 'for' loop counter. If you want to get fancy, please feel
* to change how parameter names are obtained. This will break if
* someone decides to create a UI method that takes more than 8
* parameters. Which one is a bug (this breaking or having a method
* with more than eight parameters) is a subjective thing.
*/
public static String[] paramNames = {"a","b","c","d","e","f","g","h"};
/**
* Removes the package names (e.g., javax.swing) from the name.
*/
public static String unqualifyName(String name) {
StringTokenizer parser = new StringTokenizer(name,".");
String unqualifiedName = null;
while (parser.hasMoreTokens()) {
unqualifiedName = parser.nextToken();
}
return removeDollars(unqualifiedName);
}
/**
* Strips the extension from the filename.
*/
public static String stripExtension(String name) {
StringTokenizer parser = new StringTokenizer(name,".");
return parser.nextToken();
}
/**
* Adds some spaces.
*/
public static void indent(StringBuffer s, int i) {
while (i > 0) {
s.append(" ");
i--;
}
}
/**
* Spits out all the beginning stuff.
*/
public static StringBuffer createPreamble(String prefixName) {
StringBuffer s = new StringBuffer();
s.append("/*\n");
s.append(" *\n");
s.append(" * Copyright 1997-2007 Sun Microsystems, Inc. All Rights Reserved.\n");
s.append(" * \n");
s.append(" * This software is the proprietary information of Sun Microsystems, Inc. \n");
s.append(" * Use is subject to license terms.\n");
s.append(" * \n");
s.append(" */\n");
if (packageName != null) {
s.append("package " + packageName + ";\n");
s.append("\n");
}
return s;
}
/**
* Replaces 'Xxx$Yyy' with "Xxx'. Used by addImport because you
* can't import nested classes directly.
*/
public static String removeNestedClassName(String s) {
int dollarPosition = s.indexOf('$');
if (dollarPosition >= 0) { // s contains '$'
StringBuffer sb = new StringBuffer(s);
sb.setLength(dollarPosition);
return sb.toString();
} else { // no '$'
return s;
}
}
/**
* Replaces '$' with ".'. Needed for printing inner class names
* for argument and return types.
*/
public static String removeDollars(String s) {
int dollarPosition = s.indexOf('$');
if (dollarPosition >= 0) { // s contains '$'
StringBuffer sb = new StringBuffer(s);
while (dollarPosition >= 0) {
//XXX: will there ever be more than one '$'?
sb.replace(dollarPosition, dollarPosition+1, ".");
dollarPosition = sb.indexOf("$", dollarPosition);
}
return sb.toString();
} else { // no $
return s;
}
}
/**
* Adds an import line to the String.
*/
public static void addImport(String s, Class theClass) {
if (!theClass.isPrimitive() && (theClass != Object.class)) {
String className = removeNestedClassName(theClass.getName());
String importLine = new String("import " + className + ";\n");
if (importLines.indexOf(importLine) == -1) {
importLines += importLine;
}
}
}
/**
* Spits out the class header information.
*/
public static void addHeader(StringBuffer s, String className) {
s.append("/**\n");
s.append(" * An auxiliary UI for <code>" + className + "</code>s.\n");
s.append(" * \n");
s.append(" * <p>This file was automatically generated by TestALFGenerator.\n");
s.append(" *\n");
s.append(" * @author Otto Multey\n"); // Get it? I crack myself up.
s.append(" */\n");
s.append("public class " + classPrefix + className + " extends " + className + " {\n");
s.append("\n");
}
/**
* Prints out the code for a method.
*/
public static void addMethod(StringBuffer s, Method m, String origName, String className) {
// Get the method name and the return type. Be a little careful about arrays.
//
String methodName = unqualifyName(m.getName());
String returnType;
if (!m.getReturnType().isArray()) {
returnType = unqualifyName(m.getReturnType().toString());
addImport(importLines,m.getReturnType());
} else {
returnType = unqualifyName(m.getReturnType().getComponentType().toString())
+ "[]";
addImport(importLines,m.getReturnType().getComponentType());
}
// Print the javadoc
//
s.append("\n");
if (methodName.equals("createUI")) {
s.append(" /**\n");
s.append(" * Returns a UI object for this component.\n");
s.append(" */\n");
} else {
s.append(" /**\n");
s.append(" * Prints a message saying this method has been invoked.\n");
s.append(" */\n");
}
// Print the method signature
//
s.append(" public");
if (Modifier.isStatic(m.getModifiers())) {
s.append(" static");
}
s.append(" " + returnType);
s.append(" " + methodName);
s.append("(");
Class[] params = m.getParameterTypes();
Class temp;
String braces;
for (int i = 0; i < params.length; i++) {
if (i > 0) {
s.append(", ");
}
temp = params[i];
braces = new String("");
while (temp.isArray()) {
braces += "[]";
temp = temp.getComponentType();
}
s.append(unqualifyName(temp.getName()) + braces + " " + paramNames[i]);
addImport(importLines,temp);
}
s.append(")");
// Don't forget about exceptions
//
Class exceptions[] = m.getExceptionTypes();
String throwsString = new String("");
if (exceptions.length > 0) {
s.append("\n");
indent(s,12);
s.append("throws ");
for (int i = 0; i < exceptions.length; i++) {
if (i > 0) {
s.append(", ");
}
s.append(unqualifyName(exceptions[i].getName()));
addImport(importLines,exceptions[i]);
}
}
s.append(throwsString + " {\n");
// Now print out the contents of the method.
indent(s,8);
s.append("System.out.println(\"In the " + methodName
+ " method of the "
+ classPrefix + origName + " class.\");\n");
if (methodName.equals("createUI")) {
indent(s,8);
s.append("return ui;\n");
} else {
// If we have to return something, do so.
if (!returnType.equals("void")) {
Class rType = m.getReturnType();
indent(s,8);
if (!rType.isPrimitive()) {
s.append("return null;\n");
} else if (rType == Boolean.TYPE) {
s.append("return false;\n");
} else if (rType == Character.TYPE) {
s.append("return '0';\n");
} else { // byte, short, int, long, float, or double
s.append("return 0;\n");
}
}
}
indent(s,4);
s.append("}\n");
}
/**
* Takes a plaf class name (e.g., "MenuUI") and generates the corresponding
* TestALF UI Java source code (e.g., "TestALFMenuUI.java").
*/
public static void generateFile(String prefixName, String className) {
try {
FileOutputStream fos;
PrintWriter outFile;
importLines = new String();
importLines += new String("import java.util.Vector;\n");
StringBuffer body = new StringBuffer();
Class wee = Class.forName(prefixName + ".swing.plaf." + className);
String weeName = unqualifyName(wee.getName());
String thisClassName = classPrefix + className;
addImport(importLines,wee);
// Declare and initialize the shared UI object.
body.append("\n");
body.append("////////////////////\n");
body.append("// Shared UI object\n");
body.append("////////////////////\n");
body.append("private final static " + thisClassName
+ " ui = new " + thisClassName + "();\n");
while (!weeName.equals("Object")) {
body.append("\n");
body.append("////////////////////\n");
body.append("// " + weeName + " methods\n");
body.append("////////////////////\n");
Method[] methods = wee.getDeclaredMethods();
for (int i=0; i < methods.length; i++) {
if (Modifier.isPublic(methods[i].getModifiers())) {
addMethod(body,methods[i],className,weeName);
}
}
wee = wee.getSuperclass();
weeName = unqualifyName(wee.getName());
addImport(importLines,wee);
}
fos = new FileOutputStream(classPrefix + className + ".java");
outFile = new PrintWriter(fos);
StringBuffer outText = createPreamble(prefixName);
outText.append(importLines.toString() + "\n");
addHeader(outText,className);
outText.append(body.toString());
outText.append("}\n");
outFile.write(outText.toString());
outFile.flush();
outFile.close();
} catch (Exception e) {
System.err.println(e);
}
}
/**
* D'Oh! Something bad happened.
*/
public static void usage(String s) throws IOException {
System.err.println("Usage: java TestALFGenerator <plafdir> [<packageName>]");
throw new IllegalArgumentException(s);
}
/**
* Takes the plaf directory name and generates the TestALF UI
* source code.
*/
public static void main(String[] args) throws IOException {
if (args.length < 1) {
usage("");
}
String dirName = args[0];
File dir = new File(dirName);
if (!dir.isDirectory()) {
System.err.println("No such directory: " + dirName);
usage("");
}
if (args.length > 1) {
packageName = args[1];
}
String plafUIs[] = dir.list(new UIJavaFilter());
for (int i = 0; i < plafUIs.length; i++) {
generateFile("javax",stripExtension(plafUIs[i]));
}
}
}
/**
* Only accepts file names of the form *UI.java. The one exception
* is not accepting ComponentUI.java because we don't need to generate
* a TestALF class for it.
*/
class UIJavaFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
if (name.equals("ComponentUI.java")) {
return false;
} else if (name.endsWith("UI.java")) {
return true;
} else {
return false;
}
}
}

View File

@ -1,182 +0,0 @@
/*
* Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
//package com.myco.myalaf; //search for myalaf for other refs to package name
package build.tools.automulti;
import java.util.Vector;
import java.lang.reflect.Method;
import javax.swing.*;
import javax.swing.plaf.*;
/**
* <p>An auxiliary look and feel used for testing the Multiplexing
* look and feel.
* <p>
*
* @see UIManager#addAuxiliaryLookAndFeel
* @see javax.swing.plaf.multi
*
* @author Kathy Walrath
* @author Will Walker
*/
public class TestALFLookAndFeel extends LookAndFeel {
//////////////////////////////
// LookAndFeel methods
//////////////////////////////
/**
* Returns a string, suitable for use in menus,
* that identifies this look and feel.
*
* @return a string such as "Test Auxiliary Look and Feel"
*/
public String getName() {
return "Test Auxiliary Look and Feel";
}
/**
* Returns a string, suitable for use by applications/services,
* that identifies this look and feel.
*
* @return "TestALF"
*/
public String getID() {
return "TestALF";
}
/**
* Returns a one-line description of this look and feel.
*
* @return a descriptive string such as "Allows multiple UI instances per component instance"
*/
public String getDescription() {
return "Allows multiple UI instances per component instance";
}
/**
* Returns <code>false</code>;
* this look and feel is not native to any platform.
*
* @return <code>false</code>
*/
public boolean isNativeLookAndFeel() {
return false;
}
/**
* Returns <code>true</code>;
* every platform permits this look and feel.
*
* @return <code>true</code>
*/
public boolean isSupportedLookAndFeel() {
return true;
}
/**
* Creates, initializes, and returns
* the look and feel specific defaults.
* For this look and feel,
* the defaults consist solely of
* mappings of UI class IDs
* (such as "ButtonUI")
* to <code>ComponentUI</code> class names
* (such as "com.myco.myalaf.MultiButtonUI").
*
* @return an initialized <code>UIDefaults</code> object
* @see javax.swing.JComponent#getUIClassID
*/
public UIDefaults getDefaults() {
System.out.println("In the TestALFLookAndFeel getDefaults method.");
UIDefaults table = new TestALFUIDefaults();
//String prefix = "com.myco.myalaf.TestALF";
String prefix = "TestALF";
Object[] uiDefaults = {
"ButtonUI", prefix + "ButtonUI",
"CheckBoxMenuItemUI", prefix + "MenuItemUI",
"CheckBoxUI", prefix + "ButtonUI",
"ColorChooserUI", prefix + "ColorChooserUI",
"ComboBoxUI", prefix + "ComboBoxUI",
"DesktopIconUI", prefix + "DesktopIconUI",
"DesktopPaneUI", prefix + "DesktopPaneUI",
"EditorPaneUI", prefix + "TextUI",
"FileChooserUI", prefix + "FileChooserUI",
"FormattedTextFieldUI", prefix + "TextUI",
"InternalFrameUI", prefix + "InternalFrameUI",
"LabelUI", prefix + "LabelUI",
"ListUI", prefix + "ListUI",
"MenuBarUI", prefix + "MenuBarUI",
"MenuItemUI", prefix + "MenuItemUI",
"MenuUI", prefix + "MenuItemUI",
"OptionPaneUI", prefix + "OptionPaneUI",
"PanelUI", prefix + "PanelUI",
"PasswordFieldUI", prefix + "TextUI",
"PopupMenuSeparatorUI", prefix + "SeparatorUI",
"PopupMenuUI", prefix + "PopupMenuUI",
"ProgressBarUI", prefix + "ProgressBarUI",
"RadioButtonMenuItemUI", prefix + "MenuItemUI",
"RadioButtonUI", prefix + "ButtonUI",
"RootPaneUI", prefix + "RootPaneUI",
"ScrollBarUI", prefix + "ScrollBarUI",
"ScrollPaneUI", prefix + "ScrollPaneUI",
"SeparatorUI", prefix + "SeparatorUI",
"SliderUI", prefix + "SliderUI",
"SpinnerUI", prefix + "SpinnerUI",
"SplitPaneUI", prefix + "SplitPaneUI",
"TabbedPaneUI", prefix + "TabbedPaneUI",
"TableHeaderUI", prefix + "TableHeaderUI",
"TableUI", prefix + "TableUI",
"TextAreaUI", prefix + "TextUI",
"TextFieldUI", prefix + "TextUI",
"TextPaneUI", prefix + "TextUI",
"ToggleButtonUI", prefix + "ButtonUI",
"ToolBarSeparatorUI", prefix + "SeparatorUI",
"ToolBarUI", prefix + "ToolBarUI",
"ToolTipUI", prefix + "ToolTipUI",
"TreeUI", prefix + "TreeUI",
"ViewportUI", prefix + "ViewportUI",
};
table.putDefaults(uiDefaults);
return table;
}
}
/**
* We want the Test auxiliary look and feel to be quiet and fallback
* gracefully if it cannot find a UI. This class overrides the
* getUIError method of UIDefaults, which is the method that
* emits error messages when it cannot find a UI class in the
* LAF.
*/
class TestALFUIDefaults extends UIDefaults {
protected void getUIError(String msg) {
System.err.println("Test auxiliary L&F: " + msg);
}
}

View File

@ -0,0 +1,178 @@
/*
* Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.java.swing;
import sun.awt.EventQueueDelegate;
import sun.awt.AppContext;
import java.util.Map;
import java.util.concurrent.Callable;
import java.awt.AWTEvent;
import java.awt.EventQueue;
import java.awt.Component;
import javax.swing.JComponent;
import javax.swing.RepaintManager;
/**
* A collection of utility methods for Swing.
* <p>
* <b>WARNING:</b> While this class is public, it should not be treated as
* public API and its API may change in incompatable ways between dot dot
* releases and even patch releases. You should not rely on this class even
* existing.
*
* This is a second part of sun.swing.SwingUtilities2. It is required
* to provide services for JavaFX applets.
*
*/
public class SwingUtilities3 {
/**
* The {@code clientProperty} key for delegate {@code RepaintManager}
*/
private static final Object DELEGATE_REPAINT_MANAGER_KEY =
new StringBuilder("DelegateRepaintManagerKey");
/**
* Registers delegate RepaintManager for {@code JComponent}.
*/
public static void setDelegateRepaintManager(JComponent component,
RepaintManager repaintManager) {
/* setting up flag in AppContext to speed up lookups in case
* there are no delegate RepaintManagers used.
*/
AppContext.getAppContext().put(DELEGATE_REPAINT_MANAGER_KEY,
Boolean.TRUE);
component.putClientProperty(DELEGATE_REPAINT_MANAGER_KEY,
repaintManager);
}
/**
* Returns delegate {@code RepaintManager} for {@code component} hierarchy.
*/
public static RepaintManager getDelegateRepaintManager(Component
component) {
RepaintManager delegate = null;
if (Boolean.TRUE == AppContext.getAppContext().get(
DELEGATE_REPAINT_MANAGER_KEY)) {
while (delegate == null && component != null) {
while (component != null
&& ! (component instanceof JComponent)) {
component = component.getParent();
}
if (component != null) {
delegate = (RepaintManager)
((JComponent) component)
.getClientProperty(DELEGATE_REPAINT_MANAGER_KEY);
component = component.getParent();
}
}
}
return delegate;
}
/*
* We use maps to avoid reflection. Hopefully it should perform better
* this way.
*/
public static void setEventQueueDelegate(
Map<String, Map<String, Object>> map) {
EventQueueDelegate.setDelegate(new EventQueueDelegateFromMap(map));
}
private static class EventQueueDelegateFromMap
implements EventQueueDelegate.Delegate {
private final AWTEvent[] afterDispatchEventArgument;
private final Object[] afterDispatchHandleArgument;
private final Callable<Void> afterDispatchCallable;
private final AWTEvent[] beforeDispatchEventArgument;
private final Callable<Object> beforeDispatchCallable;
private final EventQueue[] getNextEventEventQueueArgument;
private final Callable<AWTEvent> getNextEventCallable;
@SuppressWarnings("unchecked")
public EventQueueDelegateFromMap(Map<String, Map<String, Object>> objectMap) {
Map<String, Object> methodMap = objectMap.get("afterDispatch");
afterDispatchEventArgument = (AWTEvent[]) methodMap.get("event");
afterDispatchHandleArgument = (Object[]) methodMap.get("handle");
afterDispatchCallable = (Callable<Void>) methodMap.get("method");
methodMap = objectMap.get("beforeDispatch");
beforeDispatchEventArgument = (AWTEvent[]) methodMap.get("event");
beforeDispatchCallable = (Callable<Object>) methodMap.get("method");
methodMap = objectMap.get("getNextEvent");
getNextEventEventQueueArgument =
(EventQueue[]) methodMap.get("eventQueue");
getNextEventCallable = (Callable<AWTEvent>) methodMap.get("method");
}
@Override
public void afterDispatch(AWTEvent event, Object handle) throws InterruptedException {
afterDispatchEventArgument[0] = event;
afterDispatchHandleArgument[0] = handle;
try {
afterDispatchCallable.call();
} catch (InterruptedException e) {
throw e;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Object beforeDispatch(AWTEvent event) throws InterruptedException {
beforeDispatchEventArgument[0] = event;
try {
return beforeDispatchCallable.call();
} catch (InterruptedException e) {
throw e;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public AWTEvent getNextEvent(EventQueue eventQueue) throws InterruptedException {
getNextEventEventQueueArgument[0] = eventQueue;
try {
return getNextEventCallable.call();
} catch (InterruptedException e) {
throw e;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}

View File

@ -442,7 +442,10 @@ class GTKColorChooserPanel extends AbstractColorChooserPanel implements
}
if (updateModel) {
getColorSelectionModel().setSelectedColor(color);
ColorSelectionModel model = getColorSelectionModel();
if (model != null) {
model.setSelectedColor(color);
}
}
triangle.setColor(hue, saturation, brightness);

View File

@ -770,33 +770,56 @@ class Metacity implements SynthConstants {
JComponent maximizeButton = findChild(titlePane, "InternalFrameTitlePane.maximizeButton");
JComponent closeButton = findChild(titlePane, "InternalFrameTitlePane.closeButton");
int buttonGap = 0;
Insets button_border = (Insets)gm.get("button_border");
Dimension buttonDim = calculateButtonSize(titlePane);
int x = getInt("left_titlebar_edge");
int y = (button_border != null) ? button_border.top : 0;
if (titlePaneParent.getComponentOrientation().isLeftToRight()) {
int x = getInt("left_titlebar_edge");
menuButton.setBounds(x, y, buttonDim.width, buttonDim.height);
menuButton.setBounds(x, y, buttonDim.width, buttonDim.height);
x = w - buttonDim.width - getInt("right_titlebar_edge");
if (button_border != null) {
x -= button_border.right;
}
x = w - buttonDim.width - getInt("right_titlebar_edge");
if (button_border != null) {
x -= button_border.right;
}
if (frame.isClosable()) {
closeButton.setBounds(x, y, buttonDim.width, buttonDim.height);
x -= (buttonDim.width + buttonGap);
}
if (frame.isClosable()) {
closeButton.setBounds(x, y, buttonDim.width, buttonDim.height);
x -= buttonDim.width;
}
if (frame.isMaximizable()) {
maximizeButton.setBounds(x, y, buttonDim.width, buttonDim.height);
x -= (buttonDim.width + buttonGap);
}
if (frame.isMaximizable()) {
maximizeButton.setBounds(x, y, buttonDim.width, buttonDim.height);
x -= buttonDim.width;
}
if (frame.isIconifiable()) {
minimizeButton.setBounds(x, y, buttonDim.width, buttonDim.height);
if (frame.isIconifiable()) {
minimizeButton.setBounds(x, y, buttonDim.width, buttonDim.height);
}
} else {
int x = w - buttonDim.width - getInt("right_titlebar_edge");
menuButton.setBounds(x, y, buttonDim.width, buttonDim.height);
x = getInt("left_titlebar_edge");
if (button_border != null) {
x += button_border.left;
}
if (frame.isClosable()) {
closeButton.setBounds(x, y, buttonDim.width, buttonDim.height);
x += buttonDim.width;
}
if (frame.isMaximizable()) {
maximizeButton.setBounds(x, y, buttonDim.width, buttonDim.height);
x += buttonDim.width;
}
if (frame.isIconifiable()) {
minimizeButton.setBounds(x, y, buttonDim.width, buttonDim.height);
}
}
}
} // end TitlePaneLayout
@ -973,10 +996,8 @@ class Metacity implements SynthConstants {
String title = jif.getTitle();
if (title != null) {
FontMetrics fm = SwingUtilities2.getFontMetrics(jif, g);
if (jif.getComponentOrientation().isLeftToRight()) {
title = SwingUtilities2.clipStringIfNecessary(jif, fm, title,
calculateTitleTextWidth(g, jif));
}
title = SwingUtilities2.clipStringIfNecessary(jif, fm, title,
calculateTitleArea(jif).width);
g.setColor(color);
SwingUtilities2.drawString(jif, g, title, x, y + fm.getAscent());
}
@ -1010,9 +1031,10 @@ class Metacity implements SynthConstants {
JComponent titlePane = findChild(jif, "InternalFrame.northPane");
Dimension buttonDim = calculateButtonSize(titlePane);
Insets title_border = (Insets)frameGeometry.get("title_border");
Rectangle r = new Rectangle();
Insets button_border = (Insets)getFrameGeometry().get("button_border");
r.x = getInt("left_titlebar_edge") + buttonDim.width;
Rectangle r = new Rectangle();
r.x = getInt("left_titlebar_edge");
r.y = 0;
r.height = titlePane.getHeight();
if (title_border != null) {
@ -1021,15 +1043,36 @@ class Metacity implements SynthConstants {
r.height -= (title_border.top + title_border.bottom);
}
r.width = titlePane.getWidth() - r.x - getInt("right_titlebar_edge");
if (jif.isClosable()) {
r.width -= buttonDim.width;
}
if (jif.isMaximizable()) {
r.width -= buttonDim.width;
}
if (jif.isIconifiable()) {
r.width -= buttonDim.width;
if (titlePane.getParent().getComponentOrientation().isLeftToRight()) {
r.x += buttonDim.width;
if (button_border != null) {
r.x += button_border.left;
}
r.width = titlePane.getWidth() - r.x - getInt("right_titlebar_edge");
if (jif.isClosable()) {
r.width -= buttonDim.width;
}
if (jif.isMaximizable()) {
r.width -= buttonDim.width;
}
if (jif.isIconifiable()) {
r.width -= buttonDim.width;
}
} else {
if (jif.isClosable()) {
r.x += buttonDim.width;
}
if (jif.isMaximizable()) {
r.x += buttonDim.width;
}
if (jif.isIconifiable()) {
r.x += buttonDim.width;
}
r.width = titlePane.getWidth() - r.x - getInt("right_titlebar_edge")
- buttonDim.width;
if (button_border != null) {
r.x -= button_border.right;
}
}
if (title_border != null) {
r.width -= title_border.right;

View File

@ -49,8 +49,7 @@ public class DesktopProperty implements UIDefaults.ActiveValue {
/**
* ReferenceQueue of unreferenced WeakPCLs.
*/
private static ReferenceQueue queue;
private static ReferenceQueue<DesktopProperty> queue;
/**
* PropertyChangeListener attached to the Toolkit.
@ -76,7 +75,7 @@ public class DesktopProperty implements UIDefaults.ActiveValue {
static {
queue = new ReferenceQueue();
queue = new ReferenceQueue<DesktopProperty>();
}
/**
@ -117,8 +116,8 @@ public class DesktopProperty implements UIDefaults.ActiveValue {
XPStyle.invalidateStyle();
}
Frame appFrames[] = Frame.getFrames();
for (int j=0; j < appFrames.length; j++) {
updateWindowUI(appFrames[j]);
for (Frame appFrame : appFrames) {
updateWindowUI(appFrame);
}
}
@ -128,8 +127,8 @@ public class DesktopProperty implements UIDefaults.ActiveValue {
private static void updateWindowUI(Window window) {
SwingUtilities.updateComponentTreeUI(window);
Window ownedWins[] = window.getOwnedWindows();
for (int i=0; i < ownedWins.length; i++) {
updateWindowUI(ownedWins[i]);
for (Window ownedWin : ownedWins) {
updateWindowUI(ownedWin);
}
}
@ -270,13 +269,13 @@ public class DesktopProperty implements UIDefaults.ActiveValue {
* is handled via a WeakReference so as not to pin down the
* DesktopProperty.
*/
private static class WeakPCL extends WeakReference
private static class WeakPCL extends WeakReference<DesktopProperty>
implements PropertyChangeListener {
private Toolkit kit;
private String key;
private LookAndFeel laf;
WeakPCL(Object target, Toolkit kit, String key, LookAndFeel laf) {
WeakPCL(DesktopProperty target, Toolkit kit, String key, LookAndFeel laf) {
super(target, queue);
this.kit = kit;
this.key = key;
@ -284,7 +283,7 @@ public class DesktopProperty implements UIDefaults.ActiveValue {
}
public void propertyChange(PropertyChangeEvent pce) {
DesktopProperty property = (DesktopProperty)get();
DesktopProperty property = get();
if (property == null || laf != UIManager.getLookAndFeel()) {
// The property was GC'ed, we're no longer interested in

View File

@ -96,7 +96,7 @@ public class WindowsDesktopManager extends DefaultDesktopManager
}
} catch (PropertyVetoException e) {}
if (f != currentFrame) {
currentFrameRef = new WeakReference(f);
currentFrameRef = new WeakReference<JInternalFrame>(f);
}
}

View File

@ -983,7 +983,7 @@ public class WindowsFileChooserUI extends BasicFileChooserUI {
} else if (s.equals("componentOrientation")) {
ComponentOrientation o = (ComponentOrientation)e.getNewValue();
JFileChooser cc = (JFileChooser)e.getSource();
if (o != (ComponentOrientation)e.getOldValue()) {
if (o != e.getOldValue()) {
cc.applyComponentOrientation(o);
}
} else if (s.equals("ancestor")) {
@ -1123,7 +1123,7 @@ public class WindowsFileChooserUI extends BasicFileChooserUI {
* Data model for a type-face selection combo-box.
*/
protected class DirectoryComboBoxModel extends AbstractListModel implements ComboBoxModel {
Vector directories = new Vector();
Vector<File> directories = new Vector<File>();
int[] depths = null;
File selectedDirectory = null;
JFileChooser chooser = getFileChooser();
@ -1162,7 +1162,7 @@ public class WindowsFileChooserUI extends BasicFileChooserUI {
// Get the canonical (full) path. This has the side
// benefit of removing extraneous chars from the path,
// for example /foo/bar/ becomes /foo/bar
File canonical = null;
File canonical;
try {
canonical = directory.getCanonicalFile();
} catch (IOException e) {
@ -1175,7 +1175,7 @@ public class WindowsFileChooserUI extends BasicFileChooserUI {
File sf = useShellFolder ? ShellFolder.getShellFolder(canonical)
: canonical;
File f = sf;
Vector path = new Vector(10);
Vector<File> path = new Vector<File>(10);
do {
path.addElement(f);
} while ((f = f.getParentFile()) != null);
@ -1183,7 +1183,7 @@ public class WindowsFileChooserUI extends BasicFileChooserUI {
int pathCount = path.size();
// Insert chain at appropriate place in vector
for (int i = 0; i < pathCount; i++) {
f = (File)path.get(i);
f = path.get(i);
if (directories.contains(f)) {
int topIndex = directories.indexOf(f);
for (int j = i-1; j >= 0; j--) {
@ -1202,12 +1202,12 @@ public class WindowsFileChooserUI extends BasicFileChooserUI {
private void calculateDepths() {
depths = new int[directories.size()];
for (int i = 0; i < depths.length; i++) {
File dir = (File)directories.get(i);
File dir = directories.get(i);
File parent = dir.getParentFile();
depths[i] = 0;
if (parent != null) {
for (int j = i-1; j >= 0; j--) {
if (parent.equals((File)directories.get(j))) {
if (parent.equals(directories.get(j))) {
depths[i] = depths[j] + 1;
break;
}
@ -1306,8 +1306,8 @@ public class WindowsFileChooserUI extends BasicFileChooserUI {
FileFilter currentFilter = getFileChooser().getFileFilter();
boolean found = false;
if(currentFilter != null) {
for(int i=0; i < filters.length; i++) {
if(filters[i] == currentFilter) {
for (FileFilter filter : filters) {
if (filter == currentFilter) {
found = true;
}
}

View File

@ -137,25 +137,46 @@ public class WindowsInternalFrameTitlePane extends BasicInternalFrameTitlePane {
int baseline = (getHeight() + fm.getAscent() - fm.getLeading() -
fm.getDescent()) / 2;
int titleX;
Rectangle r = new Rectangle(0, 0, 0, 0);
if (frame.isIconifiable()) r = iconButton.getBounds();
else if (frame.isMaximizable()) r = maxButton.getBounds();
else if (frame.isClosable()) r = closeButton.getBounds();
int titleW;
if(WindowsGraphicsUtils.isLeftToRight(frame) ) {
if (r.x == 0) r.x = frame.getWidth()-frame.getInsets().right;
titleX = systemLabel.getX() + systemLabel.getWidth() + 2;
if (xp != null) {
titleX += 2;
}
titleW = r.x - titleX - 3;
title = getTitle(frame.getTitle(), fm, titleW);
} else {
titleX = systemLabel.getX() - 2
- SwingUtilities2.stringWidth(frame,fm,title);
Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0);
if (frame.isIconifiable()) {
lastIconBounds = iconButton.getBounds();
} else if (frame.isMaximizable()) {
lastIconBounds = maxButton.getBounds();
} else if (frame.isClosable()) {
lastIconBounds = closeButton.getBounds();
}
int titleX;
int titleW;
int gap = 2;
if (WindowsGraphicsUtils.isLeftToRight(frame)) {
if (lastIconBounds.x == 0) { // There are no icons
lastIconBounds.x = frame.getWidth() - frame.getInsets().right;
}
titleX = systemLabel.getX() + systemLabel.getWidth() + gap;
if (xp != null) {
titleX += 2;
}
titleW = lastIconBounds.x - titleX - gap;
} else {
if (lastIconBounds.x == 0) { // There are no icons
lastIconBounds.x = frame.getInsets().left;
}
titleW = SwingUtilities2.stringWidth(frame, fm, title);
int minTitleX = lastIconBounds.x + lastIconBounds.width + gap;
if (xp != null) {
minTitleX += 2;
}
int availableWidth = systemLabel.getX() - gap - minTitleX;
if (availableWidth > titleW) {
titleX = systemLabel.getX() - gap - titleW;
} else {
titleX = minTitleX;
titleW = availableWidth;
}
}
title = getTitle(frame.getTitle(), fm, titleW);
if (xp != null) {
String shadowType = null;
if (isSelected) {
@ -258,8 +279,8 @@ public class WindowsInternalFrameTitlePane extends BasicInternalFrameTitlePane {
g.fillRect(0, 0, w, h);
}
Icon icon = getIcon();
int iconWidth = 0;
int iconHeight = 0;
int iconWidth;
int iconHeight;
if (icon != null &&
(iconWidth = icon.getIconWidth()) > 0 &&
(iconHeight = icon.getIconHeight()) > 0) {
@ -304,18 +325,18 @@ public class WindowsInternalFrameTitlePane extends BasicInternalFrameTitlePane {
}
protected void addSystemMenuItems(JPopupMenu menu) {
JMenuItem mi = (JMenuItem)menu.add(restoreAction);
JMenuItem mi = menu.add(restoreAction);
mi.setMnemonic('R');
mi = (JMenuItem)menu.add(moveAction);
mi = menu.add(moveAction);
mi.setMnemonic('M');
mi = (JMenuItem)menu.add(sizeAction);
mi = menu.add(sizeAction);
mi.setMnemonic('S');
mi = (JMenuItem)menu.add(iconifyAction);
mi = menu.add(iconifyAction);
mi.setMnemonic('n');
mi = (JMenuItem)menu.add(maximizeAction);
mi = menu.add(maximizeAction);
mi.setMnemonic('x');
systemPopupMenu.add(new JSeparator());
mi = (JMenuItem)menu.add(closeAction);
mi = menu.add(closeAction);
mi.setMnemonic('C');
}
@ -441,7 +462,7 @@ public class WindowsInternalFrameTitlePane extends BasicInternalFrameTitlePane {
public class WindowsPropertyChangeHandler extends PropertyChangeHandler {
public void propertyChange(PropertyChangeEvent evt) {
String prop = (String)evt.getPropertyName();
String prop = evt.getPropertyName();
// Update the internal frame icon for the system menu.
if (JInternalFrame.FRAME_ICON_PROPERTY.equals(prop) &&

View File

@ -369,21 +369,21 @@ public class WindowsScrollBarUI extends BasicScrollBarUI {
*/
private static class Grid {
private static final int BUFFER_SIZE = 64;
private static HashMap map;
private static HashMap<String, WeakReference<Grid>> map;
private BufferedImage image;
static {
map = new HashMap();
map = new HashMap<String, WeakReference<Grid>>();
}
public static Grid getGrid(Color fg, Color bg) {
String key = fg.getRGB() + " " + bg.getRGB();
WeakReference ref = (WeakReference)map.get(key);
Grid grid = (ref == null) ? null : (Grid)ref.get();
WeakReference<Grid> ref = map.get(key);
Grid grid = (ref == null) ? null : ref.get();
if (grid == null) {
grid = new Grid(fg, bg);
map.put(key, new WeakReference(grid));
map.put(key, new WeakReference<Grid>(grid));
}
return grid;
}

View File

@ -53,13 +53,13 @@ public class WindowsTabbedPaneUI extends BasicTabbedPaneUI {
* Keys to use for forward focus traversal when the JComponent is
* managing focus.
*/
private static Set managingFocusForwardTraversalKeys;
private static Set<KeyStroke> managingFocusForwardTraversalKeys;
/**
* Keys to use for backward focus traversal when the JComponent is
* managing focus.
*/
private static Set managingFocusBackwardTraversalKeys;
private static Set<KeyStroke> managingFocusBackwardTraversalKeys;
private boolean contentOpaque = true;
@ -69,13 +69,13 @@ public class WindowsTabbedPaneUI extends BasicTabbedPaneUI {
// focus forward traversal key
if (managingFocusForwardTraversalKeys==null) {
managingFocusForwardTraversalKeys = new HashSet();
managingFocusForwardTraversalKeys = new HashSet<KeyStroke>();
managingFocusForwardTraversalKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));
}
tabPane.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, managingFocusForwardTraversalKeys);
// focus backward traversal key
if (managingFocusBackwardTraversalKeys==null) {
managingFocusBackwardTraversalKeys = new HashSet();
managingFocusBackwardTraversalKeys = new HashSet<KeyStroke>();
managingFocusBackwardTraversalKeys.add( KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK));
}
tabPane.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, managingFocusBackwardTraversalKeys);

View File

@ -124,7 +124,7 @@ public class WindowsTableHeaderUI extends BasicTableHeaderUI {
setIcon(null);
sortIcon = null;
SortOrder sortOrder =
getColumnSortOrder(header.getTable(), column);
getColumnSortOrder(table, column);
if (sortOrder != null) {
switch (sortOrder) {
case ASCENDING:

View File

@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82
ColorChooser.sampleText=Sample Text Sample Text
ColorChooser.swatchesNameText=Swatches
ColorChooser.swatchesMnemonic=83
ColorChooser.swatchesDisplayedMnemonicIndex=0
ColorChooser.swatchesRecentText=Recent:
ColorChooser.hsbNameText=HSB
# Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX
# constant, and an index into the text to render the mnemonic as. The
# mnemonic is xxxMnemonic and the index of the character to underline is
# xxxDisplayedMnemonicIndex.
ColorChooser.hsbMnemonic=72
ColorChooser.hsbDisplayedMnemonicIndex=0
ColorChooser.hsbHueText=H
ColorChooser.hsbSaturationText=S
ColorChooser.hsbBrightnessText=B
ColorChooser.hsbRedText=R
ColorChooser.hsbGreenText=G
ColorChooser.hsbBlueText=B
ColorChooser.hsvNameText=HSV
ColorChooser.hsvMnemonic=72
ColorChooser.hsvHueText=Hue
ColorChooser.hsvSaturationText=Saturation
ColorChooser.hsvValueText=Value
ColorChooser.hsvTransparencyText=Transparency
ColorChooser.hslNameText=HSL
ColorChooser.hslMnemonic=76
ColorChooser.hslHueText=Hue
ColorChooser.hslSaturationText=Saturation
ColorChooser.hslLightnessText=Lightness
ColorChooser.hslTransparencyText=Transparency
ColorChooser.rgbNameText=RGB
ColorChooser.rgbMnemonic=71
ColorChooser.rgbDisplayedMnemonicIndex=1
ColorChooser.rgbRedText=Red
ColorChooser.rgbRedMnemonic=68
ColorChooser.rgbGreenText=Green
ColorChooser.rgbGreenMnemonic=78
ColorChooser.rgbBlueText=Blue
ColorChooser.rgbBlueMnemonic=66
ColorChooser.rgbAlphaText=Alpha
ColorChooser.rgbHexCodeText=Color Code
ColorChooser.rgbHexCodeMnemonic=67
ColorChooser.cmykNameText=CMYK
ColorChooser.cmykMnemonic=77
ColorChooser.cmykCyanText=Cyan
ColorChooser.cmykMagentaText=Magenta
ColorChooser.cmykYellowText=Yellow
ColorChooser.cmykBlackText=Black
ColorChooser.cmykAlphaText=Alpha
############ OPTION PANE STRINGS #############
# Mnemonic keys correspond to KeyEvent.VK_XXX constant

View File

@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=90
ColorChooser.sampleText=Beispieltext Beispieltext
ColorChooser.swatchesNameText=Muster
ColorChooser.swatchesMnemonic=77
ColorChooser.swatchesDisplayedMnemonicIndex=0
ColorChooser.swatchesRecentText=Aktuell:
ColorChooser.hsbNameText=HSB
# Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX
# constant, and an index into the text to render the mnemonic as. The
# mnemonic is xxxMnemonic and the index of the character to underline is
# xxxDisplayedMnemonicIndex.
ColorChooser.hsbMnemonic=72
ColorChooser.hsbDisplayedMnemonicIndex=0
ColorChooser.hsbHueText=H
ColorChooser.hsbSaturationText=S
ColorChooser.hsbBrightnessText=B
ColorChooser.hsbRedText=R
ColorChooser.hsbGreenText=G
ColorChooser.hsbBlueText=B
ColorChooser.hsvNameText=HSV
ColorChooser.hsvMnemonic=72
ColorChooser.hsvHueText=Hue
ColorChooser.hsvSaturationText=Saturation
ColorChooser.hsvValueText=Value
ColorChooser.hsvTransparencyText=Transparency
ColorChooser.hslNameText=HSL
ColorChooser.hslMnemonic=76
ColorChooser.hslHueText=Hue
ColorChooser.hslSaturationText=Saturation
ColorChooser.hslLightnessText=Lightness
ColorChooser.hslTransparencyText=Transparency
ColorChooser.rgbNameText=RGB
ColorChooser.rgbMnemonic=71
ColorChooser.rgbDisplayedMnemonicIndex=1
ColorChooser.rgbRedText=Rot
ColorChooser.rgbRedMnemonic=82
ColorChooser.rgbGreenText=Gr\u00fcn
ColorChooser.rgbGreenMnemonic=78
ColorChooser.rgbBlueText=Blau
ColorChooser.rgbBlueMnemonic=66
ColorChooser.rgbAlphaText=Alpha
ColorChooser.rgbHexCodeText=Color Code
ColorChooser.rgbHexCodeMnemonic=67
ColorChooser.cmykNameText=CMYK
ColorChooser.cmykMnemonic=77
ColorChooser.cmykCyanText=Cyan
ColorChooser.cmykMagentaText=Magenta
ColorChooser.cmykYellowText=Yellow
ColorChooser.cmykBlackText=Black
ColorChooser.cmykAlphaText=Alpha
############ OPTION PANE STRINGS #############
# Mnemonic keys correspond to KeyEvent.VK_XXX constant

View File

@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82
ColorChooser.sampleText=Texto de ejemplo Texto de ejemplo
ColorChooser.swatchesNameText=Muestras
ColorChooser.swatchesMnemonic=77
ColorChooser.swatchesDisplayedMnemonicIndex=0
ColorChooser.swatchesRecentText=Reciente:
ColorChooser.hsbNameText=HSB
# Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX
# constant, and an index into the text to render the mnemonic as. The
# mnemonic is xxxMnemonic and the index of the character to underline is
# xxxDisplayedMnemonicIndex.
ColorChooser.hsbMnemonic=72
ColorChooser.hsbDisplayedMnemonicIndex=0
ColorChooser.hsbHueText=H
ColorChooser.hsbSaturationText=S
ColorChooser.hsbBrightnessText=B
ColorChooser.hsbRedText=R
ColorChooser.hsbGreenText=V
ColorChooser.hsbBlueText=A
ColorChooser.hsvNameText=HSV
ColorChooser.hsvMnemonic=72
ColorChooser.hsvHueText=Hue
ColorChooser.hsvSaturationText=Saturation
ColorChooser.hsvValueText=Value
ColorChooser.hsvTransparencyText=Transparency
ColorChooser.hslNameText=HSL
ColorChooser.hslMnemonic=76
ColorChooser.hslHueText=Hue
ColorChooser.hslSaturationText=Saturation
ColorChooser.hslLightnessText=Lightness
ColorChooser.hslTransparencyText=Transparency
ColorChooser.rgbNameText=RGB
ColorChooser.rgbMnemonic=71
ColorChooser.rgbDisplayedMnemonicIndex=1
ColorChooser.rgbRedText=Rojo
ColorChooser.rgbRedMnemonic=74
ColorChooser.rgbGreenText=Verde
ColorChooser.rgbGreenMnemonic=86
ColorChooser.rgbBlueText=Azul
ColorChooser.rgbBlueMnemonic=76
ColorChooser.rgbAlphaText=Alpha
ColorChooser.rgbHexCodeText=Color Code
ColorChooser.rgbHexCodeMnemonic=67
ColorChooser.cmykNameText=CMYK
ColorChooser.cmykMnemonic=77
ColorChooser.cmykCyanText=Cyan
ColorChooser.cmykMagentaText=Magenta
ColorChooser.cmykYellowText=Yellow
ColorChooser.cmykBlackText=Black
ColorChooser.cmykAlphaText=Alpha
############ OPTION PANE STRINGS #############
# Mnemonic keys correspond to KeyEvent.VK_XXX constant

View File

@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82
ColorChooser.sampleText=Echantillon de texte Echantillon de texte
ColorChooser.swatchesNameText=Echantillons
ColorChooser.swatchesMnemonic=69
ColorChooser.swatchesDisplayedMnemonicIndex=0
ColorChooser.swatchesRecentText=Dernier :
ColorChooser.hsbNameText=HSB
# Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX
# constant, and an index into the text to render the mnemonic as. The
# mnemonic is xxxMnemonic and the index of the character to underline is
# xxxDisplayedMnemonicIndex.
ColorChooser.hsbMnemonic=72
ColorChooser.hsbDisplayedMnemonicIndex=0
ColorChooser.hsbHueText=H
ColorChooser.hsbSaturationText=S
ColorChooser.hsbBrightnessText=B
ColorChooser.hsbRedText=R
ColorChooser.hsbGreenText=V
ColorChooser.hsbBlueText=B
ColorChooser.hsvNameText=HSV
ColorChooser.hsvMnemonic=72
ColorChooser.hsvHueText=Hue
ColorChooser.hsvSaturationText=Saturation
ColorChooser.hsvValueText=Value
ColorChooser.hsvTransparencyText=Transparency
ColorChooser.hslNameText=HSL
ColorChooser.hslMnemonic=76
ColorChooser.hslHueText=Hue
ColorChooser.hslSaturationText=Saturation
ColorChooser.hslLightnessText=Lightness
ColorChooser.hslTransparencyText=Transparency
ColorChooser.rgbNameText=RVB
ColorChooser.rgbMnemonic=86
ColorChooser.rgbDisplayedMnemonicIndex=1
ColorChooser.rgbRedText=Rouge
ColorChooser.rgbRedMnemonic=71
ColorChooser.rgbGreenText=Vert
ColorChooser.rgbGreenMnemonic=84
ColorChooser.rgbBlueText=Bleu
ColorChooser.rgbBlueMnemonic=66
ColorChooser.rgbAlphaText=Alpha
ColorChooser.rgbHexCodeText=Color Code
ColorChooser.rgbHexCodeMnemonic=67
ColorChooser.cmykNameText=CMYK
ColorChooser.cmykMnemonic=77
ColorChooser.cmykCyanText=Cyan
ColorChooser.cmykMagentaText=Magenta
ColorChooser.cmykYellowText=Yellow
ColorChooser.cmykBlackText=Black
ColorChooser.cmykAlphaText=Alpha
############ OPTION PANE STRINGS #############
# Mnemonic keys correspond to KeyEvent.VK_XXX constant

View File

@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82
ColorChooser.sampleText=Testo di prova Testo di prova
ColorChooser.swatchesNameText=Colori campione
ColorChooser.swatchesMnemonic=67
ColorChooser.swatchesDisplayedMnemonicIndex=0
ColorChooser.swatchesRecentText=Recenti:
ColorChooser.hsbNameText=HSB
# Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX
# constant, and an index into the text to render the mnemonic as. The
# mnemonic is xxxMnemonic and the index of the character to underline is
# xxxDisplayedMnemonicIndex.
ColorChooser.hsbMnemonic=72
ColorChooser.hsbDisplayedMnemonicIndex=0
ColorChooser.hsbHueText=H
ColorChooser.hsbSaturationText=S
ColorChooser.hsbBrightnessText=B
ColorChooser.hsbRedText=R
ColorChooser.hsbGreenText=G
ColorChooser.hsbBlueText=B
ColorChooser.hsvNameText=HSV
ColorChooser.hsvMnemonic=72
ColorChooser.hsvHueText=Hue
ColorChooser.hsvSaturationText=Saturation
ColorChooser.hsvValueText=Value
ColorChooser.hsvTransparencyText=Transparency
ColorChooser.hslNameText=HSL
ColorChooser.hslMnemonic=76
ColorChooser.hslHueText=Hue
ColorChooser.hslSaturationText=Saturation
ColorChooser.hslLightnessText=Lightness
ColorChooser.hslTransparencyText=Transparency
ColorChooser.rgbNameText=RGB
ColorChooser.rgbMnemonic=71
ColorChooser.rgbDisplayedMnemonicIndex=1
ColorChooser.rgbRedText=Rosso
ColorChooser.rgbRedMnemonic=79
ColorChooser.rgbGreenText=Verde
ColorChooser.rgbGreenMnemonic=69
ColorChooser.rgbBlueText=Blu
ColorChooser.rgbBlueMnemonic=66
ColorChooser.rgbAlphaText=Alpha
ColorChooser.rgbHexCodeText=Color Code
ColorChooser.rgbHexCodeMnemonic=67
ColorChooser.cmykNameText=CMYK
ColorChooser.cmykMnemonic=77
ColorChooser.cmykCyanText=Cyan
ColorChooser.cmykMagentaText=Magenta
ColorChooser.cmykYellowText=Yellow
ColorChooser.cmykBlackText=Black
ColorChooser.cmykAlphaText=Alpha
############ OPTION PANE STRINGS #############
# Mnemonic keys correspond to KeyEvent.VK_XXX constant

View File

@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82
ColorChooser.sampleText=\u30b5\u30f3\u30d7\u30eb\u30c6\u30ad\u30b9\u30c8 \u30b5\u30f3\u30d7\u30eb\u30c6\u30ad\u30b9\u30c8
ColorChooser.swatchesNameText=\u30b5\u30f3\u30d7\u30eb(S)
ColorChooser.swatchesMnemonic=83
ColorChooser.swatchesDisplayedMnemonicIndex=5
ColorChooser.swatchesRecentText=\u6700\u65b0:
ColorChooser.hsbNameText=HSB
# Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX
# constant, and an index into the text to render the mnemonic as. The
# mnemonic is xxxMnemonic and the index of the character to underline is
# xxxDisplayedMnemonicIndex.
ColorChooser.hsbMnemonic=72
ColorChooser.hsbDisplayedMnemonicIndex=0
ColorChooser.hsbHueText=H
ColorChooser.hsbSaturationText=S
ColorChooser.hsbBrightnessText=B
ColorChooser.hsbRedText=R
ColorChooser.hsbGreenText=G
ColorChooser.hsbBlueText=B
ColorChooser.hsvNameText=HSV
ColorChooser.hsvMnemonic=72
ColorChooser.hsvHueText=Hue
ColorChooser.hsvSaturationText=Saturation
ColorChooser.hsvValueText=Value
ColorChooser.hsvTransparencyText=Transparency
ColorChooser.hslNameText=HSL
ColorChooser.hslMnemonic=76
ColorChooser.hslHueText=Hue
ColorChooser.hslSaturationText=Saturation
ColorChooser.hslLightnessText=Lightness
ColorChooser.hslTransparencyText=Transparency
ColorChooser.rgbNameText=RGB
ColorChooser.rgbMnemonic=71
ColorChooser.rgbDisplayedMnemonicIndex=1
ColorChooser.rgbRedText=\u8d64(D)
ColorChooser.rgbRedMnemonic=68
ColorChooser.rgbGreenText=\u7dd1(N)
ColorChooser.rgbGreenMnemonic=78
ColorChooser.rgbBlueText=\u9752(B)
ColorChooser.rgbBlueMnemonic=66
ColorChooser.rgbAlphaText=Alpha
ColorChooser.rgbHexCodeText=Color Code
ColorChooser.rgbHexCodeMnemonic=67
ColorChooser.cmykNameText=CMYK
ColorChooser.cmykMnemonic=77
ColorChooser.cmykCyanText=Cyan
ColorChooser.cmykMagentaText=Magenta
ColorChooser.cmykYellowText=Yellow
ColorChooser.cmykBlackText=Black
ColorChooser.cmykAlphaText=Alpha
############ OPTION PANE STRINGS #############
# Mnemonic keys correspond to KeyEvent.VK_XXX constant

View File

@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82
ColorChooser.sampleText=\uc0d8\ud50c \ud14d\uc2a4\ud2b8 \uc0d8\ud50c \ud14d\uc2a4\ud2b8
ColorChooser.swatchesNameText=\uacac\ubcf8(S)
ColorChooser.swatchesMnemonic=83
ColorChooser.swatchesDisplayedMnemonicIndex=3
ColorChooser.swatchesRecentText=\ucd5c\uadfc \ubaa9\ub85d:
ColorChooser.hsbNameText=HSB
# Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX
# constant, and an index into the text to render the mnemonic as. The
# mnemonic is xxxMnemonic and the index of the character to underline is
# xxxDisplayedMnemonicIndex.
ColorChooser.hsbMnemonic=72
ColorChooser.hsbDisplayedMnemonicIndex=0
ColorChooser.hsbHueText=H
ColorChooser.hsbSaturationText=S
ColorChooser.hsbBrightnessText=B
ColorChooser.hsbRedText=R
ColorChooser.hsbGreenText=G
ColorChooser.hsbBlueText=B
ColorChooser.hsvNameText=HSV
ColorChooser.hsvMnemonic=72
ColorChooser.hsvHueText=Hue
ColorChooser.hsvSaturationText=Saturation
ColorChooser.hsvValueText=Value
ColorChooser.hsvTransparencyText=Transparency
ColorChooser.hslNameText=HSL
ColorChooser.hslMnemonic=76
ColorChooser.hslHueText=Hue
ColorChooser.hslSaturationText=Saturation
ColorChooser.hslLightnessText=Lightness
ColorChooser.hslTransparencyText=Transparency
ColorChooser.rgbNameText=RGB
ColorChooser.rgbMnemonic=71
ColorChooser.rgbDisplayedMnemonicIndex=1
ColorChooser.rgbRedText=\ube68\uac04\uc0c9(D)
ColorChooser.rgbRedMnemonic=68
ColorChooser.rgbGreenText=\ub179\uc0c9(N)
ColorChooser.rgbGreenMnemonic=78
ColorChooser.rgbBlueText=\ud30c\ub780\uc0c9(B)
ColorChooser.rgbBlueMnemonic=66
ColorChooser.rgbAlphaText=Alpha
ColorChooser.rgbHexCodeText=Color Code
ColorChooser.rgbHexCodeMnemonic=67
ColorChooser.cmykNameText=CMYK
ColorChooser.cmykMnemonic=77
ColorChooser.cmykCyanText=Cyan
ColorChooser.cmykMagentaText=Magenta
ColorChooser.cmykYellowText=Yellow
ColorChooser.cmykBlackText=Black
ColorChooser.cmykAlphaText=Alpha
############ OPTION PANE STRINGS #############
# Mnemonic keys correspond to KeyEvent.VK_XXX constant

View File

@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=84
ColorChooser.sampleText=Exempeltext Exempeltext
ColorChooser.swatchesNameText=Prov
ColorChooser.swatchesMnemonic=80
ColorChooser.swatchesDisplayedMnemonicIndex=0
ColorChooser.swatchesRecentText=Tidigare:
ColorChooser.hsbNameText=HSB
# Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX
# constant, and an index into the text to render the mnemonic as. The
# mnemonic is xxxMnemonic and the index of the character to underline is
# xxxDisplayedMnemonicIndex.
ColorChooser.hsbMnemonic=72
ColorChooser.hsbDisplayedMnemonicIndex=0
ColorChooser.hsbHueText=H
ColorChooser.hsbSaturationText=S
ColorChooser.hsbBrightnessText=B
ColorChooser.hsbRedText=R
ColorChooser.hsbGreenText=G
ColorChooser.hsbBlueText=B
ColorChooser.hsvNameText=HSV
ColorChooser.hsvMnemonic=72
ColorChooser.hsvHueText=Hue
ColorChooser.hsvSaturationText=Saturation
ColorChooser.hsvValueText=Value
ColorChooser.hsvTransparencyText=Transparency
ColorChooser.hslNameText=HSL
ColorChooser.hslMnemonic=76
ColorChooser.hslHueText=Hue
ColorChooser.hslSaturationText=Saturation
ColorChooser.hslLightnessText=Lightness
ColorChooser.hslTransparencyText=Transparency
ColorChooser.rgbNameText=RGB
ColorChooser.rgbMnemonic=71
ColorChooser.rgbDisplayedMnemonicIndex=1
ColorChooser.rgbRedText=R\u00f6d
ColorChooser.rgbRedMnemonic=82
ColorChooser.rgbGreenText=Gr\u00f6n
ColorChooser.rgbGreenMnemonic=71
ColorChooser.rgbBlueText=Bl\u00e5
ColorChooser.rgbBlueMnemonic=66
ColorChooser.rgbAlphaText=Alpha
ColorChooser.rgbHexCodeText=Color Code
ColorChooser.rgbHexCodeMnemonic=67
ColorChooser.cmykNameText=CMYK
ColorChooser.cmykMnemonic=77
ColorChooser.cmykCyanText=Cyan
ColorChooser.cmykMagentaText=Magenta
ColorChooser.cmykYellowText=Yellow
ColorChooser.cmykBlackText=Black
ColorChooser.cmykAlphaText=Alpha
############ OPTION PANE STRINGS #############
# Mnemonic keys correspond to KeyEvent.VK_XXX constant

View File

@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82
ColorChooser.sampleText=\u6837\u54c1\u6587\u672c \u6837\u54c1\u6587\u672c
ColorChooser.swatchesNameText=\u6837\u54c1(S)
ColorChooser.swatchesMnemonic=83
ColorChooser.swatchesDisplayedMnemonicIndex=3
ColorChooser.swatchesRecentText=\u6700\u8fd1:
ColorChooser.hsbNameText=HSB
# Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX
# constant, and an index into the text to render the mnemonic as. The
# mnemonic is xxxMnemonic and the index of the character to underline is
# xxxDisplayedMnemonicIndex.
ColorChooser.hsbMnemonic=72
ColorChooser.hsbDisplayedMnemonicIndex=0
ColorChooser.hsbHueText=H
ColorChooser.hsbSaturationText=S
ColorChooser.hsbBrightnessText=B
ColorChooser.hsbRedText=R
ColorChooser.hsbGreenText=G
ColorChooser.hsbBlueText=B
ColorChooser.hsvNameText=HSV
ColorChooser.hsvMnemonic=72
ColorChooser.hsvHueText=Hue
ColorChooser.hsvSaturationText=Saturation
ColorChooser.hsvValueText=Value
ColorChooser.hsvTransparencyText=Transparency
ColorChooser.hslNameText=HSL
ColorChooser.hslMnemonic=76
ColorChooser.hslHueText=Hue
ColorChooser.hslSaturationText=Saturation
ColorChooser.hslLightnessText=Lightness
ColorChooser.hslTransparencyText=Transparency
ColorChooser.rgbNameText=RGB
ColorChooser.rgbMnemonic=71
ColorChooser.rgbDisplayedMnemonicIndex=1
ColorChooser.rgbRedText=\u7ea2
ColorChooser.rgbRedMnemonic=68
ColorChooser.rgbGreenText=\u7eff
ColorChooser.rgbGreenMnemonic=78
ColorChooser.rgbBlueText=\u84dd
ColorChooser.rgbBlueMnemonic=66
ColorChooser.rgbAlphaText=Alpha
ColorChooser.rgbHexCodeText=Color Code
ColorChooser.rgbHexCodeMnemonic=67
ColorChooser.cmykNameText=CMYK
ColorChooser.cmykMnemonic=77
ColorChooser.cmykCyanText=Cyan
ColorChooser.cmykMagentaText=Magenta
ColorChooser.cmykYellowText=Yellow
ColorChooser.cmykBlackText=Black
ColorChooser.cmykAlphaText=Alpha
############ OPTION PANE STRINGS #############
# Mnemonic keys correspond to KeyEvent.VK_XXX constant

View File

@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82
ColorChooser.sampleText=\u7bc4\u4f8b\u6587\u5b57 \u7bc4\u4f8b\u6587\u5b57
ColorChooser.swatchesNameText=\u8abf\u8272\u677f(S)
ColorChooser.swatchesMnemonic=83
ColorChooser.swatchesDisplayedMnemonicIndex=4
ColorChooser.swatchesRecentText=\u6700\u65b0\u9078\u64c7:
ColorChooser.hsbNameText=HSB
# Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX
# constant, and an index into the text to render the mnemonic as. The
# mnemonic is xxxMnemonic and the index of the character to underline is
# xxxDisplayedMnemonicIndex.
ColorChooser.hsbMnemonic=72
ColorChooser.hsbDisplayedMnemonicIndex=0
ColorChooser.hsbHueText=H
ColorChooser.hsbSaturationText=S
ColorChooser.hsbBrightnessText=B
ColorChooser.hsbRedText=R
ColorChooser.hsbGreenText=G
ColorChooser.hsbBlueText=B
ColorChooser.hsvNameText=HSV
ColorChooser.hsvMnemonic=72
ColorChooser.hsvHueText=Hue
ColorChooser.hsvSaturationText=Saturation
ColorChooser.hsvValueText=Value
ColorChooser.hsvTransparencyText=Transparency
ColorChooser.hslNameText=HSL
ColorChooser.hslMnemonic=76
ColorChooser.hslHueText=Hue
ColorChooser.hslSaturationText=Saturation
ColorChooser.hslLightnessText=Lightness
ColorChooser.hslTransparencyText=Transparency
ColorChooser.rgbNameText=RGB
ColorChooser.rgbMnemonic=71
ColorChooser.rgbDisplayedMnemonicIndex=1
ColorChooser.rgbRedText=\u7d05\u8272(D)
ColorChooser.rgbRedMnemonic=68
ColorChooser.rgbGreenText=\u7da0\u8272(N)
ColorChooser.rgbGreenMnemonic=78
ColorChooser.rgbBlueText=\u85cd\u8272(B)
ColorChooser.rgbBlueMnemonic=66
ColorChooser.rgbAlphaText=Alpha
ColorChooser.rgbHexCodeText=Color Code
ColorChooser.rgbHexCodeMnemonic=67
ColorChooser.cmykNameText=CMYK
ColorChooser.cmykMnemonic=77
ColorChooser.cmykCyanText=Cyan
ColorChooser.cmykMagentaText=Magenta
ColorChooser.cmykYellowText=Yellow
ColorChooser.cmykBlackText=Black
ColorChooser.cmykAlphaText=Alpha
############ OPTION PANE STRINGS #############
# Mnemonic keys correspond to KeyEvent.VK_XXX constant

View File

@ -39,6 +39,7 @@ import java.util.Vector;
import java.util.logging.*;
import sun.awt.dnd.SunDragSourceContextPeer;
import sun.awt.EventQueueDelegate;
/**
* EventDispatchThread is a package-private AWT class which takes
@ -243,10 +244,16 @@ class EventDispatchThread extends Thread {
try {
AWTEvent event;
boolean eventOK;
EventQueueDelegate.Delegate delegate =
EventQueueDelegate.getDelegate();
do {
event = (id == ANY_EVENT)
? theQueue.getNextEvent()
: theQueue.getNextEvent(id);
if (delegate != null && id == ANY_EVENT) {
event = delegate.getNextEvent(theQueue);
} else {
event = (id == ANY_EVENT)
? theQueue.getNextEvent()
: theQueue.getNextEvent(id);
}
eventOK = true;
synchronized (eventFilters) {
@ -272,7 +279,14 @@ class EventDispatchThread extends Thread {
eventLog.log(Level.FINEST, "Dispatching: " + event);
}
Object handle = null;
if (delegate != null) {
handle = delegate.beforeDispatch(event);
}
theQueue.dispatchEvent(event);
if (delegate != null) {
delegate.afterDispatch(event, handle);
}
return true;
}
catch (ThreadDeath death) {

View File

@ -298,7 +298,7 @@ public class DefaultPersistenceDelegate extends PersistenceDelegate {
oldL = (EventListener[])MethodUtil.invoke(m, oldInstance, new Object[]{});
newL = (EventListener[])MethodUtil.invoke(m, newInstance, new Object[]{});
}
catch (Throwable e2) {
catch (Exception e2) {
try {
Method m = type.getMethod("getListeners", new Class[]{Class.class});
oldL = (EventListener[])MethodUtil.invoke(m, oldInstance, new Object[]{listenerType});

View File

@ -404,7 +404,7 @@ public class EventHandler implements InvocationHandler {
Object newTarget = MethodUtil.invoke(getter, target, new Object[]{});
return applyGetters(newTarget, rest);
}
catch (Throwable e) {
catch (Exception e) {
throw new RuntimeException("Failed to call method: " + first +
" on " + target, e);
}

View File

@ -650,7 +650,7 @@ class java_util_Map_PersistenceDelegate extends DefaultPersistenceDelegate {
// Remove the new elements.
// Do this first otherwise we undo the adding work.
if (newMap != null) {
for ( Object newKey : newMap.keySet() ) {
for (Object newKey : newMap.keySet().toArray()) {
// PENDING: This "key" is not in the right environment.
if (!oldMap.containsKey(newKey)) {
invokeStatement(oldInstance, "remove", new Object[]{newKey}, out);
@ -986,14 +986,20 @@ class java_awt_Component_PersistenceDelegate extends DefaultPersistenceDelegate
// null to defined values after the Windows are made visible -
// special case them for now.
if (!(oldInstance instanceof java.awt.Window)) {
String[] fieldNames = new String[]{"background", "foreground", "font"};
for(int i = 0; i < fieldNames.length; i++) {
String name = fieldNames[i];
Object oldValue = ReflectionUtils.getPrivateField(oldInstance, java.awt.Component.class, name, out.getExceptionListener());
Object newValue = (newInstance == null) ? null : ReflectionUtils.getPrivateField(newInstance, java.awt.Component.class, name, out.getExceptionListener());
if (oldValue != null && !oldValue.equals(newValue)) {
invokeStatement(oldInstance, "set" + NameGenerator.capitalize(name), new Object[]{oldValue}, out);
}
Object oldBackground = c.isBackgroundSet() ? c.getBackground() : null;
Object newBackground = c2.isBackgroundSet() ? c2.getBackground() : null;
if (!MetaData.equals(oldBackground, newBackground)) {
invokeStatement(oldInstance, "setBackground", new Object[] { oldBackground }, out);
}
Object oldForeground = c.isForegroundSet() ? c.getForeground() : null;
Object newForeground = c2.isForegroundSet() ? c2.getForeground() : null;
if (!MetaData.equals(oldForeground, newForeground)) {
invokeStatement(oldInstance, "setForeground", new Object[] { oldForeground }, out);
}
Object oldFont = c.isFontSet() ? c.getFont() : null;
Object newFont = c2.isFontSet() ? c2.getFont() : null;
if (!MetaData.equals(oldFont, newFont)) {
invokeStatement(oldInstance, "setFont", new Object[] { oldFont }, out);
}
}
@ -1104,26 +1110,30 @@ class java_awt_List_PersistenceDelegate extends DefaultPersistenceDelegate {
// BorderLayout
class java_awt_BorderLayout_PersistenceDelegate extends DefaultPersistenceDelegate {
private static final String[] CONSTRAINTS = {
BorderLayout.NORTH,
BorderLayout.SOUTH,
BorderLayout.EAST,
BorderLayout.WEST,
BorderLayout.CENTER,
BorderLayout.PAGE_START,
BorderLayout.PAGE_END,
BorderLayout.LINE_START,
BorderLayout.LINE_END,
};
@Override
protected void initialize(Class<?> type, Object oldInstance,
Object newInstance, Encoder out) {
super.initialize(type, oldInstance, newInstance, out);
String[] locations = {"north", "south", "east", "west", "center"};
String[] names = {java.awt.BorderLayout.NORTH, java.awt.BorderLayout.SOUTH,
java.awt.BorderLayout.EAST, java.awt.BorderLayout.WEST,
java.awt.BorderLayout.CENTER};
for(int i = 0; i < locations.length; i++) {
Object oldC = ReflectionUtils.getPrivateField(oldInstance,
java.awt.BorderLayout.class,
locations[i],
out.getExceptionListener());
Object newC = ReflectionUtils.getPrivateField(newInstance,
java.awt.BorderLayout.class,
locations[i],
out.getExceptionListener());
BorderLayout oldLayout = (BorderLayout) oldInstance;
BorderLayout newLayout = (BorderLayout) newInstance;
for (String constraints : CONSTRAINTS) {
Object oldC = oldLayout.getLayoutComponent(constraints);
Object newC = newLayout.getLayoutComponent(constraints);
// Pending, assume any existing elements are OK.
if (oldC != null && newC == null) {
invokeStatement(oldInstance, "addLayoutComponent",
new Object[]{oldC, names[i]}, out);
new Object[] { oldC, constraints }, out);
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved.
* Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -208,91 +208,91 @@ public class PropertyChangeSupport implements Serializable {
}
/**
* Report a bound property update to any registered listeners.
* No event is fired if old and new are equal and non-null.
*
* Reports a bound property update to listeners
* that have been registered to track updates of
* all properties or a property with the specified name.
* <p>
* No event is fired if old and new values are equal and non-null.
* <p>
* This is merely a convenience wrapper around the more general
* firePropertyChange method that takes {@code
* PropertyChangeEvent} value.
* {@link #firePropertyChange(PropertyChangeEvent)} method.
*
* @param propertyName The programmatic name of the property
* that was changed.
* @param oldValue The old value of the property.
* @param newValue The new value of the property.
* @param propertyName the programmatic name of the property that was changed
* @param oldValue the old value of the property
* @param newValue the new value of the property
*/
public void firePropertyChange(String propertyName,
Object oldValue, Object newValue) {
if (oldValue != null && newValue != null && oldValue.equals(newValue)) {
return;
public void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
if (oldValue == null || newValue == null || !oldValue.equals(newValue)) {
firePropertyChange(new PropertyChangeEvent(this.source, propertyName, oldValue, newValue));
}
firePropertyChange(new PropertyChangeEvent(source, propertyName,
oldValue, newValue));
}
/**
* Report an int bound property update to any registered listeners.
* No event is fired if old and new are equal.
* Reports an integer bound property update to listeners
* that have been registered to track updates of
* all properties or a property with the specified name.
* <p>
* No event is fired if old and new values are equal.
* <p>
* This is merely a convenience wrapper around the more general
* firePropertyChange method that takes Object values.
* {@link #firePropertyChange(String, Object, Object)} method.
*
* @param propertyName The programmatic name of the property
* that was changed.
* @param oldValue The old value of the property.
* @param newValue The new value of the property.
* @param propertyName the programmatic name of the property that was changed
* @param oldValue the old value of the property
* @param newValue the new value of the property
*/
public void firePropertyChange(String propertyName,
int oldValue, int newValue) {
if (oldValue == newValue) {
return;
public void firePropertyChange(String propertyName, int oldValue, int newValue) {
if (oldValue != newValue) {
firePropertyChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue));
}
firePropertyChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue));
}
/**
* Report a boolean bound property update to any registered listeners.
* No event is fired if old and new are equal.
* Reports a boolean bound property update to listeners
* that have been registered to track updates of
* all properties or a property with the specified name.
* <p>
* No event is fired if old and new values are equal.
* <p>
* This is merely a convenience wrapper around the more general
* firePropertyChange method that takes Object values.
* {@link #firePropertyChange(String, Object, Object)} method.
*
* @param propertyName The programmatic name of the property
* that was changed.
* @param oldValue The old value of the property.
* @param newValue The new value of the property.
* @param propertyName the programmatic name of the property that was changed
* @param oldValue the old value of the property
* @param newValue the new value of the property
*/
public void firePropertyChange(String propertyName,
boolean oldValue, boolean newValue) {
if (oldValue == newValue) {
return;
public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {
if (oldValue != newValue) {
firePropertyChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue));
}
firePropertyChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue));
}
/**
* Fire an existing PropertyChangeEvent to any registered listeners.
* No event is fired if the given event's old and new values are
* equal and non-null.
* @param evt The PropertyChangeEvent object.
* Fires a property change event to listeners
* that have been registered to track updates of
* all properties or a property with the specified name.
* <p>
* No event is fired if the given event's old and new values are equal and non-null.
*
* @param event the {@code PropertyChangeEvent} to be fired
*/
public void firePropertyChange(PropertyChangeEvent evt) {
Object oldValue = evt.getOldValue();
Object newValue = evt.getNewValue();
String propertyName = evt.getPropertyName();
if (oldValue != null && newValue != null && oldValue.equals(newValue)) {
return;
}
PropertyChangeListener[] common = this.map.get(null);
PropertyChangeListener[] named = (propertyName != null)
? this.map.get(propertyName)
: null;
public void firePropertyChange(PropertyChangeEvent event) {
Object oldValue = event.getOldValue();
Object newValue = event.getNewValue();
if (oldValue == null || newValue == null || !oldValue.equals(newValue)) {
String name = event.getPropertyName();
fire(common, evt);
fire(named, evt);
PropertyChangeListener[] common = this.map.get(null);
PropertyChangeListener[] named = (name != null)
? this.map.get(name)
: null;
fire(common, event);
fire(named, event);
}
}
private void fire(PropertyChangeListener[] listeners, PropertyChangeEvent event) {
private static void fire(PropertyChangeListener[] listeners, PropertyChangeEvent event) {
if (listeners != null) {
for (PropertyChangeListener listener : listeners) {
listener.propertyChange(event);
@ -301,78 +301,69 @@ public class PropertyChangeSupport implements Serializable {
}
/**
* Report a bound indexed property update to any registered
* listeners.
* Reports a bound indexed property update to listeners
* that have been registered to track updates of
* all properties or a property with the specified name.
* <p>
* No event is fired if old and new values are equal
* and non-null.
*
* No event is fired if old and new values are equal and non-null.
* <p>
* This is merely a convenience wrapper around the more general
* firePropertyChange method that takes {@code PropertyChangeEvent} value.
* {@link #firePropertyChange(PropertyChangeEvent)} method.
*
* @param propertyName The programmatic name of the property that
* was changed.
* @param index index of the property element that was changed.
* @param oldValue The old value of the property.
* @param newValue The new value of the property.
* @param propertyName the programmatic name of the property that was changed
* @param index the index of the property element that was changed
* @param oldValue the old value of the property
* @param newValue the new value of the property
* @since 1.5
*/
public void fireIndexedPropertyChange(String propertyName, int index,
Object oldValue, Object newValue) {
firePropertyChange(new IndexedPropertyChangeEvent
(source, propertyName, oldValue, newValue, index));
public void fireIndexedPropertyChange(String propertyName, int index, Object oldValue, Object newValue) {
if (oldValue == null || newValue == null || !oldValue.equals(newValue)) {
firePropertyChange(new IndexedPropertyChangeEvent(source, propertyName, oldValue, newValue, index));
}
}
/**
* Report an <code>int</code> bound indexed property update to any registered
* listeners.
* Reports an integer bound indexed property update to listeners
* that have been registered to track updates of
* all properties or a property with the specified name.
* <p>
* No event is fired if old and new values are equal.
* <p>
* This is merely a convenience wrapper around the more general
* fireIndexedPropertyChange method which takes Object values.
* {@link #fireIndexedPropertyChange(String, int, Object, Object)} method.
*
* @param propertyName The programmatic name of the property that
* was changed.
* @param index index of the property element that was changed.
* @param oldValue The old value of the property.
* @param newValue The new value of the property.
* @param propertyName the programmatic name of the property that was changed
* @param index the index of the property element that was changed
* @param oldValue the old value of the property
* @param newValue the new value of the property
* @since 1.5
*/
public void fireIndexedPropertyChange(String propertyName, int index,
int oldValue, int newValue) {
if (oldValue == newValue) {
return;
public void fireIndexedPropertyChange(String propertyName, int index, int oldValue, int newValue) {
if (oldValue != newValue) {
fireIndexedPropertyChange(propertyName, index, Integer.valueOf(oldValue), Integer.valueOf(newValue));
}
fireIndexedPropertyChange(propertyName, index,
Integer.valueOf(oldValue),
Integer.valueOf(newValue));
}
/**
* Report a <code>boolean</code> bound indexed property update to any
* registered listeners.
* Reports a boolean bound indexed property update to listeners
* that have been registered to track updates of
* all properties or a property with the specified name.
* <p>
* No event is fired if old and new values are equal.
* <p>
* This is merely a convenience wrapper around the more general
* fireIndexedPropertyChange method which takes Object values.
* {@link #fireIndexedPropertyChange(String, int, Object, Object)} method.
*
* @param propertyName The programmatic name of the property that
* was changed.
* @param index index of the property element that was changed.
* @param oldValue The old value of the property.
* @param newValue The new value of the property.
* @param propertyName the programmatic name of the property that was changed
* @param index the index of the property element that was changed
* @param oldValue the old value of the property
* @param newValue the new value of the property
* @since 1.5
*/
public void fireIndexedPropertyChange(String propertyName, int index,
boolean oldValue, boolean newValue) {
if (oldValue == newValue) {
return;
public void fireIndexedPropertyChange(String propertyName, int index, boolean oldValue, boolean newValue) {
if (oldValue != newValue) {
fireIndexedPropertyChange(propertyName, index, Boolean.valueOf(oldValue), Boolean.valueOf(newValue));
}
fireIndexedPropertyChange(propertyName, index, Boolean.valueOf(oldValue),
Boolean.valueOf(newValue));
}
/**

View File

@ -204,20 +204,21 @@ public interface PropertyEditor {
//----------------------------------------------------------------------
/**
* Register a listener for the PropertyChange event. When a
* PropertyEditor changes its value it should fire a PropertyChange
* event on all registered PropertyChangeListeners, specifying the
* null value for the property name and itself as the source.
* Adds a listener for the value change.
* When the property editor changes its value
* it should fire a {@link PropertyChangeEvent}
* on all registered {@link PropertyChangeListener}s,
* specifying the {@code null} value for the property name
* and itself as the source.
*
* @param listener An object to be invoked when a PropertyChange
* event is fired.
* @param listener the {@link PropertyChangeListener} to add
*/
void addPropertyChangeListener(PropertyChangeListener listener);
/**
* Remove a listener for the PropertyChange event.
* Removes a listener for the value change.
*
* @param listener The PropertyChange listener to be removed.
* @param listener the {@link PropertyChangeListener} to remove
*/
void removePropertyChangeListener(PropertyChangeListener listener);

View File

@ -233,11 +233,20 @@ public class PropertyEditorSupport implements PropertyEditor {
//----------------------------------------------------------------------
/**
* Register a listener for the PropertyChange event. The class will
* fire a PropertyChange value whenever the value is updated.
* Adds a listener for the value change.
* When the property editor changes its value
* it should fire a {@link PropertyChangeEvent}
* on all registered {@link PropertyChangeListener}s,
* specifying the {@code null} value for the property name.
* If the source property is set,
* it should be used as the source of the event.
* <p>
* The same listener object may be added more than once,
* and will be called as many times as it is added.
* If {@code listener} is {@code null},
* no exception is thrown and no action is taken.
*
* @param listener An object to be invoked when a PropertyChange
* event is fired.
* @param listener the {@link PropertyChangeListener} to add
*/
public synchronized void addPropertyChangeListener(
PropertyChangeListener listener) {
@ -248,9 +257,14 @@ public class PropertyEditorSupport implements PropertyEditor {
}
/**
* Remove a listener for the PropertyChange event.
* Removes a listener for the value change.
* <p>
* If the same listener was added more than once,
* it will be notified one less time after being removed.
* If {@code listener} is {@code null}, or was never added,
* no exception is thrown and no action is taken.
*
* @param listener The PropertyChange listener to be removed.
* @param listener the {@link PropertyChangeListener} to remove
*/
public synchronized void removePropertyChangeListener(
PropertyChangeListener listener) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved.
* Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -208,126 +208,149 @@ public class VetoableChangeSupport implements Serializable {
}
/**
* Report a vetoable property update to any registered listeners. If
* anyone vetos the change, then fire a new event reverting everyone to
* the old value and then rethrow the PropertyVetoException.
* Reports a constrained property update to listeners
* that have been registered to track updates of
* all properties or a property with the specified name.
* <p>
* No event is fired if old and new are equal and non-null.
*
* @param propertyName The programmatic name of the property
* that is about to change..
* @param oldValue The old value of the property.
* @param newValue The new value of the property.
* @exception PropertyVetoException if the recipient wishes the property
* change to be rolled back.
*/
public void fireVetoableChange(String propertyName,
Object oldValue, Object newValue)
throws PropertyVetoException {
if (oldValue != null && newValue != null && oldValue.equals(newValue)) {
return;
}
PropertyChangeEvent evt = new PropertyChangeEvent(source, propertyName,
oldValue, newValue);
fireVetoableChange(evt);
}
/**
* Report a int vetoable property update to any registered listeners.
* No event is fired if old and new are equal.
* Any listener can throw a {@code PropertyVetoException} to veto the update.
* If one of the listeners vetoes the update, this method passes
* a new "undo" {@code PropertyChangeEvent} that reverts to the old value
* to all listeners that already confirmed this update
* and throws the {@code PropertyVetoException} again.
* <p>
* No event is fired if old and new values are equal and non-null.
* <p>
* This is merely a convenience wrapper around the more general
* fireVetoableChange method that takes Object values.
* {@link #fireVetoableChange(PropertyChangeEvent)} method.
*
* @param propertyName The programmatic name of the property
* that is about to change.
* @param oldValue The old value of the property.
* @param newValue The new value of the property.
* @param propertyName the programmatic name of the property that is about to change
* @param oldValue the old value of the property
* @param newValue the new value of the property
* @throws PropertyVetoException if one of listeners vetoes the property update
*/
public void fireVetoableChange(String propertyName,
int oldValue, int newValue)
throws PropertyVetoException {
if (oldValue == newValue) {
return;
public void fireVetoableChange(String propertyName, Object oldValue, Object newValue)
throws PropertyVetoException {
if (oldValue == null || newValue == null || !oldValue.equals(newValue)) {
fireVetoableChange(new PropertyChangeEvent(this.source, propertyName, oldValue, newValue));
}
fireVetoableChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue));
}
/**
* Report a boolean vetoable property update to any registered listeners.
* No event is fired if old and new are equal.
* Reports an integer constrained property update to listeners
* that have been registered to track updates of
* all properties or a property with the specified name.
* <p>
* Any listener can throw a {@code PropertyVetoException} to veto the update.
* If one of the listeners vetoes the update, this method passes
* a new "undo" {@code PropertyChangeEvent} that reverts to the old value
* to all listeners that already confirmed this update
* and throws the {@code PropertyVetoException} again.
* <p>
* No event is fired if old and new values are equal.
* <p>
* This is merely a convenience wrapper around the more general
* fireVetoableChange method that takes Object values.
* {@link #fireVetoableChange(String, Object, Object)} method.
*
* @param propertyName The programmatic name of the property
* that is about to change.
* @param oldValue The old value of the property.
* @param newValue The new value of the property.
* @param propertyName the programmatic name of the property that is about to change
* @param oldValue the old value of the property
* @param newValue the new value of the property
* @throws PropertyVetoException if one of listeners vetoes the property update
*/
public void fireVetoableChange(String propertyName,
boolean oldValue, boolean newValue)
throws PropertyVetoException {
if (oldValue == newValue) {
return;
public void fireVetoableChange(String propertyName, int oldValue, int newValue)
throws PropertyVetoException {
if (oldValue != newValue) {
fireVetoableChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue));
}
fireVetoableChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue));
}
/**
* Fire a vetoable property update to any registered listeners. If
* anyone vetos the change, then fire a new event reverting everyone to
* the old value and then rethrow the PropertyVetoException.
* Reports a boolean constrained property update to listeners
* that have been registered to track updates of
* all properties or a property with the specified name.
* <p>
* No event is fired if old and new are equal and non-null.
* Any listener can throw a {@code PropertyVetoException} to veto the update.
* If one of the listeners vetoes the update, this method passes
* a new "undo" {@code PropertyChangeEvent} that reverts to the old value
* to all listeners that already confirmed this update
* and throws the {@code PropertyVetoException} again.
* <p>
* No event is fired if old and new values are equal.
* <p>
* This is merely a convenience wrapper around the more general
* {@link #fireVetoableChange(String, Object, Object)} method.
*
* @param evt The PropertyChangeEvent to be fired.
* @exception PropertyVetoException if the recipient wishes the property
* change to be rolled back.
* @param propertyName the programmatic name of the property that is about to change
* @param oldValue the old value of the property
* @param newValue the new value of the property
* @throws PropertyVetoException if one of listeners vetoes the property update
*/
public void fireVetoableChange(PropertyChangeEvent evt)
throws PropertyVetoException {
Object oldValue = evt.getOldValue();
Object newValue = evt.getNewValue();
String propertyName = evt.getPropertyName();
if (oldValue != null && newValue != null && oldValue.equals(newValue)) {
return;
public void fireVetoableChange(String propertyName, boolean oldValue, boolean newValue)
throws PropertyVetoException {
if (oldValue != newValue) {
fireVetoableChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue));
}
VetoableChangeListener[] common = this.map.get(null);
VetoableChangeListener[] named = (propertyName != null)
? this.map.get(propertyName)
: null;
fire(common, evt);
fire(named, evt);
}
private void fire(VetoableChangeListener[] listeners, PropertyChangeEvent event) throws PropertyVetoException {
if (listeners != null) {
VetoableChangeListener current = null;
try {
for (VetoableChangeListener listener : listeners) {
current = listener;
listener.vetoableChange(event);
}
} catch (PropertyVetoException veto) {
// Create an event to revert everyone to the old value.
event = new PropertyChangeEvent( this.source,
event.getPropertyName(),
event.getNewValue(),
event.getOldValue() );
for (VetoableChangeListener listener : listeners) {
if (current == listener) {
break;
}
try {
listener.vetoableChange(event);
} catch (PropertyVetoException ex) {
// We just ignore exceptions that occur during reversions.
/**
* Fires a property change event to listeners
* that have been registered to track updates of
* all properties or a property with the specified name.
* <p>
* Any listener can throw a {@code PropertyVetoException} to veto the update.
* If one of the listeners vetoes the update, this method passes
* a new "undo" {@code PropertyChangeEvent} that reverts to the old value
* to all listeners that already confirmed this update
* and throws the {@code PropertyVetoException} again.
* <p>
* No event is fired if the given event's old and new values are equal and non-null.
*
* @param event the {@code PropertyChangeEvent} to be fired
* @throws PropertyVetoException if one of listeners vetoes the property update
*/
public void fireVetoableChange(PropertyChangeEvent event)
throws PropertyVetoException {
Object oldValue = event.getOldValue();
Object newValue = event.getNewValue();
if (oldValue == null || newValue == null || !oldValue.equals(newValue)) {
String name = event.getPropertyName();
VetoableChangeListener[] common = this.map.get(null);
VetoableChangeListener[] named = (name != null)
? this.map.get(name)
: null;
VetoableChangeListener[] listeners;
if (common == null) {
listeners = named;
}
else if (named == null) {
listeners = common;
}
else {
listeners = new VetoableChangeListener[common.length + named.length];
System.arraycopy(common, 0, listeners, 0, common.length);
System.arraycopy(named, 0, listeners, common.length, named.length);
}
if (listeners != null) {
int current = 0;
try {
while (current < listeners.length) {
listeners[current].vetoableChange(event);
current++;
}
}
// And now rethrow the PropertyVetoException.
throw veto;
catch (PropertyVetoException veto) {
event = new PropertyChangeEvent(this.source, name, newValue, oldValue);
for (int i = 0; i < current; i++) {
try {
listeners[i].vetoableChange(event);
}
catch (PropertyVetoException exception) {
// ignore exceptions that occur during rolling back
}
}
throw veto; // rethrow the veto exception
}
}
}
}

View File

@ -131,10 +131,7 @@ public class JApplet extends Applet implements Accessible,
// Check the timerQ and restart if necessary.
TimerQueue q = TimerQueue.sharedInstance();
if(q != null) {
synchronized(q) {
if(!q.running)
q.start();
}
q.startIfNeeded();
}
/* Workaround for bug 4155072. The shared double buffer image

View File

@ -40,6 +40,8 @@ import sun.awt.SunToolkit;
import sun.java2d.SunGraphicsEnvironment;
import sun.security.action.GetPropertyAction;
import com.sun.java.swing.SwingUtilities3;
/**
* This class manages repaint requests, allowing the number
@ -303,6 +305,11 @@ public class RepaintManager
*/
public synchronized void addInvalidComponent(JComponent invalidComponent)
{
RepaintManager delegate = getDelegate(invalidComponent);
if (delegate != null) {
delegate.addInvalidComponent(invalidComponent);
return;
}
Component validateRoot = null;
/* Find the first JComponent ancestor of this component whose
@ -373,6 +380,11 @@ public class RepaintManager
* @see #addInvalidComponent
*/
public synchronized void removeInvalidComponent(JComponent component) {
RepaintManager delegate = getDelegate(component);
if (delegate != null) {
delegate.removeInvalidComponent(component);
return;
}
if(invalidComponents != null) {
int index = invalidComponents.indexOf(component);
if(index != -1) {
@ -464,6 +476,11 @@ public class RepaintManager
*/
public void addDirtyRegion(JComponent c, int x, int y, int w, int h)
{
RepaintManager delegate = getDelegate(c);
if (delegate != null) {
delegate.addDirtyRegion(c, x, y, w, h);
return;
}
addDirtyRegion0(c, x, y, w, h);
}
@ -588,6 +605,10 @@ public class RepaintManager
* dirty.
*/
public Rectangle getDirtyRegion(JComponent aComponent) {
RepaintManager delegate = getDelegate(aComponent);
if (delegate != null) {
return delegate.getDirtyRegion(aComponent);
}
Rectangle r = null;
synchronized(this) {
r = (Rectangle)dirtyComponents.get(aComponent);
@ -603,6 +624,11 @@ public class RepaintManager
* completely painted during the next paintDirtyRegions() call.
*/
public void markCompletelyDirty(JComponent aComponent) {
RepaintManager delegate = getDelegate(aComponent);
if (delegate != null) {
delegate.markCompletelyDirty(aComponent);
return;
}
addDirtyRegion(aComponent,0,0,Integer.MAX_VALUE,Integer.MAX_VALUE);
}
@ -611,6 +637,11 @@ public class RepaintManager
* get painted during the next paintDirtyRegions() call.
*/
public void markCompletelyClean(JComponent aComponent) {
RepaintManager delegate = getDelegate(aComponent);
if (delegate != null) {
delegate.markCompletelyClean(aComponent);
return;
}
synchronized(this) {
dirtyComponents.remove(aComponent);
}
@ -623,6 +654,10 @@ public class RepaintManager
* if it return true.
*/
public boolean isCompletelyDirty(JComponent aComponent) {
RepaintManager delegate = getDelegate(aComponent);
if (delegate != null) {
return delegate.isCompletelyDirty(aComponent);
}
Rectangle r;
r = getDirtyRegion(aComponent);
@ -900,6 +935,10 @@ public class RepaintManager
* repaint manager.
*/
public Image getOffscreenBuffer(Component c,int proposedWidth,int proposedHeight) {
RepaintManager delegate = getDelegate(c);
if (delegate != null) {
return delegate.getOffscreenBuffer(c, proposedWidth, proposedHeight);
}
return _getOffscreenBuffer(c, proposedWidth, proposedHeight);
}
@ -917,6 +956,11 @@ public class RepaintManager
*/
public Image getVolatileOffscreenBuffer(Component c,
int proposedWidth,int proposedHeight) {
RepaintManager delegate = getDelegate(c);
if (delegate != null) {
return delegate.getVolatileOffscreenBuffer(c, proposedWidth,
proposedHeight);
}
GraphicsConfiguration config = c.getGraphicsConfiguration();
if (config == null) {
config = GraphicsEnvironment.getLocalGraphicsEnvironment().
@ -1550,4 +1594,11 @@ public class RepaintManager
prePaintDirtyRegions();
}
}
private RepaintManager getDelegate(Component c) {
RepaintManager delegate = SwingUtilities3.getDelegateRepaintManager(c);
if (this == delegate) {
delegate = null;
}
return delegate;
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 1997-2007 Sun Microsystems, Inc. All Rights Reserved.
* Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -974,6 +974,7 @@ public class SwingUtilities implements SwingConstants
boolean textIsEmpty = (text == null) || text.equals("");
int lsb = 0;
int rsb = 0;
/* Unless both text and icon are non-null, we effectively ignore
* the value of textIconGap.
*/
@ -1015,7 +1016,7 @@ public class SwingUtilities implements SwingConstants
if (lsb < 0) {
textR.width -= lsb;
}
int rsb = SwingUtilities2.getRightSideBearing(c, fm, text);
rsb = SwingUtilities2.getRightSideBearing(c, fm, text);
if (rsb > 0) {
textR.width += rsb;
}
@ -1118,6 +1119,11 @@ public class SwingUtilities implements SwingConstants
// lsb is negative. Shift the x location so that the text is
// visually drawn at the right location.
textR.x -= lsb;
textR.width += lsb;
}
if (rsb > 0) {
textR.width -= rsb;
}
return text;

View File

@ -31,6 +31,7 @@ package javax.swing;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.util.concurrent.atomic.AtomicLong;
import sun.awt.AppContext;
@ -52,7 +53,8 @@ class TimerQueue implements Runnable
new StringBuffer("TimerQueue.expiredTimersKey");
private final DelayQueue<DelayedTimer> queue;
volatile boolean running;
private volatile boolean running;
private final Lock runningLock;
/* Lock object used in place of class object for synchronization.
* (4187686)
@ -69,7 +71,8 @@ class TimerQueue implements Runnable
super();
queue = new DelayQueue<DelayedTimer>();
// Now start the TimerQueue thread.
start();
runningLock = new ReentrantLock();
startIfNeeded();
}
@ -87,33 +90,30 @@ class TimerQueue implements Runnable
}
synchronized void start() {
if (running) {
throw new RuntimeException("Can't start a TimerQueue " +
"that is already running");
}
else {
final ThreadGroup threadGroup =
AppContext.getAppContext().getThreadGroup();
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
Thread timerThread = new Thread(threadGroup, TimerQueue.this,
"TimerQueue");
timerThread.setDaemon(true);
timerThread.setPriority(Thread.NORM_PRIORITY);
timerThread.start();
return null;
}
});
running = true;
void startIfNeeded() {
if (! running) {
runningLock.lock();
try {
final ThreadGroup threadGroup =
AppContext.getAppContext().getThreadGroup();
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
Thread timerThread = new Thread(threadGroup, TimerQueue.this,
"TimerQueue");
timerThread.setDaemon(true);
timerThread.setPriority(Thread.NORM_PRIORITY);
timerThread.start();
return null;
}
});
running = true;
} finally {
runningLock.unlock();
}
}
}
synchronized void stop() {
running = false;
}
void addTimer(Timer timer, long delayMillis) {
timer.getLock().lock();
try {
@ -164,6 +164,7 @@ class TimerQueue implements Runnable
public void run() {
runningLock.lock();
try {
while (running) {
try {
@ -195,14 +196,14 @@ class TimerQueue implements Runnable
}
}
catch (ThreadDeath td) {
synchronized (this) {
running = false;
// Mark all the timers we contain as not being queued.
for (DelayedTimer delayedTimer : queue) {
delayedTimer.getTimer().cancelEvent();
}
throw td;
// Mark all the timers we contain as not being queued.
for (DelayedTimer delayedTimer : queue) {
delayedTimer.getTimer().cancelEvent();
}
throw td;
} finally {
running = false;
runningLock.unlock();
}
}

View File

@ -79,10 +79,13 @@ public class CompoundBorder extends AbstractBorder {
}
/**
* Returns whether or not this compound border is opaque.
* Returns true if both the inside and outside borders are
* non-null and opaque; returns false otherwise.
* Returns whether or not the compound border is opaque.
*
* @return {@code true} if the inside and outside borders
* are each either {@code null} or opaque;
* or {@code false} otherwise
*/
@Override
public boolean isBorderOpaque() {
return (outsideBorder == null || outsideBorder.isBorderOpaque()) &&
(insideBorder == null || insideBorder.isBorderOpaque());

View File

@ -160,7 +160,9 @@ public abstract class AbstractColorChooserPanel extends JPanel {
* is editing
*/
public ColorSelectionModel getColorSelectionModel() {
return chooser.getSelectionModel();
return (this.chooser != null)
? this.chooser.getSelectionModel()
: null;
}
/**
@ -168,7 +170,17 @@ public abstract class AbstractColorChooserPanel extends JPanel {
* @return the <code>Color</code> that is selected
*/
protected Color getColorFromModel() {
return getColorSelectionModel().getSelectedColor();
ColorSelectionModel model = getColorSelectionModel();
return (model != null)
? model.getSelectedColor()
: null;
}
void setSelectedColor(Color color) {
ColorSelectionModel model = getColorSelectionModel();
if (model != null) {
model.setSelectedColor(color);
}
}
/**

View File

@ -1,5 +1,5 @@
/*
* Copyright 1998-2001 Sun Microsystems, Inc. All Rights Reserved.
* Copyright 1998-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -25,9 +25,7 @@
package javax.swing.colorchooser;
import javax.swing.*;
import javax.swing.JComponent;
/**
* A class designed to produce preconfigured "accessory" objects to
@ -49,16 +47,17 @@ public class ColorChooserComponentFactory {
private ColorChooserComponentFactory() { } // can't instantiate
public static AbstractColorChooserPanel[] getDefaultChooserPanels() {
AbstractColorChooserPanel[] choosers = { new DefaultSwatchChooserPanel(),
new DefaultHSBChooserPanel(),
new DefaultRGBChooserPanel() };
return choosers;
return new AbstractColorChooserPanel[] {
new DefaultSwatchChooserPanel(),
new ColorChooserPanel(new ColorModelHSV()),
new ColorChooserPanel(new ColorModelHSL()),
new ColorChooserPanel(new ColorModel()),
new ColorChooserPanel(new ColorModelCMYK()),
};
}
public static JComponent getPreviewPanel() {
return new DefaultPreviewPanel();
}
}

View File

@ -0,0 +1,187 @@
/*
* Copyright 2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.swing.colorchooser;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
final class ColorChooserPanel extends AbstractColorChooserPanel implements PropertyChangeListener {
private static final int MASK = 0xFF000000;
private final ColorModel model;
private final ColorPanel panel;
private final DiagramComponent slider;
private final DiagramComponent diagram;
private final JFormattedTextField text;
private final JLabel label;
ColorChooserPanel(ColorModel model) {
this.model = model;
this.panel = new ColorPanel(this.model);
this.slider = new DiagramComponent(this.panel, false);
this.diagram = new DiagramComponent(this.panel, true);
this.text = new JFormattedTextField();
this.label = new JLabel(null, null, SwingConstants.RIGHT);
ValueFormatter.init(6, true, this.text);
}
@Override
public void updateChooser() {
Color color = getColorFromModel();
if (color != null) {
this.panel.setColor(color);
this.text.setValue(Integer.valueOf(color.getRGB()));
this.slider.repaint();
this.diagram.repaint();
}
}
@Override
protected void buildChooser() {
if (0 == getComponentCount()) {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 3;
gbc.gridwidth = 2;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.NORTH;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets.top = 10;
gbc.insets.right = 10;
add(this.panel, gbc);
gbc.gridwidth = 1;
gbc.weightx = 1.0;
gbc.weighty = 0.0;
gbc.anchor = GridBagConstraints.CENTER;
gbc.insets.right = 5;
gbc.insets.bottom = 10;
add(this.label, gbc);
gbc.gridx = 4;
gbc.weightx = 0.0;
gbc.insets.right = 10;
add(this.text, gbc);
gbc.gridx = 2;
gbc.gridheight = 2;
gbc.anchor = GridBagConstraints.NORTH;
gbc.ipadx = this.text.getPreferredSize().height;
gbc.ipady = getPreferredSize().height;
add(this.slider, gbc);
gbc.gridx = 1;
gbc.insets.left = 10;
gbc.ipadx = gbc.ipady;
add(this.diagram, gbc);
this.label.setLabelFor(this.text);
this.text.addPropertyChangeListener("value", this); // NON-NLS: the property name
this.slider.setBorder(this.text.getBorder());
this.diagram.setBorder(this.text.getBorder());
setInheritsPopupMenu(this, true); // CR:4966112
}
String label = this.model.getText(this, "HexCode"); // NON-NLS: suffix
boolean visible = label != null;
this.text.setVisible(visible);
this.label.setVisible(visible);
if (visible) {
this.label.setText(label);
int mnemonic = this.model.getInteger(this, "HexCodeMnemonic"); // NON-NLS: suffix
if (mnemonic > 0) {
this.label.setDisplayedMnemonic(mnemonic);
mnemonic = this.model.getInteger(this, "HexCodeMnemonicIndex"); // NON-NLS: suffix
if (mnemonic >= 0) {
this.label.setDisplayedMnemonicIndex(mnemonic);
}
}
}
this.panel.buildPanel();
}
@Override
public String getDisplayName() {
return this.model.getText(this, "Name"); // NON-NLS: suffix
}
@Override
public int getMnemonic() {
return this.model.getInteger(this, "Mnemonic"); // NON-NLS: suffix
}
@Override
public int getDisplayedMnemonicIndex() {
return this.model.getInteger(this, "DisplayedMnemonicIndex"); // NON-NLS: suffix
}
@Override
public Icon getSmallDisplayIcon() {
return null;
}
@Override
public Icon getLargeDisplayIcon() {
return null;
}
public void propertyChange(PropertyChangeEvent event) {
ColorSelectionModel model = getColorSelectionModel();
if (model != null) {
Object object = event.getNewValue();
if (object instanceof Integer) {
int value = MASK & model.getSelectedColor().getRGB() | (Integer) object;
model.setSelectedColor(new Color(value, true));
}
}
this.text.selectAll();
}
/**
* Allows to show context popup for all components recursively.
*
* @param component the root component of the tree
* @param value whether or not the popup menu is inherited
*/
private static void setInheritsPopupMenu(JComponent component, boolean value) {
component.setInheritsPopupMenu(value);
for (Object object : component.getComponents()) {
if (object instanceof JComponent) {
setInheritsPopupMenu((JComponent) object, value);
}
}
}
}

View File

@ -0,0 +1,102 @@
/*
* Copyright 2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.swing.colorchooser;
import java.awt.Component;
import javax.swing.UIManager;
class ColorModel {
private final String prefix;
private final String[] labels;
ColorModel(String name, String... labels) {
this.prefix = "ColorChooser." + name; // NON-NLS: default prefix
this.labels = labels;
}
ColorModel() {
this("rgb", "Red", "Green", "Blue", "Alpha"); // NON-NLS: components
}
void setColor(int color, float[] model) {
model[0] = normalize(color >> 16);
model[1] = normalize(color >> 8);
model[2] = normalize(color);
model[3] = normalize(color >> 24);
}
int getColor(float[] model) {
return to8bit(model[2]) | (to8bit(model[1]) << 8) | (to8bit(model[0]) << 16) | (to8bit(model[3]) << 24);
}
int getCount() {
return this.labels.length;
}
int getMinimum(int index) {
return 0;
}
int getMaximum(int index) {
return 255;
}
float getDefault(int index) {
return 0.0f;
}
final String getLabel(Component component, int index) {
return getText(component, this.labels[index]);
}
private static float normalize(int value) {
return (float) (value & 0xFF) / 255.0f;
}
private static int to8bit(float value) {
return (int) (255.0f * value);
}
final String getText(Component component, String suffix) {
return UIManager.getString(this.prefix + suffix + "Text", component.getLocale()); // NON-NLS: default postfix
}
final int getInteger(Component component, String suffix) {
Object value = UIManager.get(this.prefix + suffix, component.getLocale());
if (value instanceof Integer) {
return (Integer) value;
}
if (value instanceof String) {
try {
return Integer.parseInt((String) value);
}
catch (NumberFormatException exception) {
}
}
return -1;
}
}

View File

@ -0,0 +1,94 @@
/*
* Copyright 2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.swing.colorchooser;
final class ColorModelCMYK extends ColorModel {
ColorModelCMYK() {
super("cmyk", "Cyan", "Magenta", "Yellow", "Black", "Alpha"); // NON-NLS: components
}
@Override
void setColor(int color, float[] space) {
super.setColor(color, space);
space[4] = space[3];
RGBtoCMYK(space, space);
}
@Override
int getColor(float[] space) {
CMYKtoRGB(space, space);
space[3] = space[4];
return super.getColor(space);
}
/**
* Converts CMYK components of a color to a set of RGB components.
*
* @param cmyk a float array with length equal to
* the number of CMYK components
* @param rgb a float array with length of at least 3
* that contains RGB components of a color
* @return a float array that contains RGB components
*/
private static float[] CMYKtoRGB(float[] cmyk, float[] rgb) {
if (rgb == null) {
rgb = new float[3];
}
rgb[0] = 1.0f + cmyk[0] * cmyk[3] - cmyk[3] - cmyk[0];
rgb[1] = 1.0f + cmyk[1] * cmyk[3] - cmyk[3] - cmyk[1];
rgb[2] = 1.0f + cmyk[2] * cmyk[3] - cmyk[3] - cmyk[2];
return rgb;
}
/**
* Converts RGB components of a color to a set of CMYK components.
*
* @param rgb a float array with length of at least 3
* that contains RGB components of a color
* @param cmyk a float array with length equal to
* the number of CMYK components
* @return a float array that contains CMYK components
*/
private static float[] RGBtoCMYK(float[] rgb, float[] cmyk) {
if (cmyk == null) {
cmyk = new float[4];
}
float max = ColorModelHSL.max(rgb[0], rgb[1], rgb[2]);
if (max > 0.0f) {
cmyk[0] = 1.0f - rgb[0] / max;
cmyk[1] = 1.0f - rgb[1] / max;
cmyk[2] = 1.0f - rgb[2] / max;
}
else {
cmyk[0] = 0.0f;
cmyk[1] = 0.0f;
cmyk[2] = 0.0f;
}
cmyk[3] = 1.0f - max;
return cmyk;
}
}

View File

@ -0,0 +1,188 @@
/*
* Copyright 2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.swing.colorchooser;
final class ColorModelHSL extends ColorModel {
ColorModelHSL() {
super("hsl", "Hue", "Saturation", "Lightness", "Transparency"); // NON-NLS: components
}
@Override
void setColor(int color, float[] space) {
super.setColor(color, space);
RGBtoHSL(space, space);
space[3] = 1.0f - space[3];
}
@Override
int getColor(float[] space) {
space[3] = 1.0f - space[3];
HSLtoRGB(space, space);
return super.getColor(space);
}
@Override
int getMaximum(int index) {
return (index == 0) ? 360 : 100;
}
@Override
float getDefault(int index) {
return (index == 0) ? -1.0f : (index == 2) ? 0.5f : 1.0f;
}
/**
* Converts HSL components of a color to a set of RGB components.
*
* @param hsl a float array with length equal to
* the number of HSL components
* @param rgb a float array with length of at least 3
* that contains RGB components of a color
* @return a float array that contains RGB components
*/
private static float[] HSLtoRGB(float[] hsl, float[] rgb) {
if (rgb == null) {
rgb = new float[3];
}
float hue = hsl[0];
float saturation = hsl[1];
float lightness = hsl[2];
if (saturation > 0.0f) {
hue = (hue < 1.0f) ? hue * 6.0f : 0.0f;
float q = lightness + saturation * ((lightness > 0.5f) ? 1.0f - lightness : lightness);
float p = 2.0f * lightness - q;
rgb[0]= normalize(q, p, (hue < 4.0f) ? (hue + 2.0f) : (hue - 4.0f));
rgb[1]= normalize(q, p, hue);
rgb[2]= normalize(q, p, (hue < 2.0f) ? (hue + 4.0f) : (hue - 2.0f));
}
else {
rgb[0] = lightness;
rgb[1] = lightness;
rgb[2] = lightness;
}
return rgb;
}
/**
* Converts RGB components of a color to a set of HSL components.
*
* @param rgb a float array with length of at least 3
* that contains RGB components of a color
* @param hsl a float array with length equal to
* the number of HSL components
* @return a float array that contains HSL components
*/
private static float[] RGBtoHSL(float[] rgb, float[] hsl) {
if (hsl == null) {
hsl = new float[3];
}
float max = max(rgb[0], rgb[1], rgb[2]);
float min = min(rgb[0], rgb[1], rgb[2]);
float summa = max + min;
float saturation = max - min;
if (saturation > 0.0f) {
saturation /= (summa > 1.0f)
? 2.0f - summa
: summa;
}
hsl[0] = getHue(rgb[0], rgb[1], rgb[2], max, min);
hsl[1] = saturation;
hsl[2] = summa / 2.0f;
return hsl;
}
/**
* Returns the smaller of three color components.
*
* @param red the red component of the color
* @param green the green component of the color
* @param blue the blue component of the color
* @return the smaller of {@code red}, {@code green} and {@code blue}
*/
static float min(float red, float green, float blue) {
float min = (red < green) ? red : green;
return (min < blue) ? min : blue;
}
/**
* Returns the larger of three color components.
*
* @param red the red component of the color
* @param green the green component of the color
* @param blue the blue component of the color
* @return the larger of {@code red}, {@code green} and {@code blue}
*/
static float max(float red, float green, float blue) {
float max = (red > green) ? red : green;
return (max > blue) ? max : blue;
}
/**
* Calculates the hue component for HSL and HSV color spaces.
*
* @param red the red component of the color
* @param green the green component of the color
* @param blue the blue component of the color
* @param max the larger of {@code red}, {@code green} and {@code blue}
* @param min the smaller of {@code red}, {@code green} and {@code blue}
* @return the hue component
*/
static float getHue(float red, float green, float blue, float max, float min) {
float hue = max - min;
if (hue > 0.0f) {
if (max == red) {
hue = (green - blue) / hue;
if (hue < 0.0f) {
hue += 6.0f;
}
}
else if (max == green) {
hue = 2.0f + (blue - red) / hue;
}
else /*max == blue*/ {
hue = 4.0f + (red - green) / hue;
}
hue /= 6.0f;
}
return hue;
}
private static float normalize(float q, float p, float color) {
if (color < 1.0f) {
return p + (q - p) * color;
}
if (color < 3.0f) {
return q;
}
if (color < 4.0f) {
return p + (q - p) * (4.0f - color);
}
return p;
}
}

View File

@ -0,0 +1,138 @@
/*
* Copyright 2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.swing.colorchooser;
final class ColorModelHSV extends ColorModel {
ColorModelHSV() {
super("hsv", "Hue", "Saturation", "Value", "Transparency"); // NON-NLS: components
}
@Override
void setColor(int color, float[] space) {
super.setColor(color, space);
RGBtoHSV(space, space);
space[3] = 1.0f - space[3];
}
@Override
int getColor(float[] space) {
space[3] = 1.0f - space[3];
HSVtoRGB(space, space);
return super.getColor(space);
}
@Override
int getMaximum(int index) {
return (index == 0) ? 360 : 100;
}
@Override
float getDefault(int index) {
return (index == 0) ? -1.0f : 1.0f;
}
/**
* Converts HSV components of a color to a set of RGB components.
*
* @param hsv a float array with length equal to
* the number of HSV components
* @param rgb a float array with length of at least 3
* that contains RGB components of a color
* @return a float array that contains RGB components
*/
private static float[] HSVtoRGB(float[] hsv, float[] rgb) {
if (rgb == null) {
rgb = new float[3];
}
float hue = hsv[0];
float saturation = hsv[1];
float value = hsv[2];
rgb[0] = value;
rgb[1] = value;
rgb[2] = value;
if (saturation > 0.0f) {
hue = (hue < 1.0f) ? hue * 6.0f : 0.0f;
int integer = (int) hue;
float f = hue - (float) integer;
switch (integer) {
case 0:
rgb[1] *= 1.0f - saturation * (1.0f - f);
rgb[2] *= 1.0f - saturation;
break;
case 1:
rgb[0] *= 1.0f - saturation * f;
rgb[2] *= 1.0f - saturation;
break;
case 2:
rgb[0] *= 1.0f - saturation;
rgb[2] *= 1.0f - saturation * (1.0f - f);
break;
case 3:
rgb[0] *= 1.0f - saturation;
rgb[1] *= 1.0f - saturation * f;
break;
case 4:
rgb[0] *= 1.0f - saturation * (1.0f - f);
rgb[1] *= 1.0f - saturation;
break;
case 5:
rgb[1] *= 1.0f - saturation;
rgb[2] *= 1.0f - saturation * f;
break;
}
}
return rgb;
}
/**
* Converts RGB components of a color to a set of HSV components.
*
* @param rgb a float array with length of at least 3
* that contains RGB components of a color
* @param hsv a float array with length equal to
* the number of HSV components
* @return a float array that contains HSV components
*/
private static float[] RGBtoHSV(float[] rgb, float[] hsv) {
if (hsv == null) {
hsv = new float[3];
}
float max = ColorModelHSL.max(rgb[0], rgb[1], rgb[2]);
float min = ColorModelHSL.min(rgb[0], rgb[1], rgb[2]);
float saturation = max - min;
if (saturation > 0.0f) {
saturation /= max;
}
hsv[0] = ColorModelHSL.getHue(rgb[0], rgb[1], rgb[2], max, min);
hsv[1] = saturation;
hsv[2] = max;
return hsv;
}
}

View File

@ -0,0 +1,210 @@
/*
* Copyright 2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.swing.colorchooser;
import java.awt.Color;
import java.awt.ContainerOrderFocusTraversalPolicy;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.EmptyBorder;
final class ColorPanel extends JPanel implements ActionListener {
private final SlidingSpinner[] spinners = new SlidingSpinner[5];
private final float[] values = new float[this.spinners.length];
private final ColorModel model;
private Color color;
private int x = 1;
private int y = 2;
private int z;
ColorPanel(ColorModel model) {
super(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
ButtonGroup group = new ButtonGroup();
EmptyBorder border = null;
for (int i = 0; i < this.spinners.length; i++) {
if (i < 3) {
JRadioButton button = new JRadioButton();
if (i == 0) {
Insets insets = button.getInsets();
insets.left = button.getPreferredSize().width;
border = new EmptyBorder(insets);
button.setSelected(true);
gbc.insets.top = 5;
}
add(button, gbc);
group.add(button);
button.setActionCommand(Integer.toString(i));
button.addActionListener(this);
this.spinners[i] = new SlidingSpinner(this, button);
}
else {
JLabel label = new JLabel();
add(label, gbc);
label.setBorder(border);
label.setFocusable(false);
this.spinners[i] = new SlidingSpinner(this, label);
}
}
gbc.gridx = 2;
gbc.weightx = 1.0;
gbc.insets.top = 0;
gbc.insets.left = 5;
for (SlidingSpinner spinner : this.spinners) {
add(spinner.getSlider(), gbc);
gbc.insets.top = 5;
}
gbc.gridx = 3;
gbc.weightx = 0.0;
gbc.insets.top = 0;
for (SlidingSpinner spinner : this.spinners) {
add(spinner.getSpinner(), gbc);
gbc.insets.top = 5;
}
setFocusTraversalPolicy(new ContainerOrderFocusTraversalPolicy());
setFocusTraversalPolicyProvider(true);
setFocusable(false);
this.model = model;
}
public void actionPerformed(ActionEvent event) {
try {
this.z = Integer.parseInt(event.getActionCommand());
this.y = (this.z != 2) ? 2 : 1;
this.x = (this.z != 0) ? 0 : 1;
getParent().repaint();
}
catch (NumberFormatException exception) {
}
}
void buildPanel() {
int count = this.model.getCount();
this.spinners[4].setVisible(count > 4);
for (int i = 0; i < count; i++) {
Object object = this.spinners[i].getLabel();
if (object instanceof JRadioButton) {
JRadioButton button = (JRadioButton) object;
button.setText(this.model.getLabel(this, i));
}
else if (object instanceof JLabel) {
JLabel label = (JLabel) object;
label.setText(this.model.getLabel(this, i));
}
this.spinners[i].setRange(this.model.getMinimum(i), this.model.getMaximum(i));
this.spinners[i].setValue(this.values[i]);
}
}
void colorChanged() {
this.color = new Color(getColor(0), true);
Object parent = getParent();
if (parent instanceof ColorChooserPanel) {
ColorChooserPanel chooser = (ColorChooserPanel) parent;
chooser.setSelectedColor(this.color);
chooser.repaint();
}
}
float getValueX() {
return this.spinners[this.x].getValue();
}
float getValueY() {
return 1.0f - this.spinners[this.y].getValue();
}
float getValueZ() {
return 1.0f - this.spinners[this.z].getValue();
}
void setValue(float z) {
this.spinners[this.z].setValue(1.0f - z);
colorChanged();
}
void setValue(float x, float y) {
this.spinners[this.x].setValue(x);
this.spinners[this.y].setValue(1.0f - y);
colorChanged();
}
int getColor(float z) {
setDefaultValue(this.x);
setDefaultValue(this.y);
this.values[this.z] = 1.0f - z;
return getColor(3);
}
int getColor(float x, float y) {
this.values[this.x] = x;
this.values[this.y] = 1.0f - y;
setValue(this.z);
return getColor(3);
}
void setColor(Color color) {
if (!color.equals(this.color)) {
this.color = color;
this.model.setColor(color.getRGB(), this.values);
for (int i = 0; i < this.model.getCount(); i++) {
this.spinners[i].setValue(this.values[i]);
}
}
}
private int getColor(int index) {
while (index < this.model.getCount()) {
setValue(index++);
}
return this.model.getColor(this.values);
}
private void setValue(int index) {
this.values[index] = this.spinners[index].getValue();
}
private void setDefaultValue(int index) {
float value = this.model.getDefault(index);
this.values[index] = (value < 0.0f)
? this.spinners[index].getValue()
: value;
}
}

View File

@ -1,801 +0,0 @@
/*
* Copyright 1998-2004 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.swing.colorchooser;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.awt.image.*;
import java.util.Locale;
/**
* Implements the default HSB Color chooser
*
* @author Tom Santos
* @author Steve Wilson
* @author Mark Davidson
* @author Shannon Hickey
*/
class DefaultHSBChooserPanel extends AbstractColorChooserPanel implements ChangeListener, HierarchyListener {
private transient HSBImage palette;
private transient HSBImage sliderPalette;
private transient Image paletteImage;
private transient Image sliderPaletteImage;
private JSlider slider;
private JSpinner hField;
private JSpinner sField;
private JSpinner bField;
private JTextField redField;
private JTextField greenField;
private JTextField blueField;
private boolean isAdjusting = false; // Flag which indicates that values are set internally
private Point paletteSelection = new Point();
private JLabel paletteLabel;
private JLabel sliderPaletteLabel;
private JRadioButton hRadio;
private JRadioButton sRadio;
private JRadioButton bRadio;
private static final int PALETTE_DIMENSION = 200;
private static final int MAX_HUE_VALUE = 359;
private static final int MAX_SATURATION_VALUE = 100;
private static final int MAX_BRIGHTNESS_VALUE = 100;
private int currentMode = HUE_MODE;
private static final int HUE_MODE = 0;
private static final int SATURATION_MODE = 1;
private static final int BRIGHTNESS_MODE = 2;
public DefaultHSBChooserPanel() {
}
private void addPaletteListeners() {
paletteLabel.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e ) {
float[] hsb = new float[3];
palette.getHSBForLocation( e.getX(), e.getY(), hsb );
updateHSB( hsb[0], hsb[1], hsb[2] );
}
});
paletteLabel.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged( MouseEvent e ){
int labelWidth = paletteLabel.getWidth();
int labelHeight = paletteLabel.getHeight();
int x = e.getX();
int y = e.getY();
if ( x >= labelWidth ) {
x = labelWidth - 1;
}
if ( y >= labelHeight ) {
y = labelHeight - 1;
}
if ( x < 0 ) {
x = 0;
}
if ( y < 0 ) {
y = 0;
}
float[] hsb = new float[3];
palette.getHSBForLocation( x, y, hsb );
updateHSB( hsb[0], hsb[1], hsb[2] );
}
});
}
private void updatePalette( float h, float s, float b ) {
int x = 0;
int y = 0;
switch ( currentMode ) {
case HUE_MODE:
if ( h != palette.getHue() ) {
palette.setHue( h );
palette.nextFrame();
}
x = PALETTE_DIMENSION - (int)(s * PALETTE_DIMENSION);
y = PALETTE_DIMENSION - (int)(b * PALETTE_DIMENSION);
break;
case SATURATION_MODE:
if ( s != palette.getSaturation() ) {
palette.setSaturation( s );
palette.nextFrame();
}
x = (int)(h * PALETTE_DIMENSION);
y = PALETTE_DIMENSION - (int)(b * PALETTE_DIMENSION);
break;
case BRIGHTNESS_MODE:
if ( b != palette.getBrightness() ) {
palette.setBrightness( b );
palette.nextFrame();
}
x = (int)(h * PALETTE_DIMENSION);
y = PALETTE_DIMENSION - (int)(s * PALETTE_DIMENSION);
break;
}
paletteSelection.setLocation( x, y );
paletteLabel.repaint();
}
private void updateSlider( float h, float s, float b ) {
// Update the slider palette if necessary.
// When the slider is the hue slider or the hue hasn't changed,
// the hue of the palette will not need to be updated.
if (currentMode != HUE_MODE && h != sliderPalette.getHue() ) {
sliderPalette.setHue( h );
sliderPalette.nextFrame();
}
float value = 0f;
switch ( currentMode ) {
case HUE_MODE:
value = h;
break;
case SATURATION_MODE:
value = s;
break;
case BRIGHTNESS_MODE:
value = b;
break;
}
slider.setValue( Math.round(value * (slider.getMaximum())) );
}
private void updateHSBTextFields( float hue, float saturation, float brightness ) {
int h = Math.round(hue * 359);
int s = Math.round(saturation * 100);
int b = Math.round(brightness * 100);
if (((Integer)hField.getValue()).intValue() != h) {
hField.setValue(new Integer(h));
}
if (((Integer)sField.getValue()).intValue() != s) {
sField.setValue(new Integer(s));
}
if (((Integer)bField.getValue()).intValue() != b) {
bField.setValue(new Integer(b));
}
}
/**
* Updates the values of the RGB fields to reflect the new color change
*/
private void updateRGBTextFields( Color color ) {
redField.setText(String.valueOf(color.getRed()));
greenField.setText(String.valueOf(color.getGreen()));
blueField.setText(String.valueOf(color.getBlue()));
}
/**
* Main internal method of updating the ui controls and the color model.
*/
private void updateHSB( float h, float s, float b ) {
if ( !isAdjusting ) {
isAdjusting = true;
updatePalette( h, s, b );
updateSlider( h, s, b );
updateHSBTextFields( h, s, b );
Color color = Color.getHSBColor(h, s, b);
updateRGBTextFields( color );
getColorSelectionModel().setSelectedColor( color );
isAdjusting = false;
}
}
/**
* Invoked automatically when the model's state changes.
* It is also called by <code>installChooserPanel</code> to allow
* you to set up the initial state of your chooser.
* Override this method to update your <code>ChooserPanel</code>.
*/
public void updateChooser() {
if ( !isAdjusting ) {
float[] hsb = getHSBColorFromModel();
updateHSB( hsb[0], hsb[1], hsb[2] );
}
}
public void installChooserPanel(JColorChooser enclosingChooser) {
super.installChooserPanel(enclosingChooser);
setInheritsPopupMenu(true);
addHierarchyListener(this);
}
/**
* Invoked when the panel is removed from the chooser.
*/
public void uninstallChooserPanel(JColorChooser enclosingChooser) {
super.uninstallChooserPanel(enclosingChooser);
cleanupPalettesIfNecessary();
removeAll();
removeHierarchyListener(this);
}
/**
* Returns an float array containing the HSB values of the selected color from
* the ColorSelectionModel
*/
private float[] getHSBColorFromModel() {
Color color = getColorFromModel();
float[] hsb = new float[3];
Color.RGBtoHSB( color.getRed(), color.getGreen(), color.getBlue(), hsb );
return hsb;
}
/**
* Builds a new chooser panel.
*/
protected void buildChooser() {
setLayout(new BorderLayout());
JComponent spp = buildSliderPalettePanel();
spp.setInheritsPopupMenu(true);
add(spp, BorderLayout.BEFORE_LINE_BEGINS);
JPanel controlHolder = new JPanel(new SmartGridLayout(1,3));
JComponent hsbControls = buildHSBControls();
hsbControls.setInheritsPopupMenu(true);
controlHolder.add(hsbControls);
controlHolder.add(new JLabel(" ")); // spacer
JComponent rgbControls = buildRGBControls();
rgbControls.setInheritsPopupMenu(true);
controlHolder.add(rgbControls);
controlHolder.setInheritsPopupMenu(true);
controlHolder.setBorder(new EmptyBorder( 10, 5, 10, 5));
add( controlHolder, BorderLayout.CENTER);
}
/**
* Creates the panel with the uneditable RGB field
*/
private JComponent buildRGBControls() {
JPanel panel = new JPanel(new SmartGridLayout(2,3));
panel.setInheritsPopupMenu(true);
Color color = getColorFromModel();
redField = new JTextField( String.valueOf(color.getRed()), 3 );
redField.setEditable(false);
redField.setHorizontalAlignment( JTextField.RIGHT );
redField.setInheritsPopupMenu(true);
greenField = new JTextField(String.valueOf(color.getGreen()), 3 );
greenField.setEditable(false);
greenField.setHorizontalAlignment( JTextField.RIGHT );
greenField.setInheritsPopupMenu(true);
blueField = new JTextField( String.valueOf(color.getBlue()), 3 );
blueField.setEditable(false);
blueField.setHorizontalAlignment( JTextField.RIGHT );
blueField.setInheritsPopupMenu(true);
Locale locale = getLocale();
String redString = UIManager.getString("ColorChooser.hsbRedText", locale);
String greenString = UIManager.getString("ColorChooser.hsbGreenText", locale);
String blueString = UIManager.getString("ColorChooser.hsbBlueText", locale);
panel.add( new JLabel(redString) );
panel.add( redField );
panel.add( new JLabel(greenString) );
panel.add( greenField );
panel.add( new JLabel(blueString) );
panel.add( blueField );
return panel;
}
/**
* Creates the panel with the editable HSB fields and the radio buttons.
*/
private JComponent buildHSBControls() {
Locale locale = getLocale();
String hueString = UIManager.getString("ColorChooser.hsbHueText", locale);
String saturationString = UIManager.getString("ColorChooser.hsbSaturationText", locale);
String brightnessString = UIManager.getString("ColorChooser.hsbBrightnessText", locale);
RadioButtonHandler handler = new RadioButtonHandler();
hRadio = new JRadioButton(hueString);
hRadio.addActionListener(handler);
hRadio.setSelected(true);
hRadio.setInheritsPopupMenu(true);
sRadio = new JRadioButton(saturationString);
sRadio.addActionListener(handler);
sRadio.setInheritsPopupMenu(true);
bRadio = new JRadioButton(brightnessString);
bRadio.addActionListener(handler);
bRadio.setInheritsPopupMenu(true);
ButtonGroup group = new ButtonGroup();
group.add(hRadio);
group.add(sRadio);
group.add(bRadio);
float[] hsb = getHSBColorFromModel();
hField = new JSpinner(new SpinnerNumberModel((int)(hsb[0] * 359), 0, 359, 1));
sField = new JSpinner(new SpinnerNumberModel((int)(hsb[1] * 100), 0, 100, 1));
bField = new JSpinner(new SpinnerNumberModel((int)(hsb[2] * 100), 0, 100, 1));
hField.addChangeListener(this);
sField.addChangeListener(this);
bField.addChangeListener(this);
hField.setInheritsPopupMenu(true);
sField.setInheritsPopupMenu(true);
bField.setInheritsPopupMenu(true);
JPanel panel = new JPanel( new SmartGridLayout(2, 3) );
panel.add(hRadio);
panel.add(hField);
panel.add(sRadio);
panel.add(sField);
panel.add(bRadio);
panel.add(bField);
panel.setInheritsPopupMenu(true);
return panel;
}
/**
* Handler for the radio button classes.
*/
private class RadioButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent evt) {
Object obj = evt.getSource();
if (obj instanceof JRadioButton) {
JRadioButton button = (JRadioButton)obj;
if (button == hRadio) {
setMode(HUE_MODE);
} else if (button == sRadio) {
setMode(SATURATION_MODE);
} else if (button == bRadio) {
setMode(BRIGHTNESS_MODE);
}
}
}
}
private void setMode(int mode) {
if (currentMode == mode) {
return;
}
isAdjusting = true; // Ensure no events propagate from changing slider value.
currentMode = mode;
float[] hsb = getHSBColorFromModel();
switch (currentMode) {
case HUE_MODE:
slider.setInverted(true);
slider.setMaximum(MAX_HUE_VALUE);
palette.setValues(HSBImage.HSQUARE, hsb[0], 1.0f, 1.0f);
sliderPalette.setValues(HSBImage.HSLIDER, 0f, 1.0f, 1.0f);
break;
case SATURATION_MODE:
slider.setInverted(false);
slider.setMaximum(MAX_SATURATION_VALUE);
palette.setValues(HSBImage.SSQUARE, hsb[0], hsb[1], 1.0f);
sliderPalette.setValues(HSBImage.SSLIDER, hsb[0], 1.0f, 1.0f);
break;
case BRIGHTNESS_MODE:
slider.setInverted(false);
slider.setMaximum(MAX_BRIGHTNESS_VALUE);
palette.setValues(HSBImage.BSQUARE, hsb[0], 1.0f, hsb[2]);
sliderPalette.setValues(HSBImage.BSLIDER, hsb[0], 1.0f, 1.0f);
break;
}
isAdjusting = false;
palette.nextFrame();
sliderPalette.nextFrame();
updateChooser();
}
protected JComponent buildSliderPalettePanel() {
// This slider has to have a minimum of 0. A lot of math in this file is simplified due to this.
slider = new JSlider(JSlider.VERTICAL, 0, MAX_HUE_VALUE, 0);
slider.setInverted(true);
slider.setPaintTrack(false);
slider.setPreferredSize(new Dimension(slider.getPreferredSize().width, PALETTE_DIMENSION + 15));
slider.addChangeListener(this);
slider.setInheritsPopupMenu(true);
// We're not painting ticks, but need to ask UI classes to
// paint arrow shape anyway, if possible.
slider.putClientProperty("Slider.paintThumbArrowShape", Boolean.TRUE);
paletteLabel = createPaletteLabel();
addPaletteListeners();
sliderPaletteLabel = new JLabel();
JPanel panel = new JPanel();
panel.add( paletteLabel );
panel.add( slider );
panel.add( sliderPaletteLabel );
initializePalettesIfNecessary();
return panel;
}
private void initializePalettesIfNecessary() {
if (palette != null) {
return;
}
float[] hsb = getHSBColorFromModel();
switch(currentMode){
case HUE_MODE:
palette = new HSBImage(HSBImage.HSQUARE, PALETTE_DIMENSION, PALETTE_DIMENSION, hsb[0], 1.0f, 1.0f);
sliderPalette = new HSBImage(HSBImage.HSLIDER, 16, PALETTE_DIMENSION, 0f, 1.0f, 1.0f);
break;
case SATURATION_MODE:
palette = new HSBImage(HSBImage.SSQUARE, PALETTE_DIMENSION, PALETTE_DIMENSION, 1.0f, hsb[1], 1.0f);
sliderPalette = new HSBImage(HSBImage.SSLIDER, 16, PALETTE_DIMENSION, 1.0f, 0f, 1.0f);
break;
case BRIGHTNESS_MODE:
palette = new HSBImage(HSBImage.BSQUARE, PALETTE_DIMENSION, PALETTE_DIMENSION, 1.0f, 1.0f, hsb[2]);
sliderPalette = new HSBImage(HSBImage.BSLIDER, 16, PALETTE_DIMENSION, 1.0f, 1.0f, 0f);
break;
}
paletteImage = Toolkit.getDefaultToolkit().createImage(palette);
sliderPaletteImage = Toolkit.getDefaultToolkit().createImage(sliderPalette);
paletteLabel.setIcon(new ImageIcon(paletteImage));
sliderPaletteLabel.setIcon(new ImageIcon(sliderPaletteImage));
}
private void cleanupPalettesIfNecessary() {
if (palette == null) {
return;
}
palette.aborted = true;
sliderPalette.aborted = true;
palette.nextFrame();
sliderPalette.nextFrame();
palette = null;
sliderPalette = null;
paletteImage = null;
sliderPaletteImage = null;
paletteLabel.setIcon(null);
sliderPaletteLabel.setIcon(null);
}
protected JLabel createPaletteLabel() {
return new JLabel() {
protected void paintComponent( Graphics g ) {
super.paintComponent( g );
g.setColor( Color.white );
g.drawOval( paletteSelection.x - 4, paletteSelection.y - 4, 8, 8 );
}
};
}
public String getDisplayName() {
return UIManager.getString("ColorChooser.hsbNameText", getLocale());
}
/**
* Provides a hint to the look and feel as to the
* <code>KeyEvent.VK</code> constant that can be used as a mnemonic to
* access the panel. A return value <= 0 indicates there is no mnemonic.
* <p>
* The return value here is a hint, it is ultimately up to the look
* and feel to honor the return value in some meaningful way.
* <p>
* This implementation looks up the value from the default
* <code>ColorChooser.hsbMnemonic</code>, or if it
* isn't available (or not an <code>Integer</code>) returns -1.
* The lookup for the default is done through the <code>UIManager</code>:
* <code>UIManager.get("ColorChooser.rgbMnemonic");</code>.
*
* @return KeyEvent.VK constant identifying the mnemonic; <= 0 for no
* mnemonic
* @see #getDisplayedMnemonicIndex
* @since 1.4
*/
public int getMnemonic() {
return getInt("ColorChooser.hsbMnemonic", -1);
}
/**
* Provides a hint to the look and feel as to the index of the character in
* <code>getDisplayName</code> that should be visually identified as the
* mnemonic. The look and feel should only use this if
* <code>getMnemonic</code> returns a value > 0.
* <p>
* The return value here is a hint, it is ultimately up to the look
* and feel to honor the return value in some meaningful way. For example,
* a look and feel may wish to render each
* <code>AbstractColorChooserPanel</code> in a <code>JTabbedPane</code>,
* and further use this return value to underline a character in
* the <code>getDisplayName</code>.
* <p>
* This implementation looks up the value from the default
* <code>ColorChooser.rgbDisplayedMnemonicIndex</code>, or if it
* isn't available (or not an <code>Integer</code>) returns -1.
* The lookup for the default is done through the <code>UIManager</code>:
* <code>UIManager.get("ColorChooser.hsbDisplayedMnemonicIndex");</code>.
*
* @return Character index to render mnemonic for; -1 to provide no
* visual identifier for this panel.
* @see #getMnemonic
* @since 1.4
*/
public int getDisplayedMnemonicIndex() {
return getInt("ColorChooser.hsbDisplayedMnemonicIndex", -1);
}
public Icon getSmallDisplayIcon() {
return null;
}
public Icon getLargeDisplayIcon() {
return null;
}
/**
* Class for the slider and palette images.
*/
class HSBImage extends SyntheticImage {
protected float h = .0f;
protected float s = .0f;
protected float b = .0f;
protected float[] hsb = new float[3];
protected boolean isDirty = true;
protected int cachedY;
protected int cachedColor;
protected int type;
private static final int HSQUARE = 0;
private static final int SSQUARE = 1;
private static final int BSQUARE = 2;
private static final int HSLIDER = 3;
private static final int SSLIDER = 4;
private static final int BSLIDER = 5;
protected HSBImage(int type, int width, int height, float h, float s, float b) {
super(width, height);
setValues(type, h, s, b);
}
public void setValues(int type, float h, float s, float b) {
this.type = type;
cachedY = -1;
cachedColor = 0;
setHue( h );
setSaturation( s );
setBrightness( b );
}
public final void setHue( float hue ) {
h = hue;
}
public final void setSaturation( float saturation ) {
s = saturation;
}
public final void setBrightness( float brightness ) {
b = brightness;
}
public final float getHue() {
return h;
}
public final float getSaturation() {
return s;
}
public final float getBrightness() {
return b;
}
protected boolean isStatic() {
return false;
}
public synchronized void nextFrame() {
isDirty = true;
notifyAll();
}
public synchronized void addConsumer(ImageConsumer ic) {
isDirty = true;
super.addConsumer(ic);
}
private int getRGBForLocation( int x, int y ) {
if (type >= HSLIDER && y == cachedY) {
return cachedColor;
}
getHSBForLocation( x, y, hsb );
cachedY = y;
cachedColor = Color.HSBtoRGB( hsb[0], hsb[1], hsb[2] );
return cachedColor;
}
public void getHSBForLocation( int x, int y, float[] hsbArray ) {
switch (type) {
case HSQUARE: {
float saturationStep = ((float)x) / width;
float brightnessStep = ((float)y) / height;
hsbArray[0] = h;
hsbArray[1] = s - saturationStep;
hsbArray[2] = b - brightnessStep;
break;
}
case SSQUARE: {
float brightnessStep = ((float)y) / height;
float step = 1.0f / ((float)width);
hsbArray[0] = x * step;
hsbArray[1] = s;
hsbArray[2] = 1.0f - brightnessStep;
break;
}
case BSQUARE: {
float saturationStep = ((float)y) / height;
float step = 1.0f / ((float)width);
hsbArray[0] = x * step;
hsbArray[1] = 1.0f - saturationStep;
hsbArray[2] = b;
break;
}
case HSLIDER: {
float step = 1.0f / ((float)height);
hsbArray[0] = y * step;
hsbArray[1] = s;
hsbArray[2] = b;
break;
}
case SSLIDER: {
float saturationStep = ((float)y) / height;
hsbArray[0] = h;
hsbArray[1] = s - saturationStep;
hsbArray[2] = b;
break;
}
case BSLIDER: {
float brightnessStep = ((float)y) / height;
hsbArray[0] = h;
hsbArray[1] = s;
hsbArray[2] = b - brightnessStep;
break;
}
}
}
/**
* Overriden method from SyntheticImage
*/
protected void computeRow( int y, int[] row ) {
if ( y == 0 ) {
synchronized ( this ) {
try {
while ( !isDirty ) {
wait();
}
} catch (InterruptedException ie) {
}
isDirty = false;
}
}
if (aborted) {
return;
}
for ( int i = 0; i < row.length; ++i ) {
row[i] = getRGBForLocation( i, y );
}
}
}
public void stateChanged(ChangeEvent e) {
if (e.getSource() == slider) {
boolean modelIsAdjusting = slider.getModel().getValueIsAdjusting();
if (!modelIsAdjusting && !isAdjusting) {
int sliderValue = slider.getValue();
int sliderRange = slider.getMaximum();
float value = (float)sliderValue / (float)sliderRange;
float[] hsb = getHSBColorFromModel();
switch ( currentMode ){
case HUE_MODE:
updateHSB(value, hsb[1], hsb[2]);
break;
case SATURATION_MODE:
updateHSB(hsb[0], value, hsb[2]);
break;
case BRIGHTNESS_MODE:
updateHSB(hsb[0], hsb[1], value);
break;
}
}
} else if (e.getSource() instanceof JSpinner) {
float hue = ((Integer)hField.getValue()).floatValue() / 359f;
float saturation = ((Integer)sField.getValue()).floatValue() / 100f;
float brightness = ((Integer)bField.getValue()).floatValue() / 100f;
updateHSB(hue, saturation, brightness);
}
}
public void hierarchyChanged(HierarchyEvent he) {
if ((he.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0) {
if (isDisplayable()) {
initializePalettesIfNecessary();
} else {
cleanupPalettesIfNecessary();
}
}
}
}

View File

@ -1,294 +0,0 @@
/*
* Copyright 1998-2004 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.swing.colorchooser;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.util.Locale;
/**
* The standard RGB chooser.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Steve Wilson
* @author Mark Davidson
* @see JColorChooser
* @see AbstractColorChooserPanel
*/
class DefaultRGBChooserPanel extends AbstractColorChooserPanel implements ChangeListener {
protected JSlider redSlider;
protected JSlider greenSlider;
protected JSlider blueSlider;
protected JSpinner redField;
protected JSpinner blueField;
protected JSpinner greenField;
private final int minValue = 0;
private final int maxValue = 255;
private boolean isAdjusting = false; // indicates the fields are being set internally
public DefaultRGBChooserPanel() {
super();
setInheritsPopupMenu(true);
}
/**
* Sets the values of the controls to reflect the color
*/
private void setColor( Color newColor ) {
int red = newColor.getRed();
int blue = newColor.getBlue();
int green = newColor.getGreen();
if (redSlider.getValue() != red) {
redSlider.setValue(red);
}
if (greenSlider.getValue() != green) {
greenSlider.setValue(green);
}
if (blueSlider.getValue() != blue) {
blueSlider.setValue(blue);
}
if (((Integer)redField.getValue()).intValue() != red)
redField.setValue(new Integer(red));
if (((Integer)greenField.getValue()).intValue() != green)
greenField.setValue(new Integer(green));
if (((Integer)blueField.getValue()).intValue() != blue )
blueField.setValue(new Integer(blue));
}
public String getDisplayName() {
return UIManager.getString("ColorChooser.rgbNameText", getLocale());
}
/**
* Provides a hint to the look and feel as to the
* <code>KeyEvent.VK</code> constant that can be used as a mnemonic to
* access the panel. A return value <= 0 indicates there is no mnemonic.
* <p>
* The return value here is a hint, it is ultimately up to the look
* and feel to honor the return value in some meaningful way.
* <p>
* This implementation looks up the value from the default
* <code>ColorChooser.rgbMnemonic</code>, or if it
* isn't available (or not an <code>Integer</code>) returns -1.
* The lookup for the default is done through the <code>UIManager</code>:
* <code>UIManager.get("ColorChooser.rgbMnemonic");</code>.
*
* @return KeyEvent.VK constant identifying the mnemonic; <= 0 for no
* mnemonic
* @see #getDisplayedMnemonicIndex
* @since 1.4
*/
public int getMnemonic() {
return getInt("ColorChooser.rgbMnemonic", -1);
}
/**
* Provides a hint to the look and feel as to the index of the character in
* <code>getDisplayName</code> that should be visually identified as the
* mnemonic. The look and feel should only use this if
* <code>getMnemonic</code> returns a value > 0.
* <p>
* The return value here is a hint, it is ultimately up to the look
* and feel to honor the return value in some meaningful way. For example,
* a look and feel may wish to render each
* <code>AbstractColorChooserPanel</code> in a <code>JTabbedPane</code>,
* and further use this return value to underline a character in
* the <code>getDisplayName</code>.
* <p>
* This implementation looks up the value from the default
* <code>ColorChooser.rgbDisplayedMnemonicIndex</code>, or if it
* isn't available (or not an <code>Integer</code>) returns -1.
* The lookup for the default is done through the <code>UIManager</code>:
* <code>UIManager.get("ColorChooser.rgbDisplayedMnemonicIndex");</code>.
*
* @return Character index to render mnemonic for; -1 to provide no
* visual identifier for this panel.
* @see #getMnemonic
* @since 1.4
*/
public int getDisplayedMnemonicIndex() {
return getInt("ColorChooser.rgbDisplayedMnemonicIndex", -1);
}
public Icon getSmallDisplayIcon() {
return null;
}
public Icon getLargeDisplayIcon() {
return null;
}
/**
* The background color, foreground color, and font are already set to the
* defaults from the defaults table before this method is called.
*/
public void installChooserPanel(JColorChooser enclosingChooser) {
super.installChooserPanel(enclosingChooser);
}
protected void buildChooser() {
Locale locale = getLocale();
String redString = UIManager.getString("ColorChooser.rgbRedText", locale);
String greenString = UIManager.getString("ColorChooser.rgbGreenText", locale);
String blueString = UIManager.getString("ColorChooser.rgbBlueText", locale);
setLayout( new BorderLayout() );
Color color = getColorFromModel();
JPanel enclosure = new JPanel();
enclosure.setLayout( new SmartGridLayout( 3, 3 ) );
enclosure.setInheritsPopupMenu(true);
// The panel that holds the sliders
add( enclosure, BorderLayout.CENTER );
// sliderPanel.setBorder(new LineBorder(Color.black));
// The row for the red value
JLabel l = new JLabel(redString);
l.setDisplayedMnemonic(getInt("ColorChooser.rgbRedMnemonic", -1));
enclosure.add(l);
redSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, color.getRed());
redSlider.setMajorTickSpacing( 85 );
redSlider.setMinorTickSpacing( 17 );
redSlider.setPaintTicks( true );
redSlider.setPaintLabels( true );
redSlider.setInheritsPopupMenu(true);
enclosure.add( redSlider );
redField = new JSpinner(
new SpinnerNumberModel(color.getRed(), minValue, maxValue, 1));
l.setLabelFor(redSlider);
redField.setInheritsPopupMenu(true);
JPanel redFieldHolder = new JPanel(new CenterLayout());
redFieldHolder.setInheritsPopupMenu(true);
redField.addChangeListener(this);
redFieldHolder.add(redField);
enclosure.add(redFieldHolder);
// The row for the green value
l = new JLabel(greenString);
l.setDisplayedMnemonic(getInt("ColorChooser.rgbGreenMnemonic", -1));
enclosure.add(l);
greenSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, color.getGreen());
greenSlider.setMajorTickSpacing( 85 );
greenSlider.setMinorTickSpacing( 17 );
greenSlider.setPaintTicks( true );
greenSlider.setPaintLabels( true );
greenSlider.setInheritsPopupMenu(true);
enclosure.add(greenSlider);
greenField = new JSpinner(
new SpinnerNumberModel(color.getGreen(), minValue, maxValue, 1));
l.setLabelFor(greenSlider);
greenField.setInheritsPopupMenu(true);
JPanel greenFieldHolder = new JPanel(new CenterLayout());
greenFieldHolder.add(greenField);
greenFieldHolder.setInheritsPopupMenu(true);
greenField.addChangeListener(this);
enclosure.add(greenFieldHolder);
// The slider for the blue value
l = new JLabel(blueString);
l.setDisplayedMnemonic(getInt("ColorChooser.rgbBlueMnemonic", -1));
enclosure.add(l);
blueSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, color.getBlue());
blueSlider.setMajorTickSpacing( 85 );
blueSlider.setMinorTickSpacing( 17 );
blueSlider.setPaintTicks( true );
blueSlider.setPaintLabels( true );
blueSlider.setInheritsPopupMenu(true);
enclosure.add(blueSlider);
blueField = new JSpinner(
new SpinnerNumberModel(color.getBlue(), minValue, maxValue, 1));
l.setLabelFor(blueSlider);
blueField.setInheritsPopupMenu(true);
JPanel blueFieldHolder = new JPanel(new CenterLayout());
blueFieldHolder.add(blueField);
blueField.addChangeListener(this);
blueFieldHolder.setInheritsPopupMenu(true);
enclosure.add(blueFieldHolder);
redSlider.addChangeListener( this );
greenSlider.addChangeListener( this );
blueSlider.addChangeListener( this );
redSlider.putClientProperty("JSlider.isFilled", Boolean.TRUE);
greenSlider.putClientProperty("JSlider.isFilled", Boolean.TRUE);
blueSlider.putClientProperty("JSlider.isFilled", Boolean.TRUE);
}
public void uninstallChooserPanel(JColorChooser enclosingChooser) {
super.uninstallChooserPanel(enclosingChooser);
removeAll();
}
public void updateChooser() {
if (!isAdjusting) {
isAdjusting = true;
setColor(getColorFromModel());
isAdjusting = false;
}
}
public void stateChanged( ChangeEvent e ) {
if ( e.getSource() instanceof JSlider && !isAdjusting) {
int red = redSlider.getValue();
int green = greenSlider.getValue();
int blue = blueSlider.getValue() ;
Color color = new Color (red, green, blue);
getColorSelectionModel().setSelectedColor(color);
} else if (e.getSource() instanceof JSpinner && !isAdjusting) {
int red = ((Integer)redField.getValue()).intValue();
int green = ((Integer)greenField.getValue()).intValue();
int blue = ((Integer)blueField.getValue()).intValue();
Color color = new Color (red, green, blue);
getColorSelectionModel().setSelectedColor(color);
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 1998-2005 Sun Microsystems, Inc. All Rights Reserved.
* Copyright 1998-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -213,17 +213,15 @@ class DefaultSwatchChooserPanel extends AbstractColorChooserPanel {
class RecentSwatchListener extends MouseAdapter implements Serializable {
public void mousePressed(MouseEvent e) {
Color color = recentSwatchPanel.getColorForLocation(e.getX(), e.getY());
getColorSelectionModel().setSelectedColor(color);
setSelectedColor(color);
}
}
class MainSwatchListener extends MouseAdapter implements Serializable {
public void mousePressed(MouseEvent e) {
Color color = swatchPanel.getColorForLocation(e.getX(), e.getY());
getColorSelectionModel().setSelectedColor(color);
setSelectedColor(color);
recentSwatchPanel.setMostRecentColor(color);
}
}

View File

@ -0,0 +1,160 @@
/*
* Copyright 2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.swing.colorchooser;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
final class DiagramComponent extends JComponent implements MouseListener, MouseMotionListener {
private final ColorPanel panel;
private final boolean diagram;
private final Insets insets = new Insets(0, 0, 0, 0);
private int width;
private int height;
private int[] array;
private BufferedImage image;
DiagramComponent(ColorPanel panel, boolean diagram) {
this.panel = panel;
this.diagram = diagram;
addMouseListener(this);
addMouseMotionListener(this);
}
@Override
protected void paintComponent(Graphics g) {
getInsets(this.insets);
this.width = getWidth() - this.insets.left - this.insets.right;
this.height = getHeight() - this.insets.top - this.insets.bottom;
boolean update = (this.image == null)
|| (this.width != this.image.getWidth())
|| (this.height != this.image.getHeight());
if (update) {
int size = this.width * this.height;
if ((this.array == null) || (this.array.length < size)) {
this.array = new int[size];
}
this.image = new BufferedImage(this.width, this.height, BufferedImage.TYPE_INT_RGB);
}
{
float dx = 1.0f / (float) (this.width - 1);
float dy = 1.0f / (float) (this.height - 1);
int offset = 0;
float y = 0.0f;
for (int h = 0; h < this.height; h++, y += dy) {
if (this.diagram) {
float x = 0.0f;
for (int w = 0; w < this.width; w++, x += dx, offset++) {
this.array[offset] = this.panel.getColor(x, y);
}
}
else {
int color = this.panel.getColor(y);
for (int w = 0; w < this.width; w++, offset++) {
this.array[offset] = color;
}
}
}
}
this.image.setRGB(0, 0, this.width, this.height, this.array, 0, this.width);
g.drawImage(this.image, this.insets.left, this.insets.top, this.width, this.height, this);
if (isEnabled()) {
this.width--;
this.height--;
g.setXORMode(Color.WHITE);
g.setColor(Color.BLACK);
if (this.diagram) {
int x = getValue(this.panel.getValueX(), this.insets.left, this.width);
int y = getValue(this.panel.getValueY(), this.insets.top, this.height);
g.drawLine(x - 8, y, x + 8, y);
g.drawLine(x, y - 8, x, y + 8);
}
else {
int z = getValue(this.panel.getValueZ(), this.insets.top, this.height);
g.drawLine(this.insets.left, z, this.insets.left + this.width, z);
}
g.setPaintMode();
}
}
public void mousePressed(MouseEvent event) {
mouseDragged(event);
}
public void mouseReleased(MouseEvent event) {
}
public void mouseClicked(MouseEvent event) {
}
public void mouseEntered(MouseEvent event) {
}
public void mouseExited(MouseEvent event) {
}
public void mouseMoved(MouseEvent event) {
}
public void mouseDragged(MouseEvent event) {
if (isEnabled()) {
float y = getValue(event.getY(), this.insets.top, this.height);
if (this.diagram) {
float x = getValue(event.getX(), this.insets.left, this.width);
this.panel.setValue(x, y);
}
else {
this.panel.setValue(y);
}
}
}
private static int getValue(float value, int min, int max) {
return min + (int) (value * (float) (max));
}
private static float getValue(int value, int min, int max) {
if (min < value) {
value -= min;
return (value < max)
? (float) value / (float) max
: 1.0f;
}
return 0.0f;
}
}

View File

@ -0,0 +1,118 @@
/*
* Copyright 2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.swing.colorchooser;
import javax.swing.JComponent;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JSpinner.DefaultEditor;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
final class SlidingSpinner implements ChangeListener {
private final ColorPanel panel;
private final JComponent label;
private final SpinnerNumberModel model = new SpinnerNumberModel();
private final JSlider slider = new JSlider();
private final JSpinner spinner = new JSpinner(this.model);
private float value;
private boolean internal;
SlidingSpinner(ColorPanel panel, JComponent label) {
this.panel = panel;
this.label = label;
this.slider.addChangeListener(this);
this.spinner.addChangeListener(this);
DefaultEditor editor = (DefaultEditor) this.spinner.getEditor();
ValueFormatter.init(3, false, editor.getTextField());
editor.setFocusable(false);
this.spinner.setFocusable(false);
}
JComponent getLabel() {
return this.label;
}
JSlider getSlider() {
return this.slider;
}
JSpinner getSpinner() {
return this.spinner;
}
float getValue() {
return this.value;
}
void setValue(float value) {
int min = this.slider.getMinimum();
int max = this.slider.getMaximum();
this.internal = true;
this.slider.setValue(min + (int) (value * (float) (max - min)));
this.spinner.setValue(Integer.valueOf(this.slider.getValue()));
this.internal = false;
this.value = value;
}
void setRange(int min, int max) {
this.internal = true;
this.slider.setMinimum(min);
this.slider.setMaximum(max);
this.model.setMinimum(Integer.valueOf(min));
this.model.setMaximum(Integer.valueOf(max));
this.internal = false;
}
void setVisible(boolean visible) {
this.label.setVisible(visible);
this.slider.setVisible(visible);
this.spinner.setVisible(visible);
}
public void stateChanged(ChangeEvent event) {
if (!this.internal) {
if (this.spinner == event.getSource()) {
Object value = this.spinner.getValue();
if (value instanceof Integer) {
this.internal = true;
this.slider.setValue((Integer) value);
this.internal = false;
}
}
int value = this.slider.getValue();
this.internal = true;
this.spinner.setValue(Integer.valueOf(value));
this.internal = false;
int min = this.slider.getMinimum();
int max = this.slider.getMaximum();
this.value = (float) (value - min) / (float) (max - min);
this.panel.colorChanged();
}
}
}

View File

@ -1,166 +0,0 @@
/*
* Copyright 1997-2003 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.swing.colorchooser;
import java.awt.*;
import java.awt.image.*;
/** A helper class to make computing synthetic images a little easier.
* All you need to do is define a subclass that overrides computeRow
* to compute a row of the image. It is passed the y coordinate of the
* row and an array into which to put the pixels in
* <a href="http://java.sun.com/products/jdk/1.1/docs/api/java.awt.image.ColorModel.html#getRGBdefault()">
* standard ARGB format</a>.
* <p>Normal usage looks something like this:
* <pre>&nbsp;Image i = createImage(new SyntheticImage(200, 100) {
* &nbsp; protected void computeRow(int y, int[] row) {
* &nbsp; for(int i = width; --i>=0; ) {
* &nbsp; int grey = i*255/(width-1);
* &nbsp; row[i] = (255<<24)|(grey<<16)|(grey<<8)|grey;
* &nbsp; }
* &nbsp; }
* &nbsp;}
* </pre>This creates a image 200 pixels wide and 100 pixels high
* that is a horizontal grey ramp, going from black on the left to
* white on the right.
* <p>
* If the image is to be a movie, override isStatic to return false,
* <i>y</i> cycling back to 0 is computeRow's signal that the next
* frame has started. It is acceptable (expected?) for computeRow(0,r)
* to pause until the appropriate time to start the next frame.
*
* @author James Gosling
*/
abstract class SyntheticImage implements ImageProducer {
private SyntheticImageGenerator root;
protected int width=10, height=100;
static final ColorModel cm = ColorModel.getRGBdefault();
public static final int pixMask = 0xFF;
private Thread runner;
protected SyntheticImage() { }
protected SyntheticImage(int w, int h) { width = w; height = h; }
protected void computeRow(int y, int[] row) {
int p = 255-255*y/(height-1);
p = (pixMask<<24)|(p<<16)|(p<<8)|p;
for (int i = row.length; --i>=0; ) row[i] = p;
}
public synchronized void addConsumer(ImageConsumer ic){
for (SyntheticImageGenerator ics = root; ics != null; ics = ics.next)
if (ics.ic == ic) return;
root = new SyntheticImageGenerator(ic, root, this);
}
public synchronized boolean isConsumer(ImageConsumer ic){
for (SyntheticImageGenerator ics = root; ics != null; ics = ics.next)
if (ics.ic == ic) return true;
return false;
}
public synchronized void removeConsumer(ImageConsumer ic) {
SyntheticImageGenerator prev = null;
for (SyntheticImageGenerator ics = root; ics != null; ics = ics.next) {
if (ics.ic == ic) {
ics.useful = false;
if (prev!=null) prev.next = ics.next;
else root = ics.next;
return;
}
prev = ics;
}
}
public synchronized void startProduction(ImageConsumer ic) {
addConsumer(ic);
for (SyntheticImageGenerator ics = root; ics != null; ics = ics.next)
if (ics.useful && !ics.isAlive())
ics.start();
}
protected boolean isStatic() { return true; }
public void nextFrame(int param) {}//Override if !isStatic
public void requestTopDownLeftRightResend(ImageConsumer ic){}
protected volatile boolean aborted = false;
}
class SyntheticImageGenerator extends Thread {
ImageConsumer ic;
boolean useful;
SyntheticImageGenerator next;
SyntheticImage parent;
SyntheticImageGenerator(ImageConsumer ic, SyntheticImageGenerator next,
SyntheticImage parent) {
super("SyntheticImageGenerator");
this.ic = ic;
this.next = next;
this.parent = parent;
useful = true;
setDaemon(true);
}
public void run() {
ImageConsumer ic = this.ic;
int w = parent.width;
int h = parent.height;
int hints = ic.SINGLEPASS|ic.COMPLETESCANLINES|ic.TOPDOWNLEFTRIGHT;
if (parent.isStatic())
hints |= ic.SINGLEFRAME;
ic.setHints(hints);
ic.setDimensions(w, h);
ic.setProperties(null);
ic.setColorModel(parent.cm);
if (useful) {
int[] row=new int[w];
doPrivileged( new Runnable() {
public void run() {
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
}
});
do {
for (int y = 0; y<h && useful; y++) {
parent.computeRow(y,row);
if (parent.aborted) {
ic.imageComplete(ic.IMAGEABORTED);
return;
}
ic.setPixels(0, y, w, 1, parent.cm, row, 0, w);
}
ic.imageComplete(parent.isStatic() ? ic.STATICIMAGEDONE
: ic.SINGLEFRAMEDONE );
} while(!parent.isStatic() && useful);
}
}
private final static void doPrivileged(final Runnable doRun) {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
doRun.run();
return null;
}
}
);
}
}

View File

@ -0,0 +1,151 @@
/*
* Copyright 2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.swing.colorchooser;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.text.ParseException;
import static java.util.Locale.ENGLISH;
import javax.swing.JFormattedTextField;
import javax.swing.JFormattedTextField.AbstractFormatter;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.DocumentFilter;
final class ValueFormatter extends AbstractFormatter implements FocusListener, Runnable {
static void init(int length, boolean hex, JFormattedTextField text) {
ValueFormatter formatter = new ValueFormatter(length, hex);
text.setColumns(length);
text.setFormatterFactory(new DefaultFormatterFactory(formatter));
text.setHorizontalAlignment(SwingConstants.RIGHT);
text.setMinimumSize(text.getPreferredSize());
text.addFocusListener(formatter);
}
private final DocumentFilter filter = new DocumentFilter() {
@Override
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
if (isValid(fb.getDocument().getLength() - length)) {
fb.remove(offset, length);
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet set) throws BadLocationException {
if (isValid(fb.getDocument().getLength() + text.length() - length) && isValid(text)) {
fb.replace(offset, length, text.toUpperCase(ENGLISH), set);
}
}
@Override
public void insertString(FilterBypass fb, int offset, String text, AttributeSet set) throws BadLocationException {
if (isValid(fb.getDocument().getLength() + text.length()) && isValid(text)) {
fb.insertString(offset, text.toUpperCase(ENGLISH), set);
}
}
};
private final int length;
private final int radix;
private JFormattedTextField text;
ValueFormatter(int length, boolean hex) {
this.length = length;
this.radix = hex ? 16 : 10;
}
@Override
public Object stringToValue(String text) throws ParseException {
try {
return Integer.valueOf(text, this.radix);
}
catch (NumberFormatException nfe) {
ParseException pe = new ParseException("illegal format", 0);
pe.initCause(nfe);
throw pe;
}
}
@Override
public String valueToString(Object object) throws ParseException {
if (object instanceof Integer) {
if (this.radix == 10) {
return object.toString();
}
int value = (Integer) object;
int index = this.length;
char[] array = new char[index];
while (0 < index--) {
array[index] = Character.forDigit(value & 0x0F, this.radix);
value >>= 4;
}
return new String(array).toUpperCase(ENGLISH);
}
throw new ParseException("illegal object", 0);
}
@Override
protected DocumentFilter getDocumentFilter() {
return this.filter;
}
public void focusGained(FocusEvent event) {
Object source = event.getSource();
if (source instanceof JFormattedTextField) {
this.text = (JFormattedTextField) source;
SwingUtilities.invokeLater(this);
}
}
public void focusLost(FocusEvent event) {
}
public void run() {
if (this.text != null) {
this.text.selectAll();
}
}
private boolean isValid(int length) {
return (0 <= length) && (length <= this.length);
}
private boolean isValid(String text) {
int length = text.length();
for (int i = 0; i < length; i++) {
char ch = text.charAt(i);
if (Character.digit(ch, this.radix) < 0) {
return false;
}
}
return true;
}
}

View File

@ -165,7 +165,7 @@ public class BasicButtonListener implements MouseListener, MouseMotionListener,
JRootPane root = b.getRootPane();
if (root != null) {
BasicButtonUI ui = (BasicButtonUI)BasicLookAndFeel.getUIOfType(
((AbstractButton)b).getUI(), BasicButtonUI.class);
b.getUI(), BasicButtonUI.class);
if (ui != null && DefaultLookup.getBoolean(b, ui,
ui.getPropertyPrefix() +
"defaultButtonFollowsFocus", true)) {
@ -185,7 +185,7 @@ public class BasicButtonListener implements MouseListener, MouseMotionListener,
JButton initialDefault = (JButton)root.getClientProperty("initialDefaultButton");
if (b != initialDefault) {
BasicButtonUI ui = (BasicButtonUI)BasicLookAndFeel.getUIOfType(
((AbstractButton)b).getUI(), BasicButtonUI.class);
b.getUI(), BasicButtonUI.class);
if (ui != null && DefaultLookup.getBoolean(b, ui,
ui.getPropertyPrefix() +
"defaultButtonFollowsFocus", true)) {
@ -239,7 +239,7 @@ public class BasicButtonListener implements MouseListener, MouseMotionListener,
}
}
}
};
}
public void mouseReleased(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
@ -253,7 +253,7 @@ public class BasicButtonListener implements MouseListener, MouseMotionListener,
model.setPressed(false);
model.setArmed(false);
}
};
}
public void mouseEntered(MouseEvent e) {
AbstractButton b = (AbstractButton) e.getSource();
@ -263,7 +263,7 @@ public class BasicButtonListener implements MouseListener, MouseMotionListener,
}
if (model.isPressed())
model.setArmed(true);
};
}
public void mouseExited(MouseEvent e) {
AbstractButton b = (AbstractButton) e.getSource();
@ -272,7 +272,7 @@ public class BasicButtonListener implements MouseListener, MouseMotionListener,
model.setRollover(false);
}
model.setArmed(false);
};
}
/**

View File

@ -237,7 +237,7 @@ public class BasicButtonUI extends ButtonUI{
/* the fallback icon should be based on the selected state */
if (model.isSelected()) {
selectedIcon = (Icon) b.getSelectedIcon();
selectedIcon = b.getSelectedIcon();
if (selectedIcon != null) {
icon = selectedIcon;
}
@ -245,31 +245,31 @@ public class BasicButtonUI extends ButtonUI{
if(!model.isEnabled()) {
if(model.isSelected()) {
tmpIcon = (Icon) b.getDisabledSelectedIcon();
tmpIcon = b.getDisabledSelectedIcon();
if (tmpIcon == null) {
tmpIcon = selectedIcon;
}
}
if (tmpIcon == null) {
tmpIcon = (Icon) b.getDisabledIcon();
tmpIcon = b.getDisabledIcon();
}
} else if(model.isPressed() && model.isArmed()) {
tmpIcon = (Icon) b.getPressedIcon();
tmpIcon = b.getPressedIcon();
if(tmpIcon != null) {
// revert back to 0 offset
clearTextShiftOffset();
}
} else if(b.isRolloverEnabled() && model.isRollover()) {
if(model.isSelected()) {
tmpIcon = (Icon) b.getRolloverSelectedIcon();
tmpIcon = b.getRolloverSelectedIcon();
if (tmpIcon == null) {
tmpIcon = selectedIcon;
}
}
if (tmpIcon == null) {
tmpIcon = (Icon) b.getRolloverIcon();
tmpIcon = b.getRolloverIcon();
}
}
@ -451,9 +451,9 @@ public class BasicButtonUI extends ButtonUI{
MouseMotionListener[] listeners = b.getMouseMotionListeners();
if (listeners != null) {
for (int counter = 0; counter < listeners.length; counter++) {
if (listeners[counter] instanceof BasicButtonListener) {
return (BasicButtonListener)listeners[counter];
for (MouseMotionListener listener : listeners) {
if (listener instanceof BasicButtonListener) {
return (BasicButtonListener) listener;
}
}
}

View File

@ -299,8 +299,10 @@ public class BasicColorChooserUI extends ColorChooserUI
tabbedPane.addTab(name, centerWrapper);
if (mnemonic > 0) {
tabbedPane.setMnemonicAt(i, mnemonic);
tabbedPane.setDisplayedMnemonicIndexAt(
i, newPanels[i].getDisplayedMnemonicIndex());
int index = newPanels[i].getDisplayedMnemonicIndex();
if (index >= 0) {
tabbedPane.setDisplayedMnemonicIndexAt(i, index);
}
}
}
}

View File

@ -92,7 +92,7 @@ public class BasicComboBoxEditor implements ComboBoxEditor,FocusListener {
return oldValue;
} else {
// Must take the value from the editor and get the value and cast it to the new type.
Class cls = oldValue.getClass();
Class<?> cls = oldValue.getClass();
try {
Method method = cls.getMethod("valueOf", new Class[]{String.class});
newValue = method.invoke(oldValue, new Object[] { editor.getText()});

View File

@ -1509,15 +1509,21 @@ public class BasicComboBoxUI extends ComboBoxUI {
|| ui.isTableCellEditor) {
Object listItem = ui.popup.getList().getSelectedValue();
if (listItem != null) {
comboBox.getModel().setSelectedItem(listItem);
// Ensure that JComboBox.actionPerformed()
// doesn't set editor value as selected item
// Use the selected value from popup
// to set the selected item in combo box,
// but ensure before that JComboBox.actionPerformed()
// won't use editor's value to set the selected item
comboBox.getEditor().setItem(listItem);
comboBox.setSelectedItem(listItem);
}
}
comboBox.setPopupVisible(false);
}
else {
// Hide combo box if it is a table cell editor
if (ui.isTableCellEditor && !comboBox.isEditable()) {
comboBox.setSelectedItem(comboBox.getSelectedItem());
}
// Call the default button binding.
// This is a pretty messy way of passing an event through
// to the root pane.

View File

@ -1,5 +1,5 @@
/*
* Copyright 1997-2003 Sun Microsystems, Inc. All Rights Reserved.
* Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -47,6 +47,7 @@ public class BasicDesktopIconUI extends DesktopIconUI {
protected JInternalFrame.JDesktopIcon desktopIcon;
protected JInternalFrame frame;
private DesktopIconMover desktopIconMover;
/**
* The title pane component used in the desktop icon.
@ -127,12 +128,21 @@ public class BasicDesktopIconUI extends DesktopIconUI {
mouseInputListener = createMouseInputListener();
desktopIcon.addMouseMotionListener(mouseInputListener);
desktopIcon.addMouseListener(mouseInputListener);
getDesktopIconMover().installListeners();
}
protected void uninstallListeners() {
desktopIcon.removeMouseMotionListener(mouseInputListener);
desktopIcon.removeMouseListener(mouseInputListener);
mouseInputListener = null;
getDesktopIconMover().uninstallListeners();
}
private DesktopIconMover getDesktopIconMover() {
if (desktopIconMover == null) {
desktopIconMover = new DesktopIconMover(desktopIcon);
}
return desktopIconMover;
}
protected void installDefaults() {

View File

@ -43,10 +43,10 @@ public class BasicDirectoryModel extends AbstractListModel implements PropertyCh
private JFileChooser filechooser = null;
// PENDING(jeff) pick the size more sensibly
private Vector fileCache = new Vector(50);
private Vector<File> fileCache = new Vector<File>(50);
private LoadFilesThread loadThread = null;
private Vector files = null;
private Vector directories = null;
private Vector<File> files = null;
private Vector<File> directories = null;
private int fetchID = 0;
private PropertyChangeSupport changeSupport;
@ -106,14 +106,14 @@ public class BasicDirectoryModel extends AbstractListModel implements PropertyCh
if (files != null) {
return files;
}
files = new Vector();
directories = new Vector();
files = new Vector<File>();
directories = new Vector<File>();
directories.addElement(filechooser.getFileSystemView().createFileObject(
filechooser.getCurrentDirectory(), "..")
);
for (int i = 0; i < getSize(); i++) {
File f = (File)fileCache.get(i);
File f = fileCache.get(i);
if (filechooser.isTraversable(f)) {
directories.add(f);
} else {
@ -215,7 +215,7 @@ public class BasicDirectoryModel extends AbstractListModel implements PropertyCh
class LoadFilesThread extends Thread {
File currentDirectory = null;
int fid;
Vector runnables = new Vector(10);
Vector<DoChangeContents> runnables = new Vector<DoChangeContents>(10);
public LoadFilesThread(File currentDirectory, int fid) {
super("Basic L&F File Loading Thread");
@ -223,7 +223,7 @@ public class BasicDirectoryModel extends AbstractListModel implements PropertyCh
this.fid = fid;
}
private void invokeLater(Runnable runnable) {
private void invokeLater(DoChangeContents runnable) {
runnables.addElement(runnable);
SwingUtilities.invokeLater(runnable);
}
@ -245,9 +245,9 @@ public class BasicDirectoryModel extends AbstractListModel implements PropertyCh
}
// run through the file list, add directories and selectable files to fileCache
for (int i = 0; i < list.length; i++) {
if(filechooser.accept(list[i])) {
acceptsList.addElement(list[i]);
for (File file : list) {
if (filechooser.accept(file)) {
acceptsList.addElement(file);
}
}
@ -258,11 +258,11 @@ public class BasicDirectoryModel extends AbstractListModel implements PropertyCh
// First sort alphabetically by filename
sort(acceptsList);
Vector newDirectories = new Vector(50);
Vector newFiles = new Vector();
Vector<File> newDirectories = new Vector<File>(50);
Vector<File> newFiles = new Vector<File>();
// run through list grabbing directories in chunks of ten
for(int i = 0; i < acceptsList.size(); i++) {
File f = (File) acceptsList.elementAt(i);
File f = acceptsList.elementAt(i);
boolean isTraversable = filechooser.isTraversable(f);
if (isTraversable) {
newDirectories.addElement(f);
@ -274,7 +274,7 @@ public class BasicDirectoryModel extends AbstractListModel implements PropertyCh
}
}
Vector newFileCache = new Vector(newDirectories);
Vector<File> newFileCache = new Vector<File>(newDirectories);
newFileCache.addAll(newFiles);
int newSize = newFileCache.size();
@ -320,7 +320,7 @@ public class BasicDirectoryModel extends AbstractListModel implements PropertyCh
if(isInterrupted()) {
return;
}
invokeLater(new DoChangeContents(null, 0, new Vector(fileCache.subList(start, end)),
invokeLater(new DoChangeContents(null, 0, new Vector<File>(fileCache.subList(start, end)),
start, fid));
newFileCache = null;
}
@ -334,9 +334,9 @@ public class BasicDirectoryModel extends AbstractListModel implements PropertyCh
}
public void cancelRunnables(Vector runnables) {
for(int i = 0; i < runnables.size(); i++) {
((DoChangeContents)runnables.elementAt(i)).cancel();
public void cancelRunnables(Vector<DoChangeContents> runnables) {
for (DoChangeContents runnable : runnables) {
runnable.cancel();
}
}
@ -449,15 +449,14 @@ public class BasicDirectoryModel extends AbstractListModel implements PropertyCh
class DoChangeContents implements Runnable {
private List addFiles;
private List remFiles;
private List<File> addFiles;
private List<File> remFiles;
private boolean doFire = true;
private int fid;
private int addStart = 0;
private int remStart = 0;
private int change;
public DoChangeContents(List addFiles, int addStart, List remFiles, int remStart, int fid) {
public DoChangeContents(List<File> addFiles, int addStart, List<File> remFiles, int remStart, int fid) {
this.addFiles = addFiles;
this.addStart = addStart;
this.remFiles = remFiles;

View File

@ -159,9 +159,9 @@ public class BasicFileChooserUI extends FileChooserUI {
}
public void uninstallUI(JComponent c) {
uninstallListeners((JFileChooser) filechooser);
uninstallComponents((JFileChooser) filechooser);
uninstallDefaults((JFileChooser) filechooser);
uninstallListeners(filechooser);
uninstallComponents(filechooser);
uninstallDefaults(filechooser);
if(accessoryPanel != null) {
accessoryPanel.removeAll();
@ -506,9 +506,9 @@ public class BasicFileChooserUI extends FileChooserUI {
setDirectorySelected(true);
setDirectory(((File)objects[0]));
} else {
ArrayList fList = new ArrayList(objects.length);
for (int i = 0; i < objects.length; i++) {
File f = (File)objects[i];
ArrayList<File> fList = new ArrayList<File>(objects.length);
for (Object object : objects) {
File f = (File) object;
boolean isDir = f.isDirectory();
if ((chooser.isFileSelectionEnabled() && !isDir)
|| (chooser.isDirectorySelectionEnabled()
@ -518,7 +518,7 @@ public class BasicFileChooserUI extends FileChooserUI {
}
}
if (fList.size() > 0) {
files = (File[])fList.toArray(new File[fList.size()]);
files = fList.toArray(new File[fList.size()]);
}
setDirectorySelected(false);
}
@ -853,7 +853,7 @@ public class BasicFileChooserUI extends FileChooserUI {
}
if (chooser.isMultiSelectionEnabled() && filename.startsWith("\"")) {
ArrayList fList = new ArrayList();
ArrayList<File> fList = new ArrayList<File>();
filename = filename.substring(1);
if (filename.endsWith("\"")) {
@ -889,7 +889,7 @@ public class BasicFileChooserUI extends FileChooserUI {
fList.add(file);
} while (filename.length() > 0);
if (fList.size() > 0) {
selectedFiles = (File[])fList.toArray(new File[fList.size()]);
selectedFiles = fList.toArray(new File[fList.size()]);
}
resetGlobFilter();
} else {
@ -1213,7 +1213,7 @@ public class BasicFileChooserUI extends FileChooserUI {
}
public Icon getCachedIcon(File f) {
return (Icon) iconCache.get(f);
return iconCache.get(f);
}
public void cacheIcon(File f, Icon i) {
@ -1296,8 +1296,7 @@ public class BasicFileChooserUI extends FileChooserUI {
htmlBuf.append("<html>\n<body>\n<ul>\n");
for (int i = 0; i < values.length; i++) {
Object obj = values[i];
for (Object obj : values) {
String val = ((obj == null) ? "" : obj.toString());
plainBuf.append(val + "\n");
htmlBuf.append(" <li>" + val + "\n");
@ -1337,9 +1336,9 @@ public class BasicFileChooserUI extends FileChooserUI {
*/
protected Object getRicherData(DataFlavor flavor) {
if (DataFlavor.javaFileListFlavor.equals(flavor)) {
ArrayList files = new ArrayList();
for (int i = 0; i < fileData.length; i++) {
files.add(fileData[i]);
ArrayList<Object> files = new ArrayList<Object>();
for (Object file : this.fileData) {
files.add(file);
}
return files;
}

View File

@ -266,7 +266,7 @@ public class BasicGraphicsUtils
return null;
}
Icon icon = (Icon) b.getIcon();
Icon icon = b.getIcon();
String text = b.getText();
Font font = b.getFont();
@ -277,7 +277,7 @@ public class BasicGraphicsUtils
Rectangle viewR = new Rectangle(Short.MAX_VALUE, Short.MAX_VALUE);
SwingUtilities.layoutCompoundLabel(
(JComponent) b, fm, text, icon,
b, fm, text, icon,
b.getVerticalAlignment(), b.getHorizontalAlignment(),
b.getVerticalTextPosition(), b.getHorizontalTextPosition(),
viewR, iconR, textR, (text == null ? 0 : textIconGap)

View File

@ -86,6 +86,7 @@ public class BasicInternalFrameTitlePane extends JComponent
protected Action moveAction;
protected Action sizeAction;
// These constants are not used in JDK code
protected static final String CLOSE_CMD =
UIManager.getString("InternalFrameTitlePane.closeButtonText");
protected static final String ICONIFY_CMD =
@ -268,18 +269,18 @@ public class BasicInternalFrameTitlePane extends JComponent
}
protected void addSystemMenuItems(JMenu systemMenu) {
JMenuItem mi = (JMenuItem)systemMenu.add(restoreAction);
JMenuItem mi = systemMenu.add(restoreAction);
mi.setMnemonic('R');
mi = (JMenuItem)systemMenu.add(moveAction);
mi = systemMenu.add(moveAction);
mi.setMnemonic('M');
mi = (JMenuItem)systemMenu.add(sizeAction);
mi = systemMenu.add(sizeAction);
mi.setMnemonic('S');
mi = (JMenuItem)systemMenu.add(iconifyAction);
mi = systemMenu.add(iconifyAction);
mi.setMnemonic('n');
mi = (JMenuItem)systemMenu.add(maximizeAction);
mi = systemMenu.add(maximizeAction);
mi.setMnemonic('x');
systemMenu.add(new JSeparator());
mi = (JMenuItem)systemMenu.add(closeAction);
mi = systemMenu.add(closeAction);
mi.setMnemonic('C');
}
@ -413,7 +414,7 @@ public class BasicInternalFrameTitlePane extends JComponent
// PropertyChangeListener
//
public void propertyChange(PropertyChangeEvent evt) {
String prop = (String)evt.getPropertyName();
String prop = evt.getPropertyName();
if (prop == JInternalFrame.IS_SELECTED_PROPERTY) {
repaint();
@ -428,19 +429,19 @@ public class BasicInternalFrameTitlePane extends JComponent
}
if ("closable" == prop) {
if ((Boolean)evt.getNewValue() == Boolean.TRUE) {
if (evt.getNewValue() == Boolean.TRUE) {
add(closeButton);
} else {
remove(closeButton);
}
} else if ("maximizable" == prop) {
if ((Boolean)evt.getNewValue() == Boolean.TRUE) {
if (evt.getNewValue() == Boolean.TRUE) {
add(maxButton);
} else {
remove(maxButton);
}
} else if ("iconable" == prop) {
if ((Boolean)evt.getNewValue() == Boolean.TRUE) {
if (evt.getNewValue() == Boolean.TRUE) {
add(iconButton);
} else {
remove(iconButton);
@ -600,7 +601,8 @@ public class BasicInternalFrameTitlePane extends JComponent
*/
public class CloseAction extends AbstractAction {
public CloseAction() {
super(CLOSE_CMD);
super(UIManager.getString(
"InternalFrameTitlePane.closeButtonText"));
}
public void actionPerformed(ActionEvent e) {
@ -616,7 +618,8 @@ public class BasicInternalFrameTitlePane extends JComponent
*/
public class MaximizeAction extends AbstractAction {
public MaximizeAction() {
super(MAXIMIZE_CMD);
super(UIManager.getString(
"InternalFrameTitlePane.maximizeButtonText"));
}
public void actionPerformed(ActionEvent evt) {
@ -644,7 +647,8 @@ public class BasicInternalFrameTitlePane extends JComponent
*/
public class IconifyAction extends AbstractAction {
public IconifyAction() {
super(ICONIFY_CMD);
super(UIManager.getString(
"InternalFrameTitlePane.minimizeButtonText"));
}
public void actionPerformed(ActionEvent e) {
@ -664,7 +668,8 @@ public class BasicInternalFrameTitlePane extends JComponent
*/
public class RestoreAction extends AbstractAction {
public RestoreAction() {
super(RESTORE_CMD);
super(UIManager.getString(
"InternalFrameTitlePane.restoreButtonText"));
}
public void actionPerformed(ActionEvent evt) {
@ -690,7 +695,8 @@ public class BasicInternalFrameTitlePane extends JComponent
*/
public class MoveAction extends AbstractAction {
public MoveAction() {
super(MOVE_CMD);
super(UIManager.getString(
"InternalFrameTitlePane.moveButtonText"));
}
public void actionPerformed(ActionEvent e) {
@ -723,7 +729,8 @@ public class BasicInternalFrameTitlePane extends JComponent
*/
public class SizeAction extends AbstractAction {
public SizeAction() {
super(SIZE_CMD);
super(UIManager.getString(
"InternalFrameTitlePane.sizeButtonText"));
}
public void actionPerformed(ActionEvent e) {
@ -774,7 +781,7 @@ public class BasicInternalFrameTitlePane extends JComponent
}
}
public boolean isFocusTraversable() { return false; }
public void requestFocus() {};
public void requestFocus() {}
public AccessibleContext getAccessibleContext() {
AccessibleContext ac = super.getAccessibleContext();
if (uiKey != null) {
@ -783,6 +790,6 @@ public class BasicInternalFrameTitlePane extends JComponent
}
return ac;
}
}; // end NoFocusButton
} // end NoFocusButton
} // End Title Pane Class

View File

@ -1,5 +1,5 @@
/*
* Copyright 1997-2006 Sun Microsystems, Inc. All Rights Reserved.
* Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -55,7 +55,6 @@ public class BasicInternalFrameUI extends InternalFrameUI
protected MouseInputAdapter borderListener;
protected PropertyChangeListener propertyChangeListener;
protected LayoutManager internalFrameLayout;
protected ComponentListener componentListener;
protected MouseInputListener glassPaneDispatcher;
private InternalFrameListener internalFrameListener;
@ -67,9 +66,9 @@ public class BasicInternalFrameUI extends InternalFrameUI
protected BasicInternalFrameTitlePane titlePane; // access needs this
private static DesktopManager sharedDesktopManager;
private boolean componentListenerAdded = false;
private Rectangle parentBounds;
private DesktopIconMover desktopIconMover;
private boolean dragging = false;
private boolean resizing = false;
@ -210,14 +209,17 @@ public class BasicInternalFrameUI extends InternalFrameUI
frame.getGlassPane().addMouseListener(glassPaneDispatcher);
frame.getGlassPane().addMouseMotionListener(glassPaneDispatcher);
}
componentListener = createComponentListener();
if (frame.getParent() != null) {
parentBounds = frame.getParent().getBounds();
}
if ((frame.getParent() != null) && !componentListenerAdded) {
frame.getParent().addComponentListener(componentListener);
componentListenerAdded = true;
getDesktopIconMover().installListeners();
}
private DesktopIconMover getDesktopIconMover() {
if (desktopIconMover == null) {
desktopIconMover = new DesktopIconMover(frame);
}
return desktopIconMover;
}
// Provide a FocusListener to listen for a WINDOW_LOST_FOCUS event,
@ -288,11 +290,7 @@ public class BasicInternalFrameUI extends InternalFrameUI
* @since 1.3
*/
protected void uninstallListeners() {
if ((frame.getParent() != null) && componentListenerAdded) {
frame.getParent().removeComponentListener(componentListener);
componentListenerAdded = false;
}
componentListener = null;
getDesktopIconMover().uninstallListeners();
if (glassPaneDispatcher != null) {
frame.getGlassPane().removeMouseListener(glassPaneDispatcher);
frame.getGlassPane().removeMouseMotionListener(glassPaneDispatcher);
@ -320,7 +318,7 @@ public class BasicInternalFrameUI extends InternalFrameUI
if (resizing) {
return;
}
Cursor s = (Cursor)frame.getLastCursor();
Cursor s = frame.getLastCursor();
if (s == null) {
s = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
}
@ -338,13 +336,13 @@ public class BasicInternalFrameUI extends InternalFrameUI
public Dimension getPreferredSize(JComponent x) {
if((JComponent)frame == x)
if(frame == x)
return frame.getLayout().preferredLayoutSize(x);
return new Dimension(100, 100);
}
public Dimension getMinimumSize(JComponent x) {
if((JComponent)frame == x) {
if(frame == x) {
return frame.getLayout().minimumLayoutSize(x);
}
return new Dimension(0, 0);
@ -1095,7 +1093,7 @@ public class BasicInternalFrameUI extends InternalFrameUI
updateFrameCursor();
}
}; /// End BorderListener Class
} /// End BorderListener Class
protected class ComponentHandler implements ComponentListener {
// NOTE: This class exists only for backward compatability. All
@ -1198,7 +1196,6 @@ public class BasicInternalFrameUI extends InternalFrameUI
}
}
private static boolean isDragging = false;
private class Handler implements ComponentListener, InternalFrameListener,
LayoutManager, MouseInputListener, PropertyChangeListener,
WindowFocusListener, SwingConstants {
@ -1230,15 +1227,6 @@ public class BasicInternalFrameUI extends InternalFrameUI
}
}
// Relocate the icon base on the new parent bounds.
if (icon != null) {
Rectangle iconBounds = icon.getBounds();
int y = iconBounds.y +
(parentNewBounds.height - parentBounds.height);
icon.setBounds(iconBounds.x, y,
iconBounds.width, iconBounds.height);
}
// Update the new parent bounds for next resize.
if (!parentBounds.equals(parentNewBounds)) {
parentBounds = parentNewBounds;
@ -1384,9 +1372,6 @@ public class BasicInternalFrameUI extends InternalFrameUI
// MouseInputListener
private Component mouseEventTarget = null;
private Component dragSource = null;
public void mousePressed(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
@ -1403,7 +1388,7 @@ public class BasicInternalFrameUI extends InternalFrameUI
// PropertyChangeListener
public void propertyChange(PropertyChangeEvent evt) {
String prop = (String)evt.getPropertyName();
String prop = evt.getPropertyName();
JInternalFrame f = (JInternalFrame)evt.getSource();
Object newValue = evt.getNewValue();
Object oldValue = evt.getOldValue();
@ -1413,10 +1398,6 @@ public class BasicInternalFrameUI extends InternalFrameUI
// Cancel a resize in progress if the internal frame
// gets a setClosed(true) or dispose().
cancelResize();
if ((frame.getParent() != null) && componentListenerAdded) {
frame.getParent().removeComponentListener(
componentListener);
}
closeFrame(f);
}
} else if (JInternalFrame.IS_MAXIMUM_PROPERTY == prop) {
@ -1449,16 +1430,6 @@ public class BasicInternalFrameUI extends InternalFrameUI
} else {
parentBounds = null;
}
if ((frame.getParent() != null) && !componentListenerAdded) {
f.getParent().addComponentListener(componentListener);
componentListenerAdded = true;
} else if ((newValue == null) && componentListenerAdded) {
if (f.getParent() != null) {
f.getParent().removeComponentListener(
componentListener);
}
componentListenerAdded = false;
}
} else if (JInternalFrame.TITLE_PROPERTY == prop ||
prop == "closable" || prop == "iconable" ||
prop == "maximizable") {

View File

@ -65,6 +65,9 @@ public class BasicLabelUI extends LabelUI implements PropertyChangeListener
protected static BasicLabelUI labelUI = new BasicLabelUI();
private final static BasicLabelUI SAFE_BASIC_LABEL_UI = new BasicLabelUI();
private Rectangle paintIconR = new Rectangle();
private Rectangle paintTextR = new Rectangle();
static void loadActionMap(LazyActionMap map) {
map.put(new Actions(Actions.PRESS));
map.put(new Actions(Actions.RELEASE));
@ -135,17 +138,6 @@ public class BasicLabelUI extends LabelUI implements PropertyChangeListener
textX, textY);
}
/* These rectangles/insets are allocated once for this shared LabelUI
* implementation. Re-using rectangles rather than allocating
* them in each paint call halved the time it took paint to run.
*/
private static Rectangle paintIconR = new Rectangle();
private static Rectangle paintTextR = new Rectangle();
private static Rectangle paintViewR = new Rectangle();
private static Insets paintViewInsets = new Insets(0, 0, 0, 0);
/**
* Paint the label text in the foreground color, if the label
* is opaque then paint the entire background with the background
@ -194,10 +186,11 @@ public class BasicLabelUI extends LabelUI implements PropertyChangeListener
private String layout(JLabel label, FontMetrics fm,
int width, int height) {
Insets insets = label.getInsets(paintViewInsets);
Insets insets = label.getInsets(null);
String text = label.getText();
Icon icon = (label.isEnabled()) ? label.getIcon() :
label.getDisabledIcon();
Rectangle paintViewR = new Rectangle();
paintViewR.x = insets.left;
paintViewR.y = insets.top;
paintViewR.width = width - (insets.left + insets.right);
@ -208,24 +201,13 @@ public class BasicLabelUI extends LabelUI implements PropertyChangeListener
paintTextR);
}
/* These rectangles/insets are allocated once for this shared LabelUI
* implementation. Re-using rectangles rather than allocating
* them in each getPreferredSize call sped up the method substantially.
*/
private static Rectangle iconR = new Rectangle();
private static Rectangle textR = new Rectangle();
private static Rectangle viewR = new Rectangle();
private static Insets viewInsets = new Insets(0, 0, 0, 0);
public Dimension getPreferredSize(JComponent c)
{
JLabel label = (JLabel)c;
String text = label.getText();
Icon icon = (label.isEnabled()) ? label.getIcon() :
label.getDisabledIcon();
Insets insets = label.getInsets(viewInsets);
Insets insets = label.getInsets(null);
Font font = label.getFont();
int dx = insets.left + insets.right;
@ -242,6 +224,9 @@ public class BasicLabelUI extends LabelUI implements PropertyChangeListener
}
else {
FontMetrics fm = label.getFontMetrics(font);
Rectangle iconR = new Rectangle();
Rectangle textR = new Rectangle();
Rectangle viewR = new Rectangle();
iconR.x = iconR.y = iconR.width = iconR.height = 0;
textR.x = textR.y = textR.width = textR.height = 0;

View File

@ -2102,8 +2102,6 @@ public abstract class BasicLookAndFeel extends LookAndFeel implements Serializab
* <code>soundFile</code> passed into this method, it will
* return <code>null</code>.
*
* @param baseClass used as the root class/location to get the
* soundFile from
* @param soundFile the name of the audio file to be retrieved
* from disk
* @return A byte[] with audio data or null
@ -2120,9 +2118,9 @@ public abstract class BasicLookAndFeel extends LookAndFeel implements Serializab
* Class.getResourceAsStream just returns raw
* bytes, which we can convert to a sound.
*/
byte[] buffer = (byte[])AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
byte[] buffer = AccessController.doPrivileged(
new PrivilegedAction<byte[]>() {
public byte[] run() {
try {
InputStream resource = BasicLookAndFeel.this.
getClass().getResourceAsStream(soundFile);
@ -2184,9 +2182,9 @@ public abstract class BasicLookAndFeel extends LookAndFeel implements Serializab
UIManager.get("AuditoryCues.playList");
if (audioStrings != null) {
// create a HashSet to help us decide to play or not
HashSet audioCues = new HashSet();
for (int i = 0; i < audioStrings.length; i++) {
audioCues.add(audioStrings[i]);
HashSet<Object> audioCues = new HashSet<Object>();
for (Object audioString : audioStrings) {
audioCues.add(audioString);
}
// get the name of the Action
String actionName = (String)audioAction.getValue(Action.NAME);
@ -2237,7 +2235,7 @@ public abstract class BasicLookAndFeel extends LookAndFeel implements Serializab
* This class contains listener that watches for all the mouse
* events that can possibly invoke popup on the component
*/
class AWTEventHelper implements AWTEventListener,PrivilegedAction {
class AWTEventHelper implements AWTEventListener,PrivilegedAction<Object> {
AWTEventHelper() {
super();
AccessController.doPrivileged(this);

View File

@ -123,9 +123,9 @@ public class BasicMenuUI extends BasicMenuItemUI
InputMap windowInputMap = SwingUtilities.getUIInputMap(
menuItem, JComponent.WHEN_IN_FOCUSED_WINDOW);
if (lastMnemonic != 0 && windowInputMap != null) {
for (int i=0; i<shortcutKeys.length; i++) {
for (int shortcutKey : shortcutKeys) {
windowInputMap.remove(KeyStroke.getKeyStroke
(lastMnemonic, shortcutKeys[i], false));
(lastMnemonic, shortcutKey, false));
}
}
if (mnemonic != 0) {
@ -135,10 +135,9 @@ public class BasicMenuUI extends BasicMenuItemUI
SwingUtilities.replaceUIInputMap(menuItem, JComponent.
WHEN_IN_FOCUSED_WINDOW, windowInputMap);
}
for (int i=0; i<shortcutKeys.length; i++) {
for (int shortcutKey : shortcutKeys) {
windowInputMap.put(KeyStroke.getKeyStroke(mnemonic,
shortcutKeys[i], false),
"selectMenu");
shortcutKey, false), "selectMenu");
}
}
lastMnemonic = mnemonic;
@ -264,14 +263,14 @@ public class BasicMenuUI extends BasicMenuItemUI
if(subElements.length > 0) {
me = new MenuElement[4];
me[0] = (MenuElement) cnt;
me[1] = (MenuElement) menu;
me[2] = (MenuElement) menu.getPopupMenu();
me[1] = menu;
me[2] = menu.getPopupMenu();
me[3] = subElements[0];
} else {
me = new MenuElement[3];
me[0] = (MenuElement)cnt;
me[1] = menu;
me[2] = (MenuElement) menu.getPopupMenu();
me[2] = menu.getPopupMenu();
}
defaultManager.setSelectedPath(me);
}
@ -606,7 +605,7 @@ public class BasicMenuUI extends BasicMenuItemUI
MenuSelectionManager manager = e.getMenuSelectionManager();
if (key == Character.toLowerCase(e.getKeyChar())) {
JPopupMenu popupMenu = ((JMenu)menuItem).getPopupMenu();
ArrayList newList = new ArrayList(Arrays.asList(path));
ArrayList<MenuElement> newList = new ArrayList<MenuElement>(Arrays.asList(path));
newList.add(popupMenu);
MenuElement subs[] = popupMenu.getSubElements();
MenuElement sub =
@ -614,8 +613,8 @@ public class BasicMenuUI extends BasicMenuItemUI
if(sub != null) {
newList.add(sub);
}
MenuElement newPath[] = new MenuElement[0];;
newPath = (MenuElement[]) newList.toArray(newPath);
MenuElement newPath[] = new MenuElement[0];
newPath = newList.toArray(newPath);
manager.setSelectedPath(newPath);
e.consume();
} else if (((JMenu)menuItem).isTopLevelMenu()

View File

@ -109,7 +109,7 @@ public class BasicOptionPaneUI extends OptionPaneUI {
static {
newline = (String)java.security.AccessController.doPrivileged(
newline = java.security.AccessController.doPrivileged(
new GetPropertyAction("line.separator"));
if (newline == null) {
newline = "\n";
@ -262,7 +262,7 @@ public class BasicOptionPaneUI extends OptionPaneUI {
* <code>getMinimumOptionPaneSize</code>.
*/
public Dimension getPreferredSize(JComponent c) {
if ((JOptionPane)c == optionPane) {
if (c == optionPane) {
Dimension ourMin = getMinimumOptionPaneSize();
LayoutManager lm = c.getLayout();
@ -366,8 +366,8 @@ public class BasicOptionPaneUI extends OptionPaneUI {
} else if (msg instanceof Object[]) {
Object [] msgs = (Object[]) msg;
for (int i = 0; i < msgs.length; i++) {
addMessageComponents(container, cons, msgs[i], maxll, false);
for (Object o : msgs) {
addMessageComponents(container, cons, o, maxll, false);
}
} else if (msg instanceof Icon) {
@ -381,7 +381,7 @@ public class BasicOptionPaneUI extends OptionPaneUI {
if (len <= 0) {
return;
}
int nl = -1;
int nl;
int nll = 0;
if ((nl = s.indexOf(newline)) >= 0) {
@ -1320,7 +1320,7 @@ public class BasicOptionPaneUI extends OptionPaneUI {
else if (changeName == "componentOrientation") {
ComponentOrientation o = (ComponentOrientation)e.getNewValue();
JOptionPane op = (JOptionPane)e.getSource();
if (o != (ComponentOrientation)e.getOldValue()) {
if (o != e.getOldValue()) {
op.applyComponentOrientation(o);
}
}
@ -1418,7 +1418,7 @@ public class BasicOptionPaneUI extends OptionPaneUI {
}
JButton createButton() {
JButton button = null;
JButton button;
if (minimumWidth > 0) {
button = new ConstrainedButton(text, minimumWidth);

View File

@ -225,14 +225,14 @@ public class BasicPopupMenuUI extends PopupMenuUI {
return popup;
}
static List getPopups() {
static List<JPopupMenu> getPopups() {
MenuSelectionManager msm = MenuSelectionManager.defaultManager();
MenuElement[] p = msm.getSelectedPath();
List list = new ArrayList(p.length);
for(int i = 0; i < p.length; i++) {
if (p[i] instanceof JPopupMenu) {
list.add((JPopupMenu)p[i]);
List<JPopupMenu> list = new ArrayList<JPopupMenu>(p.length);
for (MenuElement element : p) {
if (element instanceof JPopupMenu) {
list.add((JPopupMenu) element);
}
}
return list;
@ -290,14 +290,14 @@ public class BasicPopupMenuUI extends PopupMenuUI {
MenuElement subitem = findEnabledChild(
subpopup.getSubElements(), -1, true);
ArrayList lst = new ArrayList(Arrays.asList(e.getPath()));
ArrayList<MenuElement> lst = new ArrayList<MenuElement>(Arrays.asList(e.getPath()));
lst.add(menuToOpen);
lst.add(subpopup);
if (subitem != null) {
lst.add(subitem);
}
MenuElement newPath[] = new MenuElement[0];;
newPath = (MenuElement[])lst.toArray(newPath);
MenuElement newPath[] = new MenuElement[0];
newPath = lst.toArray(newPath);
MenuSelectionManager.defaultManager().setSelectedPath(newPath);
e.consume();
}
@ -345,7 +345,7 @@ public class BasicPopupMenuUI extends PopupMenuUI {
}
if (matches == 0) {
; // no op
// no op
} else if (matches == 1) {
// Invoke the menu action
JMenuItem item = (JMenuItem)items[firstMatch];
@ -362,7 +362,7 @@ public class BasicPopupMenuUI extends PopupMenuUI {
// Select the menu item with the matching mnemonic. If
// the same mnemonic has been invoked then select the next
// menu item in the cycle.
MenuElement newItem = null;
MenuElement newItem;
newItem = items[indexes[(currentIndex + 1) % matches]];
@ -372,7 +372,6 @@ public class BasicPopupMenuUI extends PopupMenuUI {
manager.setSelectedPath(newPath);
e.consume();
}
return;
}
public void menuKeyReleased(MenuKeyEvent e) {
@ -625,7 +624,7 @@ public class BasicPopupMenuUI extends PopupMenuUI {
// 4234793: This action should call JPopupMenu.firePopupMenuCanceled but it's
// a protected method. The real solution could be to make
// firePopupMenuCanceled public and call it directly.
JPopupMenu lastPopup = (JPopupMenu)getLastPopup();
JPopupMenu lastPopup = getLastPopup();
if (lastPopup != null) {
lastPopup.putClientProperty("JPopupMenu.firePopupMenuCanceled", Boolean.TRUE);
}
@ -703,7 +702,7 @@ public class BasicPopupMenuUI extends PopupMenuUI {
static MenuElement findEnabledChild(MenuElement e[], int fromIndex,
boolean forward) {
MenuElement result = null;
MenuElement result;
if (forward) {
result = nextEnabledChild(e, fromIndex+1, e.length-1);
if (result == null) result = nextEnabledChild(e, 0, fromIndex-1);
@ -752,7 +751,7 @@ public class BasicPopupMenuUI extends PopupMenuUI {
// A grab needs to be added
final Toolkit tk = Toolkit.getDefaultToolkit();
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
new java.security.PrivilegedAction<Object>() {
public Object run() {
tk.addAWTEventListener(MouseGrabber.this,
AWTEvent.MOUSE_EVENT_MASK |
@ -785,7 +784,7 @@ public class BasicPopupMenuUI extends PopupMenuUI {
final Toolkit tk = Toolkit.getDefaultToolkit();
// The grab should be removed
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
new java.security.PrivilegedAction<Object>() {
public Object run() {
tk.removeAWTEventListener(MouseGrabber.this);
return null;
@ -911,10 +910,8 @@ public class BasicPopupMenuUI extends PopupMenuUI {
// 4234793: This action should call firePopupMenuCanceled but it's
// a protected method. The real solution could be to make
// firePopupMenuCanceled public and call it directly.
List popups = getPopups();
Iterator iter = popups.iterator();
while (iter.hasNext()) {
JPopupMenu popup = (JPopupMenu) iter.next();
List<JPopupMenu> popups = getPopups();
for (JPopupMenu popup : popups) {
popup.putClientProperty("JPopupMenu.firePopupMenuCanceled", Boolean.TRUE);
}
MenuSelectionManager.defaultManager().clearSelectedPath();

View File

@ -150,15 +150,15 @@ public class BasicRadioButtonUI extends BasicToggleButtonUI
}
} else if(model.isSelected()) {
if(b.isRolloverEnabled() && model.isRollover()) {
altIcon = (Icon) b.getRolloverSelectedIcon();
altIcon = b.getRolloverSelectedIcon();
if (altIcon == null) {
altIcon = (Icon) b.getSelectedIcon();
altIcon = b.getSelectedIcon();
}
} else {
altIcon = (Icon) b.getSelectedIcon();
altIcon = b.getSelectedIcon();
}
} else if(b.isRolloverEnabled() && model.isRollover()) {
altIcon = (Icon) b.getRolloverIcon();
altIcon = b.getRolloverIcon();
}
if(altIcon == null) {
@ -214,7 +214,7 @@ public class BasicRadioButtonUI extends BasicToggleButtonUI
String text = b.getText();
Icon buttonIcon = (Icon) b.getIcon();
Icon buttonIcon = b.getIcon();
if(buttonIcon == null) {
buttonIcon = getDefaultIcon();
}

View File

@ -106,13 +106,13 @@ public class BasicSplitPaneUI extends SplitPaneUI
* Keys to use for forward focus traversal when the JComponent is
* managing focus.
*/
private static Set managingFocusForwardTraversalKeys;
private static Set<KeyStroke> managingFocusForwardTraversalKeys;
/**
* Keys to use for backward focus traversal when the JComponent is
* managing focus.
*/
private static Set managingFocusBackwardTraversalKeys;
private static Set<KeyStroke> managingFocusBackwardTraversalKeys;
/**
@ -370,7 +370,7 @@ public class BasicSplitPaneUI extends SplitPaneUI
// focus forward traversal key
if (managingFocusForwardTraversalKeys==null) {
managingFocusForwardTraversalKeys = new HashSet();
managingFocusForwardTraversalKeys = new HashSet<KeyStroke>();
managingFocusForwardTraversalKeys.add(
KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));
}
@ -378,7 +378,7 @@ public class BasicSplitPaneUI extends SplitPaneUI
managingFocusForwardTraversalKeys);
// focus backward traversal key
if (managingFocusBackwardTraversalKeys==null) {
managingFocusBackwardTraversalKeys = new HashSet();
managingFocusBackwardTraversalKeys = new HashSet<KeyStroke>();
managingFocusBackwardTraversalKeys.add(
KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK));
}
@ -2170,7 +2170,7 @@ public class BasicSplitPaneUI extends SplitPaneUI
Component focusOn = (direction > 0) ?
policy.getComponentAfter(rootAncestor, splitPane) :
policy.getComponentBefore(rootAncestor, splitPane);
HashSet focusFrom = new HashSet();
HashSet<Component> focusFrom = new HashSet<Component>();
if (splitPane.isAncestorOf(focusOn)) {
do {
focusFrom.add(focusOn);
@ -2212,7 +2212,7 @@ public class BasicSplitPaneUI extends SplitPaneUI
private Component getNextSide(JSplitPane splitPane, Component focus) {
Component left = splitPane.getLeftComponent();
Component right = splitPane.getRightComponent();
Component next = null;
Component next;
if (focus!=null && SwingUtilities.isDescendingFrom(focus, left) &&
right!=null) {
next = getFirstAvailableComponent(right);

View File

@ -142,9 +142,9 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants {
private Component visibleComponent;
// PENDING(api): See comment for ContainerHandler
private Vector htmlViews;
private Vector<View> htmlViews;
private Hashtable mnemonicToIndexMap;
private Hashtable<Integer, Integer> mnemonicToIndexMap;
/**
* InputMap used for mnemonics. Only non-null if the JTabbedPane has
@ -546,7 +546,7 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants {
* Installs the state needed for mnemonics.
*/
private void initMnemonics() {
mnemonicToIndexMap = new Hashtable();
mnemonicToIndexMap = new Hashtable<Integer, Integer>();
mnemonicInputMap = new ComponentInputMapUIResource(tabPane);
mnemonicInputMap.setParent(SwingUtilities.getUIInputMap(tabPane,
JComponent.WHEN_IN_FOCUSED_WINDOW));
@ -909,10 +909,10 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants {
private static final int CROP_SEGMENT = 12;
private static Polygon createCroppedTabShape(int tabPlacement, Rectangle tabRect, int cropline) {
int rlen = 0;
int start = 0;
int end = 0;
int ostart = 0;
int rlen;
int start;
int end;
int ostart;
switch(tabPlacement) {
case LEFT:
@ -1014,7 +1014,7 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants {
tabPane.putClientProperty("html", v);
}
SwingUtilities.layoutCompoundLabel((JComponent) tabPane,
SwingUtilities.layoutCompoundLabel(tabPane,
metrics, title, icon,
SwingUtilities.CENTER,
SwingUtilities.CENTER,
@ -1694,7 +1694,7 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants {
*/
protected View getTextViewForTab(int tabIndex) {
if (htmlViews != null) {
return (View)htmlViews.elementAt(tabIndex);
return htmlViews.elementAt(tabIndex);
}
return null;
}
@ -2230,8 +2230,7 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants {
if (mnemonic >= 'a' && mnemonic <='z') {
mnemonic -= ('a' - 'A');
}
Integer index = (Integer)ui.mnemonicToIndexMap.
get(Integer.valueOf(mnemonic));
Integer index = ui.mnemonicToIndexMap.get(Integer.valueOf(mnemonic));
if (index != null && pane.isEnabledAt(index.intValue())) {
pane.setSelectedIndex(index.intValue());
}
@ -2292,8 +2291,7 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants {
for (int i = 0; i < tabPane.getTabCount(); i++) {
Component component = tabPane.getComponentAt(i);
if (component != null) {
Dimension size = zeroSize;
size = minimum? component.getMinimumSize() :
Dimension size = minimum ? component.getMinimumSize() :
component.getPreferredSize();
if (size != null) {
@ -2305,7 +2303,7 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants {
// Add content border insets to minimum size
width += cWidth;
height += cHeight;
int tabExtent = 0;
int tabExtent;
// Calculate how much space the tabs will need, based on the
// minimum size required to display largest child + content border
@ -3143,7 +3141,7 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants {
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
int fontHeight = metrics.getHeight();
int selectedIndex = tabPane.getSelectedIndex();
int i, j;
int i;
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
boolean leftToRight = BasicGraphicsUtils.isLeftToRight(tabPane);
int x = tabAreaInsets.left;
@ -3433,10 +3431,10 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants {
}
public String toString() {
return new String("viewport.viewSize="+viewport.getViewSize()+"\n"+
return "viewport.viewSize=" + viewport.getViewSize() + "\n" +
"viewport.viewRectangle="+viewport.getViewRect()+"\n"+
"leadingTabIndex="+leadingTabIndex+"\n"+
"tabViewPosition="+tabViewPosition);
"tabViewPosition=" + tabViewPosition;
}
}
@ -3788,8 +3786,8 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants {
}
}
private Vector createHTMLVector() {
Vector htmlViews = new Vector();
private Vector<View> createHTMLVector() {
Vector<View> htmlViews = new Vector<View>();
int count = tabPane.getTabCount();
if (count>0) {
for (int i=0 ; i<count; i++) {

View File

@ -526,16 +526,16 @@ public abstract class BasicTextUI extends TextUI implements ViewFactory {
EditorKit editorKit = getEditorKit(editor);
if ( editorKit != null
&& editorKit instanceof DefaultEditorKit) {
Set storedForwardTraversalKeys = editor.
Set<AWTKeyStroke> storedForwardTraversalKeys = editor.
getFocusTraversalKeys(KeyboardFocusManager.
FORWARD_TRAVERSAL_KEYS);
Set storedBackwardTraversalKeys = editor.
Set<AWTKeyStroke> storedBackwardTraversalKeys = editor.
getFocusTraversalKeys(KeyboardFocusManager.
BACKWARD_TRAVERSAL_KEYS);
Set forwardTraversalKeys =
new HashSet(storedForwardTraversalKeys);
Set backwardTraversalKeys =
new HashSet(storedBackwardTraversalKeys);
Set<AWTKeyStroke> forwardTraversalKeys =
new HashSet<AWTKeyStroke>(storedForwardTraversalKeys);
Set<AWTKeyStroke> backwardTraversalKeys =
new HashSet<AWTKeyStroke>(storedBackwardTraversalKeys);
if (editor.isEditable()) {
forwardTraversalKeys.
remove(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));
@ -1888,7 +1888,7 @@ public abstract class BasicTextUI extends TextUI implements ViewFactory {
*
* @param e The change notification from the currently associated
* document.
* @see DocumentListener#changeUpdate
* @see DocumentListener#changedUpdate(DocumentEvent)
*/
public final void changedUpdate(DocumentEvent e) {
Rectangle alloc = (painted) ? getVisibleEditorRect() : null;
@ -1964,9 +1964,9 @@ public abstract class BasicTextUI extends TextUI implements ViewFactory {
}
try {
rootView.setSize(alloc.width, alloc.height);
Enumeration components = constraints.keys();
Enumeration<Component> components = constraints.keys();
while (components.hasMoreElements()) {
Component comp = (Component) components.nextElement();
Component comp = components.nextElement();
View v = (View) constraints.get(comp);
Shape ca = calculateViewPosition(alloc, v);
if (ca != null) {
@ -2009,7 +2009,7 @@ public abstract class BasicTextUI extends TextUI implements ViewFactory {
public void addLayoutComponent(Component comp, Object constraint) {
if (constraint instanceof View) {
if (constraints == null) {
constraints = new Hashtable(7);
constraints = new Hashtable<Component, Object>(7);
}
constraints.put(comp, constraint);
}
@ -2060,7 +2060,7 @@ public abstract class BasicTextUI extends TextUI implements ViewFactory {
* These are View objects for those components that are represented
* by a View in the View tree.
*/
private Hashtable constraints;
private Hashtable<Component, Object> constraints;
private boolean i18nView = false;
}
@ -2457,8 +2457,7 @@ public abstract class BasicTextUI extends TextUI implements ViewFactory {
JTextComponent c = (JTextComponent)comp;
int pos = modeBetween
? ((JTextComponent.DropLocation)c.getDropLocation()).getIndex()
: c.getCaretPosition();
? c.getDropLocation().getIndex() : c.getCaretPosition();
// if we are importing to the same component that we exported from
// then don't actually do anything if the drop location is inside

View File

@ -125,31 +125,31 @@ public class BasicToggleButtonUI extends BasicButtonUI {
if(!model.isEnabled()) {
if(model.isSelected()) {
icon = (Icon) b.getDisabledSelectedIcon();
icon = b.getDisabledSelectedIcon();
} else {
icon = (Icon) b.getDisabledIcon();
icon = b.getDisabledIcon();
}
} else if(model.isPressed() && model.isArmed()) {
icon = (Icon) b.getPressedIcon();
icon = b.getPressedIcon();
if(icon == null) {
// Use selected icon
icon = (Icon) b.getSelectedIcon();
icon = b.getSelectedIcon();
}
} else if(model.isSelected()) {
if(b.isRolloverEnabled() && model.isRollover()) {
icon = (Icon) b.getRolloverSelectedIcon();
icon = b.getRolloverSelectedIcon();
if (icon == null) {
icon = (Icon) b.getSelectedIcon();
icon = b.getSelectedIcon();
}
} else {
icon = (Icon) b.getSelectedIcon();
icon = b.getSelectedIcon();
}
} else if(b.isRolloverEnabled() && model.isRollover()) {
icon = (Icon) b.getRolloverIcon();
icon = b.getRolloverIcon();
}
if(icon == null) {
icon = (Icon) b.getIcon();
icon = b.getIcon();
}
icon.paintIcon(b, g, iconRect.x, iconRect.y);

View File

@ -83,8 +83,8 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants
private static Border nonRolloverToggleBorder;
private boolean rolloverBorders = false;
private HashMap borderTable = new HashMap();
private Hashtable rolloverTable = new Hashtable();
private HashMap<AbstractButton, Border> borderTable = new HashMap<AbstractButton, Border>();
private Hashtable<AbstractButton, Boolean> rolloverTable = new Hashtable<AbstractButton, Boolean>();
/**
@ -171,7 +171,7 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants
uninstallKeyboardActions();
// Clear instance vars
if (isFloating() == true)
if (isFloating())
setFloating(false, null);
floatingToolBar = null;
@ -273,9 +273,8 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants
// Put focus listener on all components in toolbar
Component[] components = toolBar.getComponents();
for ( int i = 0; i < components.length; ++i )
{
components[ i ].addFocusListener( toolBarFocusListener );
for (Component component : components) {
component.addFocusListener(toolBarFocusListener);
}
}
}
@ -307,9 +306,8 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants
// Remove focus listener from all components in toolbar
Component[] components = toolBar.getComponents();
for ( int i = 0; i < components.length; ++i )
{
components[ i ].removeFocusListener( toolBarFocusListener );
for (Component component : components) {
component.removeFocusListener(toolBarFocusListener);
}
toolBarFocusListener = null;
@ -616,10 +614,10 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants
// Put rollover borders on buttons
Component[] components = c.getComponents();
for ( int i = 0; i < components.length; ++i ) {
if ( components[ i ] instanceof JComponent ) {
( (JComponent)components[ i ] ).updateUI();
setBorderToRollover( components[ i ] );
for (Component component : components) {
if (component instanceof JComponent) {
((JComponent) component).updateUI();
setBorderToRollover(component);
}
}
}
@ -640,10 +638,10 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants
// Put non-rollover borders on buttons. These borders reduce the margin.
Component[] components = c.getComponents();
for ( int i = 0; i < components.length; ++i ) {
if ( components[ i ] instanceof JComponent ) {
( (JComponent)components[ i ] ).updateUI();
setBorderToNonRollover( components[ i ] );
for (Component component : components) {
if (component instanceof JComponent) {
((JComponent) component).updateUI();
setBorderToNonRollover(component);
}
}
}
@ -664,8 +662,8 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants
// Put back the normal borders on buttons
Component[] components = c.getComponents();
for ( int i = 0; i < components.length; ++i ) {
setBorderToNormal( components[ i ] );
for (Component component : components) {
setBorderToNormal(component);
}
}
@ -681,7 +679,7 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants
if (c instanceof AbstractButton) {
AbstractButton b = (AbstractButton)c;
Border border = (Border)borderTable.get(b);
Border border = borderTable.get(b);
if (border == null || border instanceof UIResource) {
borderTable.put(b, b.getBorder());
}
@ -721,7 +719,7 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants
if (c instanceof AbstractButton) {
AbstractButton b = (AbstractButton)c;
Border border = (Border)borderTable.get(b);
Border border = borderTable.get(b);
if (border == null || border instanceof UIResource) {
borderTable.put(b, b.getBorder());
}
@ -765,10 +763,10 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants
if (c instanceof AbstractButton) {
AbstractButton b = (AbstractButton)c;
Border border = (Border)borderTable.remove(b);
Border border = borderTable.remove(b);
b.setBorder(border);
Boolean value = (Boolean)rolloverTable.remove(b);
Boolean value = rolloverTable.remove(b);
if (value != null) {
b.setRolloverEnabled(value.booleanValue());
}
@ -785,7 +783,7 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants
}
public void setFloating(boolean b, Point p) {
if (toolBar.isFloatable() == true) {
if (toolBar.isFloatable()) {
boolean visible = false;
Window ancestor = SwingUtilities.getWindowAncestor(toolBar);
if (ancestor != null) {
@ -953,7 +951,7 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants
protected void dragTo(Point position, Point origin)
{
if (toolBar.isFloatable() == true)
if (toolBar.isFloatable())
{
try
{
@ -1003,7 +1001,7 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants
protected void floatAt(Point position, Point origin)
{
if(toolBar.isFloatable() == true)
if(toolBar.isFloatable())
{
try
{
@ -1174,7 +1172,7 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants
if (!tb.isEnabled()) {
return;
}
if (isDragging == true) {
if (isDragging) {
Point position = evt.getPoint();
if (origin == null)
origin = evt.getComponent().getLocationOnScreen();
@ -1242,7 +1240,7 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants
protected class FrameListener extends WindowAdapter {
public void windowClosing(WindowEvent w) {
if (toolBar.isFloatable() == true) {
if (toolBar.isFloatable()) {
if (dragWindow != null)
dragWindow.setVisible(false);
floating = false;

View File

@ -1263,7 +1263,7 @@ public class BasicTreeUI extends TreeUI
}
private Rectangle getDropLineRect(JTree.DropLocation loc) {
Rectangle rect = null;
Rectangle rect;
TreePath path = loc.getPath();
int index = loc.getChildIndex();
boolean ltr = leftToRight;
@ -2138,7 +2138,7 @@ public class BasicTreeUI extends TreeUI
compositeRequestFocus(editingComponent);
boolean selectAll = true;
if(event != null && event instanceof MouseEvent) {
if(event != null) {
/* Find the component that will get forwarded all the
mouse events until mouseReleased. */
Point componentPoint = SwingUtilities.convertPoint
@ -3125,7 +3125,7 @@ public class BasicTreeUI extends TreeUI
private static final TransferHandler defaultTransferHandler = new TreeTransferHandler();
static class TreeTransferHandler extends TransferHandler implements UIResource, Comparator {
static class TreeTransferHandler extends TransferHandler implements UIResource, Comparator<TreePath> {
private JTree tree;
@ -3156,9 +3156,7 @@ public class BasicTreeUI extends TreeUI
TreePath lastPath = null;
TreePath[] displayPaths = getDisplayOrderPaths(paths);
for (int i = 0; i < displayPaths.length; i++) {
TreePath path = displayPaths[i];
for (TreePath path : displayPaths) {
Object node = path.getLastPathComponent();
boolean leaf = model.isLeaf(node);
String label = getDisplayString(path, true, leaf);
@ -3179,9 +3177,9 @@ public class BasicTreeUI extends TreeUI
return null;
}
public int compare(Object o1, Object o2) {
int row1 = tree.getRowForPath((TreePath)o1);
int row2 = tree.getRowForPath((TreePath)o2);
public int compare(TreePath o1, TreePath o2) {
int row1 = tree.getRowForPath(o1);
int row2 = tree.getRowForPath(o2);
return row1 - row2;
}
@ -3200,15 +3198,15 @@ public class BasicTreeUI extends TreeUI
*/
TreePath[] getDisplayOrderPaths(TreePath[] paths) {
// sort the paths to display order rather than selection order
ArrayList selOrder = new ArrayList();
for (int i = 0; i < paths.length; i++) {
selOrder.add(paths[i]);
ArrayList<TreePath> selOrder = new ArrayList<TreePath>();
for (TreePath path : paths) {
selOrder.add(path);
}
Collections.sort(selOrder, this);
int n = selOrder.size();
TreePath[] displayPaths = new TreePath[n];
for (int i = 0; i < n; i++) {
displayPaths[i] = (TreePath) selOrder.get(i);
displayPaths[i] = selOrder.get(i);
}
return displayPaths;
}
@ -3321,10 +3319,7 @@ public class BasicTreeUI extends TreeUI
InputMap inputMap = tree.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
KeyStroke key = KeyStroke.getKeyStrokeForEvent(event);
if (inputMap != null && inputMap.get(key) != null) {
return true;
}
return false;
return inputMap != null && inputMap.get(key) != null;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 1998-2006 Sun Microsystems, Inc. All Rights Reserved.
* Copyright 1998-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -30,7 +30,6 @@ import javax.swing.plaf.UIResource;
import java.awt.Container;
import java.awt.Dimension;
import static sun.swing.SwingUtilities2.BASICMENUITEMUI_MAX_TEXT_OFFSET;
/**
* The default layout manager for Popup menus and menubars. This
@ -49,18 +48,7 @@ public class DefaultMenuLayout extends BoxLayout implements UIResource {
public Dimension preferredLayoutSize(Container target) {
if (target instanceof JPopupMenu) {
JPopupMenu popupMenu = (JPopupMenu) target;
// Before the calculation of menu preferred size
// clear the previously calculated maximal widths and offsets
// in menu's Client Properties
popupMenu.putClientProperty(BasicMenuItemUI.MAX_ACC_WIDTH, null);
popupMenu.putClientProperty(BasicMenuItemUI.MAX_ARROW_WIDTH, null);
popupMenu.putClientProperty(BasicMenuItemUI.MAX_CHECK_WIDTH, null);
popupMenu.putClientProperty(BasicMenuItemUI.MAX_ICON_WIDTH, null);
popupMenu.putClientProperty(BasicMenuItemUI.MAX_LABEL_WIDTH, null);
popupMenu.putClientProperty(BasicMenuItemUI.MAX_TEXT_WIDTH, null);
popupMenu.putClientProperty(BASICMENUITEMUI_MAX_TEXT_OFFSET, null);
sun.swing.MenuItemLayoutHelper.clearUsedClientProperties(popupMenu);
if (popupMenu.getComponentCount() == 0) {
return new Dimension(0, 0);
}

View File

@ -0,0 +1,168 @@
/*
* Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.swing.plaf.basic;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
/**
* DesktopIconMover is intended to move desktop icon
* when parent window is resized.
*/
class DesktopIconMover implements ComponentListener, PropertyChangeListener {
private Component parent;
private JInternalFrame frame; // if not null, DesktopIconMover(frame)
// constructor was used
private JInternalFrame.JDesktopIcon icon;
private Rectangle parentBounds;
private boolean componentListenerAdded = false;
public DesktopIconMover(JInternalFrame frame) {
if (frame == null) {
throw new NullPointerException("Frame cannot be null");
}
this.frame = frame;
this.icon = frame.getDesktopIcon();
if (icon == null) {
throw new NullPointerException(
"frame.getDesktopIcon() cannot be null");
}
this.parent = frame.getParent();
if (this.parent != null) {
parentBounds = this.parent.getBounds();
}
}
public DesktopIconMover(JInternalFrame.JDesktopIcon icon) {
if (icon == null) {
throw new NullPointerException("Icon cannot be null");
}
this.icon = icon;
this.parent = icon.getParent();
if (this.parent != null) {
parentBounds = this.parent.getBounds();
}
}
public void installListeners() {
if (frame != null) {
frame.addPropertyChangeListener(this);
} else {
icon.addPropertyChangeListener(this);
}
addComponentListener();
}
public void uninstallListeners() {
if (frame != null) {
frame.removePropertyChangeListener(this);
} else {
icon.removePropertyChangeListener(this);
}
removeComponentListener();
}
public void propertyChange(PropertyChangeEvent evt) {
String propName = evt.getPropertyName();
if ("ancestor".equals(propName)) {
Component newAncestor = (Component) evt.getNewValue();
// Remove component listener if parent is changing
Component probablyNewParent = getCurrentParent();
if ((probablyNewParent != null) &&
(!probablyNewParent.equals(parent))) {
removeComponentListener();
parent = probablyNewParent;
}
if (newAncestor == null) {
removeComponentListener();
} else {
addComponentListener();
}
// Update parentBounds
if (parent != null) {
parentBounds = parent.getBounds();
} else {
parentBounds = null;
}
} else if (JInternalFrame.IS_CLOSED_PROPERTY.equals(propName)) {
removeComponentListener();
}
}
private void addComponentListener() {
if (!componentListenerAdded && (parent != null)) {
parent.addComponentListener(this);
componentListenerAdded = true;
}
}
private void removeComponentListener() {
if ((parent != null) && componentListenerAdded) {
parent.removeComponentListener(this);
componentListenerAdded = false;
}
}
private Component getCurrentParent() {
if (frame != null) {
return frame.getParent();
} else {
return icon.getParent();
}
}
public void componentResized(ComponentEvent e) {
if ((parent == null) || (parentBounds == null)) {
return;
}
Rectangle parentNewBounds = parent.getBounds();
if ((parentNewBounds == null) || parentNewBounds.equals(parentBounds)) {
return;
}
// Move desktop icon only in up-down direction
int newIconY = icon.getLocation().y +
(parentNewBounds.height - parentBounds.height);
icon.setLocation(icon.getLocation().x, newIconY);
parentBounds = parentNewBounds;
}
public void componentMoved(ComponentEvent e) {
}
public void componentShown(ComponentEvent e) {
}
public void componentHidden(ComponentEvent e) {
}
}

View File

@ -73,8 +73,7 @@ class DragRecognitionSupport {
* Returns whether or not the event is potentially part of a drag sequence.
*/
public static boolean mousePressed(MouseEvent me) {
return ((DragRecognitionSupport)getDragRecognitionSupport()).
mousePressedImpl(me);
return getDragRecognitionSupport().mousePressedImpl(me);
}
/**
@ -82,16 +81,14 @@ class DragRecognitionSupport {
* that started the recognition. Otherwise, return null.
*/
public static MouseEvent mouseReleased(MouseEvent me) {
return ((DragRecognitionSupport)getDragRecognitionSupport()).
mouseReleasedImpl(me);
return getDragRecognitionSupport().mouseReleasedImpl(me);
}
/**
* Returns whether or not a drag gesture recognition is ongoing.
*/
public static boolean mouseDragged(MouseEvent me, BeforeDrag bd) {
return ((DragRecognitionSupport)getDragRecognitionSupport()).
mouseDraggedImpl(me, bd);
return getDragRecognitionSupport().mouseDraggedImpl(me, bd);
}
private void clearState() {

View File

@ -142,7 +142,7 @@ class LazyActionMap extends ActionMapUIResource {
Object loader = _loader;
_loader = null;
Class klass = (Class)loader;
Class<?> klass = (Class<?>)loader;
try {
Method method = klass.getDeclaredMethod("loadActionMap",
new Class[] { LazyActionMap.class });

View File

@ -387,9 +387,9 @@ public class DefaultMetalTheme extends MetalTheme {
* that it is wrapped inside a <code>doPrivileged</code> call.
*/
protected Font getPrivilegedFont(final int key) {
return (Font)java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
return java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Font>() {
public Font run() {
return Font.getFont(getDefaultPropertyName(key));
}
}

View File

@ -49,7 +49,7 @@ class MetalBumps implements Icon {
protected Color shadowColor;
protected Color backColor;
protected static Vector buffers = new Vector();
protected static Vector<BumpBuffer> buffers = new Vector<BumpBuffer>();
protected BumpBuffer buffer;
public MetalBumps( Dimension bumpArea ) {
@ -81,10 +81,7 @@ class MetalBumps implements Icon {
}
BumpBuffer result = null;
Enumeration elements = buffers.elements();
while ( elements.hasMoreElements() ) {
BumpBuffer aBuffer = (BumpBuffer)elements.nextElement();
for (BumpBuffer aBuffer : buffers) {
if ( aBuffer.hasSameConfiguration(gc, aTopColor, aShadowColor,
aBackColor)) {
result = aBuffer;
@ -120,8 +117,7 @@ class MetalBumps implements Icon {
public void paintIcon( Component c, Graphics g, int x, int y ) {
GraphicsConfiguration gc = (g instanceof Graphics2D) ?
(GraphicsConfiguration)((Graphics2D)g).
getDeviceConfiguration() : null;
((Graphics2D) g).getDeviceConfiguration() : null;
buffer = getBuffer(gc, topColor, shadowColor, backColor);

View File

@ -782,7 +782,7 @@ public class MetalFileChooserUI extends BasicFileChooserUI {
} else if (s.equals("componentOrientation")) {
ComponentOrientation o = (ComponentOrientation)e.getNewValue();
JFileChooser cc = (JFileChooser)e.getSource();
if (o != (ComponentOrientation)e.getOldValue()) {
if (o != e.getOldValue()) {
cc.applyComponentOrientation(o);
}
} else if (s == "FileChooser.useShellFolder") {
@ -927,7 +927,7 @@ public class MetalFileChooserUI extends BasicFileChooserUI {
* Data model for a type-face selection combo-box.
*/
protected class DirectoryComboBoxModel extends AbstractListModel implements ComboBoxModel {
Vector directories = new Vector();
Vector<File> directories = new Vector<File>();
int[] depths = null;
File selectedDirectory = null;
JFileChooser chooser = getFileChooser();
@ -966,7 +966,7 @@ public class MetalFileChooserUI extends BasicFileChooserUI {
// Get the canonical (full) path. This has the side
// benefit of removing extraneous chars from the path,
// for example /foo/bar/ becomes /foo/bar
File canonical = null;
File canonical;
try {
canonical = ShellFolder.getNormalizedFile(directory);
} catch (IOException e) {
@ -979,7 +979,7 @@ public class MetalFileChooserUI extends BasicFileChooserUI {
File sf = useShellFolder ? ShellFolder.getShellFolder(canonical)
: canonical;
File f = sf;
Vector path = new Vector(10);
Vector<File> path = new Vector<File>(10);
do {
path.addElement(f);
} while ((f = f.getParentFile()) != null);
@ -987,7 +987,7 @@ public class MetalFileChooserUI extends BasicFileChooserUI {
int pathCount = path.size();
// Insert chain at appropriate place in vector
for (int i = 0; i < pathCount; i++) {
f = (File)path.get(i);
f = path.get(i);
if (directories.contains(f)) {
int topIndex = directories.indexOf(f);
for (int j = i-1; j >= 0; j--) {
@ -1006,12 +1006,12 @@ public class MetalFileChooserUI extends BasicFileChooserUI {
private void calculateDepths() {
depths = new int[directories.size()];
for (int i = 0; i < depths.length; i++) {
File dir = (File)directories.get(i);
File dir = directories.get(i);
File parent = dir.getParentFile();
depths[i] = 0;
if (parent != null) {
for (int j = i-1; j >= 0; j--) {
if (parent.equals((File)directories.get(j))) {
if (parent.equals(directories.get(j))) {
depths[i] = depths[j] + 1;
break;
}
@ -1110,8 +1110,8 @@ public class MetalFileChooserUI extends BasicFileChooserUI {
FileFilter currentFilter = getFileChooser().getFileFilter();
boolean found = false;
if(currentFilter != null) {
for(int i=0; i < filters.length; i++) {
if(filters[i] == currentFilter) {
for (FileFilter filter : filters) {
if (filter == currentFilter) {
found = true;
}
}

View File

@ -598,7 +598,7 @@ public class MetalIconFactory implements Serializable {
}
// Some calculations that are needed more than once later on.
int oneHalf = (int)(iconSize / 2); // 16 -> 8
int oneHalf = iconSize / 2; // 16 -> 8
g.translate(x, y);
@ -1502,7 +1502,7 @@ public class MetalIconFactory implements Serializable {
// PENDING: Replace this class with CachedPainter.
Vector images = new Vector(1, 1);
Vector<ImageGcPair> images = new Vector<ImageGcPair>(1, 1);
ImageGcPair currentImageGcPair;
class ImageGcPair {
@ -1514,12 +1514,8 @@ public class MetalIconFactory implements Serializable {
}
boolean hasSameConfiguration(GraphicsConfiguration newGC) {
if (((newGC != null) && (newGC.equals(gc))) ||
((newGC == null) && (gc == null)))
{
return true;
}
return false;
return ((newGC != null) && (newGC.equals(gc))) ||
((newGC == null) && (gc == null));
}
}
@ -1528,9 +1524,7 @@ public class MetalIconFactory implements Serializable {
if ((currentImageGcPair == null) ||
!(currentImageGcPair.hasSameConfiguration(newGC)))
{
Enumeration elements = images.elements();
while (elements.hasMoreElements()) {
ImageGcPair imgGcPair = (ImageGcPair)elements.nextElement();
for (ImageGcPair imgGcPair : images) {
if (imgGcPair.hasSameConfiguration(newGC)) {
currentImageGcPair = imgGcPair;
return imgGcPair.image;

View File

@ -191,7 +191,7 @@ public class MetalInternalFrameTitlePane extends BasicInternalFrameTitlePane {
extends BasicInternalFrameTitlePane.PropertyChangeHandler
{
public void propertyChange(PropertyChangeEvent evt) {
String prop = (String)evt.getPropertyName();
String prop = evt.getPropertyName();
if( prop.equals(JInternalFrame.IS_SELECTED_PROPERTY) ) {
Boolean b = (Boolean)evt.getNewValue();
iconButton.putClientProperty("paintActive", b);
@ -242,7 +242,7 @@ public class MetalInternalFrameTitlePane extends BasicInternalFrameTitlePane {
}
// Compute height.
int height = 0;
int height;
if (isPalette) {
height = paletteTitleHeight;
} else {
@ -410,7 +410,7 @@ public class MetalInternalFrameTitlePane extends BasicInternalFrameTitlePane {
g.drawLine ( width - 1, 0 , width -1, 0);
int titleLength = 0;
int titleLength;
int xOffset = leftToRight ? 5 : width - 5;
String frameTitle = frame.getTitle();

View File

@ -2208,9 +2208,9 @@ public class MetalLookAndFeel extends BasicLookAndFeel
if (methodName == null) {
return c.newInstance();
}
Method method = (Method)AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
Method method = AccessController.doPrivileged(
new PrivilegedAction<Method>() {
public Method run() {
Method[] methods = c.getDeclaredMethods();
for (int counter = methods.length - 1; counter >= 0;
counter--) {
@ -2273,7 +2273,7 @@ public class MetalLookAndFeel extends BasicLookAndFeel
}
}
static ReferenceQueue queue = new ReferenceQueue();
static ReferenceQueue<LookAndFeel> queue = new ReferenceQueue<LookAndFeel>();
static void flushUnreferenced() {
AATextListener aatl;
@ -2283,7 +2283,7 @@ public class MetalLookAndFeel extends BasicLookAndFeel
}
static class AATextListener
extends WeakReference implements PropertyChangeListener {
extends WeakReference<LookAndFeel> implements PropertyChangeListener {
private String key = SunToolkit.DESKTOPFONTHINTS;
@ -2294,7 +2294,7 @@ public class MetalLookAndFeel extends BasicLookAndFeel
}
public void propertyChange(PropertyChangeEvent pce) {
LookAndFeel laf = (LookAndFeel)get();
LookAndFeel laf = get();
if (laf == null || laf != UIManager.getLookAndFeel()) {
dispose();
return;
@ -2318,8 +2318,8 @@ public class MetalLookAndFeel extends BasicLookAndFeel
private static void updateWindowUI(Window window) {
SwingUtilities.updateComponentTreeUI(window);
Window ownedWins[] = window.getOwnedWindows();
for (int i=0; i < ownedWins.length; i++) {
updateWindowUI(ownedWins[i]);
for (Window w : ownedWins) {
updateWindowUI(w);
}
}
@ -2328,8 +2328,8 @@ public class MetalLookAndFeel extends BasicLookAndFeel
*/
private static void updateAllUIs() {
Frame appFrames[] = Frame.getFrames();
for (int j=0; j < appFrames.length; j++) {
updateWindowUI(appFrames[j]);
for (Frame frame : appFrames) {
updateWindowUI(frame);
}
}

View File

@ -164,15 +164,15 @@ public class MetalRadioButtonUI extends BasicRadioButtonUI {
}
} else if(model.isSelected()) {
if(b.isRolloverEnabled() && model.isRollover()) {
altIcon = (Icon) b.getRolloverSelectedIcon();
altIcon = b.getRolloverSelectedIcon();
if (altIcon == null) {
altIcon = (Icon) b.getSelectedIcon();
altIcon = b.getSelectedIcon();
}
} else {
altIcon = (Icon) b.getSelectedIcon();
altIcon = b.getSelectedIcon();
}
} else if(b.isRolloverEnabled() && model.isRollover()) {
altIcon = (Icon) b.getRolloverIcon();
altIcon = b.getRolloverIcon();
}
if(altIcon == null) {

View File

@ -61,7 +61,7 @@ public class MetalToolBarUI extends BasicToolBarUI
* instances of JToolBars and JMenuBars and is used to find
* JToolBars/JMenuBars that border each other.
*/
private static java.util.List components = new ArrayList();
private static List<WeakReference<JComponent>> components = new ArrayList<WeakReference<JComponent>>();
/**
* This protected field is implemenation specific. Do not access directly
@ -95,7 +95,7 @@ public class MetalToolBarUI extends BasicToolBarUI
// typed to throw an NPE.
throw new NullPointerException("JComponent must be non-null");
}
components.add(new WeakReference(c));
components.add(new WeakReference<JComponent>(c));
}
/**
@ -105,8 +105,7 @@ public class MetalToolBarUI extends BasicToolBarUI
for (int counter = components.size() - 1; counter >= 0; counter--) {
// Search for the component, removing any flushed references
// along the way.
WeakReference ref = (WeakReference)components.get(counter);
Object target = ((WeakReference)components.get(counter)).get();
JComponent target = components.get(counter).get();
if (target == c || target == null) {
components.remove(counter);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 Sun Microsystems, Inc. All Rights Reserved.
* Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -47,19 +47,22 @@ class DefaultMenuLayout extends BoxLayout implements UIResource {
super(target, axis);
}
public void invalidateLayout(Container target) {
if (target instanceof JPopupMenu) {
SynthPopupMenuUI popupUI = (SynthPopupMenuUI)((JPopupMenu)target).
getUI();
popupUI.resetAlignmentHints();
}
super.invalidateLayout(target);
}
public Dimension preferredLayoutSize(Container target) {
if (target instanceof JPopupMenu && target.getComponentCount() == 0) {
return new Dimension(0, 0);
if (target instanceof JPopupMenu) {
JPopupMenu popupMenu = (JPopupMenu) target;
popupMenu.putClientProperty(
SynthMenuItemLayoutHelper.MAX_ACC_OR_ARROW_WIDTH, null);
sun.swing.MenuItemLayoutHelper.clearUsedClientProperties(popupMenu);
if (popupMenu.getComponentCount() == 0) {
return new Dimension(0, 0);
}
}
// Make BoxLayout recalculate cached preferred sizes
super.invalidateLayout(target);
return super.preferredLayoutSize(target);
}
}

View File

@ -63,7 +63,7 @@ class DefaultSynthStyleFactory extends SynthStyleFactory {
/**
* Maps from a List (BakedArrayList to be precise) to the merged style.
*/
private Map _resolvedStyles;
private Map<BakedArrayList, SynthStyle> _resolvedStyles;
/**
* Used if there are no styles matching a widget.
@ -74,7 +74,7 @@ class DefaultSynthStyleFactory extends SynthStyleFactory {
DefaultSynthStyleFactory() {
_tmpList = new BakedArrayList(5);
_styles = new ArrayList<StyleAssociation>();
_resolvedStyles = new HashMap();
_resolvedStyles = new HashMap<BakedArrayList, SynthStyle>();
}
public synchronized void addStyle(DefaultSynthStyle style,
@ -138,7 +138,7 @@ class DefaultSynthStyleFactory extends SynthStyleFactory {
* Fetches any styles that match the passed into arguments into
* <code>matches</code>.
*/
private void getMatchingStyles(java.util.List matches, JComponent c,
private void getMatchingStyles(List matches, JComponent c,
Region id) {
String idName = id.getLowerCaseName();
String cName = c.getName();
@ -166,7 +166,7 @@ class DefaultSynthStyleFactory extends SynthStyleFactory {
/**
* Caches the specified style.
*/
private void cacheStyle(java.util.List styles, SynthStyle style) {
private void cacheStyle(List styles, SynthStyle style) {
BakedArrayList cachedStyles = new BakedArrayList(styles);
_resolvedStyles.put(cachedStyles, style);
@ -175,11 +175,11 @@ class DefaultSynthStyleFactory extends SynthStyleFactory {
/**
* Returns the cached style from the passed in arguments.
*/
private SynthStyle getCachedStyle(java.util.List styles) {
private SynthStyle getCachedStyle(List styles) {
if (styles.size() == 0) {
return null;
}
return (SynthStyle)_resolvedStyles.get(styles);
return _resolvedStyles.get(styles);
}
/**
@ -187,7 +187,7 @@ class DefaultSynthStyleFactory extends SynthStyleFactory {
* is reverse sorted, that is the most recently added style found to
* match will be first.
*/
private SynthStyle mergeStyles(java.util.List styles) {
private SynthStyle mergeStyles(List styles) {
int size = styles.size();
if (size == 0) {

View File

@ -66,7 +66,7 @@ class ImagePainter extends SynthPainter {
Paint9Painter painter;
if (cacheRef == null || (painter = cacheRef.get()) == null) {
painter = new Paint9Painter(30);
cacheRef = new WeakReference(painter);
cacheRef = new WeakReference<Paint9Painter>(painter);
AppContext.getAppContext().put(CACHE_KEY, cacheRef);
}
return painter;

View File

@ -67,8 +67,8 @@ import java.util.*;
* @author Scott Violet
*/
public class Region {
private static final Map uiToRegionMap = new HashMap();
private static final Map lowerCaseNameMap = new HashMap();
private static final Map<String, Region> uiToRegionMap = new HashMap<String, Region>();
private static final Map<Region, String> lowerCaseNameMap = new HashMap<Region, String>();
/**
* ArrowButton's are special types of buttons that also render a
@ -451,15 +451,11 @@ public class Region {
static Region getRegion(JComponent c) {
return (Region)uiToRegionMap.get(c.getUIClassID());
return uiToRegionMap.get(c.getUIClassID());
}
static void registerUIs(UIDefaults table) {
Iterator uis = uiToRegionMap.keySet().iterator();
while (uis.hasNext()) {
Object key = uis.next();
for (String key : uiToRegionMap.keySet()) {
table.put(key, "javax.swing.plaf.synth.SynthLookAndFeel");
}
}
@ -521,7 +517,7 @@ public class Region {
*/
String getLowerCaseName() {
synchronized(lowerCaseNameMap) {
String lowerCaseName = (String)lowerCaseNameMap.get(this);
String lowerCaseName = lowerCaseNameMap.get(this);
if (lowerCaseName == null) {
lowerCaseName = getName().toLowerCase();
lowerCaseNameMap.put(this, lowerCaseName);

View File

@ -262,7 +262,7 @@ class SynthButtonUI extends BasicButtonUI implements
* Returns the default icon. This should NOT callback
* to the JComponent.
*
* @param b AbstractButton the iocn is associated with
* @param b AbstractButton the icon is associated with
* @return default icon
*/
@ -445,9 +445,7 @@ class SynthButtonUI extends BasicButtonUI implements
* Returns the Icon used in calculating the pref/min/max size.
*/
protected Icon getSizingIcon(AbstractButton b) {
// NOTE: this is slightly different than BasicButtonUI, where it
// would just use getIcon, but this should be ok.
Icon icon = (b.isEnabled()) ? b.getIcon() : b.getDisabledIcon();
Icon icon = getEnabledIcon(b, b.getIcon());
if (icon == null) {
icon = getDefaultIcon(b);
}

View File

@ -336,7 +336,7 @@ class SynthComboBoxUI extends BasicComboBoxUI implements
return oldValue;
} else {
// Must take the value from the editor and get the value and cast it to the new type.
Class cls = oldValue.getClass();
Class<?> cls = oldValue.getClass();
try {
Method method = cls.getMethod("valueOf", new Class[]{String.class});
newValue = method.invoke(oldValue, new Object[] { editor.getText()});

View File

@ -39,7 +39,7 @@ import java.util.*;
* @author Scott Violet
*/
public class SynthContext {
private static final Map contextMap;
private static final Map<Class, List<SynthContext>> contextMap;
private JComponent component;
private Region region;
@ -48,7 +48,7 @@ public class SynthContext {
static {
contextMap = new HashMap();
contextMap = new HashMap<Class, List<SynthContext>>();
}
@ -58,13 +58,13 @@ public class SynthContext {
SynthContext context = null;
synchronized(contextMap) {
java.util.List instances = (java.util.List)contextMap.get(type);
List<SynthContext> instances = contextMap.get(type);
if (instances != null) {
int size = instances.size();
if (size > 0) {
context = (SynthContext)instances.remove(size - 1);
context = instances.remove(size - 1);
}
}
}
@ -81,11 +81,10 @@ public class SynthContext {
static void releaseContext(SynthContext context) {
synchronized(contextMap) {
java.util.List instances = (java.util.List)contextMap.get(
context.getClass());
List<SynthContext> instances = contextMap.get(context.getClass());
if (instances == null) {
instances = new ArrayList(5);
instances = new ArrayList<SynthContext>(5);
contextMap.put(context.getClass(), instances);
}
instances.add(context);

View File

@ -45,8 +45,8 @@ class SynthEditorPaneUI extends BasicEditorPaneUI implements SynthUI {
* I would prefer to use UIResource instad of this.
* Unfortunately Boolean is a final class
*/
private Boolean localTrue = new Boolean(true);
private Boolean localFalse = new Boolean(false);
private Boolean localTrue = Boolean.TRUE;
private Boolean localFalse = Boolean.FALSE;
/**
* Creates a UI for the JTextPane.
@ -69,7 +69,7 @@ class SynthEditorPaneUI extends BasicEditorPaneUI implements SynthUI {
c.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES,
localTrue);
}
updateStyle((JTextComponent)getComponent());
updateStyle(getComponent());
}
protected void uninstallDefaults() {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 Sun Microsystems, Inc. All Rights Reserved.
* Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -25,6 +25,8 @@
package javax.swing.plaf.synth;
import sun.swing.SwingUtilities2;
import sun.swing.MenuItemLayoutHelper;
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.basic.BasicHTML;
@ -411,12 +413,204 @@ public class SynthGraphicsUtils {
}
/**
* A quick note about how preferred sizes are calculated... Generally
* speaking, SynthPopupMenuUI will run through the list of its children
* (from top to bottom) and ask each for its preferred size. Each menu
* item will add up the max width of each element (icons, text,
* accelerator spacing, accelerator text or arrow icon) encountered thus
* far, so by the time all menu items have been calculated, we will
* know the maximum (preferred) menu item size for that popup menu.
* Later when it comes time to paint each menu item, we can use those
* same accumulated max element sizes in order to layout the item.
*/
static Dimension getPreferredMenuItemSize(SynthContext context,
SynthContext accContext, JComponent c,
Icon checkIcon, Icon arrowIcon, int defaultTextIconGap,
String acceleratorDelimiter, boolean useCheckAndArrow,
String propertyPrefix) {
JMenuItem mi = (JMenuItem) c;
SynthMenuItemLayoutHelper lh = new SynthMenuItemLayoutHelper(
context, accContext, mi, checkIcon, arrowIcon,
MenuItemLayoutHelper.createMaxRect(), defaultTextIconGap,
acceleratorDelimiter, SynthLookAndFeel.isLeftToRight(mi),
useCheckAndArrow, propertyPrefix);
Dimension result = new Dimension();
// Calculate the result width
int gap = lh.getGap();
result.width = 0;
MenuItemLayoutHelper.addMaxWidth(lh.getCheckSize(), gap, result);
MenuItemLayoutHelper.addMaxWidth(lh.getLabelSize(), gap, result);
MenuItemLayoutHelper.addWidth(lh.getMaxAccOrArrowWidth(), 5 * gap, result);
// The last gap is unnecessary
result.width -= gap;
// Calculate the result height
result.height = MenuItemLayoutHelper.max(lh.getCheckSize().getHeight(),
lh.getLabelSize().getHeight(), lh.getAccSize().getHeight(),
lh.getArrowSize().getHeight());
// Take into account menu item insets
Insets insets = lh.getMenuItem().getInsets();
if (insets != null) {
result.width += insets.left + insets.right;
result.height += insets.top + insets.bottom;
}
// if the width is even, bump it up one. This is critical
// for the focus dash lhne to draw properly
if (result.width % 2 == 0) {
result.width++;
}
// if the height is even, bump it up one. This is critical
// for the text to center properly
if (result.height % 2 == 0) {
result.height++;
}
return result;
}
static void applyInsets(Rectangle rect, Insets insets) {
if (insets != null) {
rect.x += insets.left;
rect.y += insets.top;
rect.width -= (insets.right + rect.x);
rect.height -= (insets.bottom + rect.y);
}
}
static void paint(SynthContext context, SynthContext accContext, Graphics g,
Icon checkIcon, Icon arrowIcon, String acceleratorDelimiter,
int defaultTextIconGap, String propertyPrefix) {
JMenuItem mi = (JMenuItem) context.getComponent();
SynthStyle style = context.getStyle();
g.setFont(style.getFont(context));
Rectangle viewRect = new Rectangle(0, 0, mi.getWidth(), mi.getHeight());
applyInsets(viewRect, mi.getInsets());
SynthMenuItemLayoutHelper lh = new SynthMenuItemLayoutHelper(
context, accContext, mi, checkIcon,
arrowIcon, viewRect, defaultTextIconGap, acceleratorDelimiter,
SynthLookAndFeel.isLeftToRight(mi),
MenuItemLayoutHelper.useCheckAndArrow(mi), propertyPrefix);
MenuItemLayoutHelper.LayoutResult lr = lh.layoutMenuItem();
paintMenuItem(g, lh, lr);
}
static void paintMenuItem(Graphics g, SynthMenuItemLayoutHelper lh,
MenuItemLayoutHelper.LayoutResult lr) {
// Save original graphics font and color
Font holdf = g.getFont();
Color holdc = g.getColor();
paintBackground(g, lh);
paintCheckIcon(g, lh, lr);
paintIcon(g, lh, lr);
paintText(g, lh, lr);
paintAccText(g, lh, lr);
paintArrowIcon(g, lh, lr);
// Restore original graphics font and color
g.setColor(holdc);
g.setFont(holdf);
}
static void paintBackground(Graphics g, SynthMenuItemLayoutHelper lh) {
paintBackground(lh.getContext(), g, lh.getMenuItem());
}
static void paintBackground(SynthContext context, Graphics g, JComponent c) {
context.getPainter().paintMenuItemBackground(context, g, 0, 0,
c.getWidth(), c.getHeight());
}
static void paintIcon(Graphics g, SynthMenuItemLayoutHelper lh,
MenuItemLayoutHelper.LayoutResult lr) {
if (lh.getIcon() != null) {
Icon icon;
JMenuItem mi = lh.getMenuItem();
ButtonModel model = mi.getModel();
if (!model.isEnabled()) {
icon = mi.getDisabledIcon();
} else if (model.isPressed() && model.isArmed()) {
icon = mi.getPressedIcon();
if (icon == null) {
// Use default icon
icon = mi.getIcon();
}
} else {
icon = mi.getIcon();
}
if (icon != null) {
Rectangle iconRect = lr.getIconRect();
SynthIcon.paintIcon(icon, lh.getContext(), g, iconRect.x,
iconRect.y, iconRect.width, iconRect.height);
}
}
}
static void paintCheckIcon(Graphics g, SynthMenuItemLayoutHelper lh,
MenuItemLayoutHelper.LayoutResult lr) {
if (lh.getCheckIcon() != null) {
Rectangle checkRect = lr.getCheckRect();
SynthIcon.paintIcon(lh.getCheckIcon(), lh.getContext(), g,
checkRect.x, checkRect.y, checkRect.width, checkRect.height);
}
}
static void paintAccText(Graphics g, SynthMenuItemLayoutHelper lh,
MenuItemLayoutHelper.LayoutResult lr) {
String accText = lh.getAccText();
if (accText != null && !accText.equals("")) {
g.setColor(lh.getAccStyle().getColor(lh.getAccContext(),
ColorType.TEXT_FOREGROUND));
g.setFont(lh.getAccStyle().getFont(lh.getAccContext()));
lh.getAccGraphicsUtils().paintText(lh.getAccContext(), g, accText,
lr.getAccRect().x, lr.getAccRect().y, -1);
}
}
static void paintText(Graphics g, SynthMenuItemLayoutHelper lh,
MenuItemLayoutHelper.LayoutResult lr) {
if (!lh.getText().equals("")) {
if (lh.getHtmlView() != null) {
// Text is HTML
lh.getHtmlView().paint(g, lr.getTextRect());
} else {
// Text isn't HTML
g.setColor(lh.getStyle().getColor(
lh.getContext(), ColorType.TEXT_FOREGROUND));
g.setFont(lh.getStyle().getFont(lh.getContext()));
lh.getGraphicsUtils().paintText(lh.getContext(), g, lh.getText(),
lr.getTextRect().x, lr.getTextRect().y,
lh.getMenuItem().getDisplayedMnemonicIndex());
}
}
}
static void paintArrowIcon(Graphics g, SynthMenuItemLayoutHelper lh,
MenuItemLayoutHelper.LayoutResult lr) {
if (lh.getArrowIcon() != null) {
Rectangle arrowRect = lr.getArrowRect();
SynthIcon.paintIcon(lh.getArrowIcon(), lh.getContext(), g,
arrowRect.x, arrowRect.y, arrowRect.width, arrowRect.height);
}
}
/**
* Wraps a SynthIcon around the Icon interface, forwarding calls to
* the SynthIcon with a given SynthContext.
*/
private static class SynthIconWrapper implements Icon {
private static final java.util.List CACHE = new java.util.ArrayList(1);
private static final java.util.List<SynthIconWrapper> CACHE = new java.util.ArrayList<SynthIconWrapper>(1);
private SynthIcon synthIcon;
private SynthContext context;
@ -425,8 +619,7 @@ public class SynthGraphicsUtils {
synchronized(CACHE) {
int size = CACHE.size();
if (size > 0) {
SynthIconWrapper wrapper = (SynthIconWrapper)CACHE.remove(
size - 1);
SynthIconWrapper wrapper = CACHE.remove(size - 1);
wrapper.reset(icon, context);
return wrapper;
}

Some files were not shown because too many files have changed in this diff Show More