--- a/jdk/make/javax/swing/Makefile Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/make/javax/swing/Makefile Tue Aug 12 17:59:58 2008 -0700
@@ -33,7 +33,7 @@
# 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
--- a/jdk/make/tools/Makefile Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/make/tools/Makefile Tue Aug 12 17:59:58 2008 -0700
@@ -32,7 +32,6 @@
SUBDIRS = \
addjsum \
- auto_multi \
buildmetaindex \
commentchecker \
compile_font_config \
--- a/jdk/make/tools/auto_multi/Makefile Thu Aug 07 09:42:31 2008 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -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
-
--- a/jdk/make/tools/src/build/tools/automulti/AutoMulti.java Thu Aug 07 09:42:31 2008 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -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;
- }
- }
-}
--- a/jdk/make/tools/src/build/tools/automulti/README.txt Thu Aug 07 09:42:31 2008 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -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.
-
--- a/jdk/make/tools/src/build/tools/automulti/TestALFGenerator.java Thu Aug 07 09:42:31 2008 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -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;
- }
- }
-}
--- a/jdk/make/tools/src/build/tools/automulti/TestALFLookAndFeel.java Thu Aug 07 09:42:31 2008 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -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);
- }
-}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java Tue Aug 12 17:59:58 2008 -0700
@@ -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);
+ }
+ }
+ }
+}
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKColorChooserPanel.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKColorChooserPanel.java Tue Aug 12 17:59:58 2008 -0700
@@ -442,7 +442,10 @@
}
if (updateModel) {
- getColorSelectionModel().setSelectedColor(color);
+ ColorSelectionModel model = getColorSelectionModel();
+ if (model != null) {
+ model.setSelectedColor(color);
+ }
}
triangle.setColor(hue, saturation, brightness);
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java Tue Aug 12 17:59:58 2008 -0700
@@ -770,33 +770,56 @@
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;
+ }
+
+ if (frame.isMaximizable()) {
+ maximizeButton.setBounds(x, y, buttonDim.width, buttonDim.height);
+ x -= buttonDim.width;
+ }
- if (frame.isClosable()) {
- closeButton.setBounds(x, y, buttonDim.width, buttonDim.height);
- x -= (buttonDim.width + buttonGap);
- }
+ 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.isMaximizable()) {
- maximizeButton.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.isIconifiable()) {
- minimizeButton.setBounds(x, y, buttonDim.width, buttonDim.height);
+ 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 @@
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 @@
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 @@
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;
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/DesktopProperty.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/DesktopProperty.java Tue Aug 12 17:59:58 2008 -0700
@@ -49,8 +49,7 @@
/**
* ReferenceQueue of unreferenced WeakPCLs.
*/
- private static ReferenceQueue queue;
-
+ private static ReferenceQueue<DesktopProperty> queue;
/**
* PropertyChangeListener attached to the Toolkit.
@@ -76,7 +75,7 @@
static {
- queue = new ReferenceQueue();
+ queue = new ReferenceQueue<DesktopProperty>();
}
/**
@@ -117,8 +116,8 @@
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 @@
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 @@
* 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 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
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsDesktopManager.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsDesktopManager.java Tue Aug 12 17:59:58 2008 -0700
@@ -96,7 +96,7 @@
}
} catch (PropertyVetoException e) {}
if (f != currentFrame) {
- currentFrameRef = new WeakReference(f);
+ currentFrameRef = new WeakReference<JInternalFrame>(f);
}
}
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsFileChooserUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsFileChooserUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -983,7 +983,7 @@
} 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 @@
* 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 @@
// 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 @@
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 @@
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 @@
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 @@
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;
}
}
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java Tue Aug 12 17:59:58 2008 -0700
@@ -137,25 +137,46 @@
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;
+ 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();
+ }
- 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);
+ 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 {
- titleX = systemLabel.getX() - 2
- - SwingUtilities2.stringWidth(frame,fm,title);
+ 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 @@
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 @@
}
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 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) &&
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsScrollBarUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsScrollBarUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -369,21 +369,21 @@
*/
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;
}
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTabbedPaneUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTabbedPaneUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -53,13 +53,13 @@
* 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 @@
// 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);
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -124,7 +124,7 @@
setIcon(null);
sortIcon = null;
SortOrder sortOrder =
- getColumnSortOrder(header.getTable(), column);
+ getColumnSortOrder(table, column);
if (sortOrder != null) {
switch (sortOrder) {
case ASCENDING:
--- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic.properties Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic.properties Tue Aug 12 17:59:58 2008 -0700
@@ -101,30 +101,41 @@
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
--- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_de.properties Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_de.properties Tue Aug 12 17:59:58 2008 -0700
@@ -101,30 +101,41 @@
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
--- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_es.properties Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_es.properties Tue Aug 12 17:59:58 2008 -0700
@@ -101,30 +101,41 @@
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
--- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_fr.properties Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_fr.properties Tue Aug 12 17:59:58 2008 -0700
@@ -101,30 +101,41 @@
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
--- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_it.properties Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_it.properties Tue Aug 12 17:59:58 2008 -0700
@@ -101,30 +101,41 @@
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
--- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ja.properties Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ja.properties Tue Aug 12 17:59:58 2008 -0700
@@ -101,30 +101,41 @@
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
--- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ko.properties Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ko.properties Tue Aug 12 17:59:58 2008 -0700
@@ -101,30 +101,41 @@
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
--- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_sv.properties Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_sv.properties Tue Aug 12 17:59:58 2008 -0700
@@ -101,30 +101,41 @@
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
--- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_CN.properties Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_CN.properties Tue Aug 12 17:59:58 2008 -0700
@@ -101,30 +101,41 @@
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
--- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_TW.properties Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_TW.properties Tue Aug 12 17:59:58 2008 -0700
@@ -101,30 +101,41 @@
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
--- a/jdk/src/share/classes/java/awt/EventDispatchThread.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/java/awt/EventDispatchThread.java Tue Aug 12 17:59:58 2008 -0700
@@ -39,6 +39,7 @@
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 @@
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 @@
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) {
--- a/jdk/src/share/classes/java/beans/DefaultPersistenceDelegate.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/java/beans/DefaultPersistenceDelegate.java Tue Aug 12 17:59:58 2008 -0700
@@ -298,7 +298,7 @@
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});
--- a/jdk/src/share/classes/java/beans/EventHandler.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/java/beans/EventHandler.java Tue Aug 12 17:59:58 2008 -0700
@@ -404,7 +404,7 @@
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);
}
--- a/jdk/src/share/classes/java/beans/MetaData.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/java/beans/MetaData.java Tue Aug 12 17:59:58 2008 -0700
@@ -650,7 +650,7 @@
// 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 @@
// 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 @@
// 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);
}
}
}
--- a/jdk/src/share/classes/java/beans/PropertyChangeSupport.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/java/beans/PropertyChangeSupport.java Tue Aug 12 17:59:58 2008 -0700
@@ -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 @@
}
/**
- * 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;
+ 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();
+
+ PropertyChangeListener[] common = this.map.get(null);
+ PropertyChangeListener[] named = (name != null)
+ ? this.map.get(name)
+ : null;
+
+ fire(common, event);
+ fire(named, event);
}
- PropertyChangeListener[] common = this.map.get(null);
- PropertyChangeListener[] named = (propertyName != null)
- ? this.map.get(propertyName)
- : null;
-
- fire(common, evt);
- fire(named, evt);
}
- 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 @@
}
/**
- * 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));
}
/**
--- a/jdk/src/share/classes/java/beans/PropertyEditor.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/java/beans/PropertyEditor.java Tue Aug 12 17:59:58 2008 -0700
@@ -204,20 +204,21 @@
//----------------------------------------------------------------------
/**
- * 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);
--- a/jdk/src/share/classes/java/beans/PropertyEditorSupport.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/java/beans/PropertyEditorSupport.java Tue Aug 12 17:59:58 2008 -0700
@@ -233,11 +233,20 @@
//----------------------------------------------------------------------
/**
- * 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 @@
}
/**
- * 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) {
--- a/jdk/src/share/classes/java/beans/VetoableChangeSupport.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/java/beans/VetoableChangeSupport.java Tue Aug 12 17:59:58 2008 -0700
@@ -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 @@
}
/**
- * 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.
+ * 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
+ * {@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.
- * @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(String propertyName,
- Object oldValue, Object newValue)
- throws PropertyVetoException {
- if (oldValue != null && newValue != null && oldValue.equals(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));
}
- 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.
+ * 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,
- int oldValue, int 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, 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 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>
+ * 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, boolean oldValue, boolean newValue)
+ throws PropertyVetoException {
+ if (oldValue != newValue) {
+ fireVetoableChange(propertyName, Boolean.valueOf(oldValue), Boolean.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.
+ * 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 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 the given event's old and new values are equal and non-null.
*
- * @param evt The PropertyChangeEvent to be fired.
- * @exception PropertyVetoException if the recipient wishes the property
- * change to be rolled back.
+ * @param event the {@code PropertyChangeEvent} to be fired
+ * @throws PropertyVetoException if one of listeners vetoes the property update
*/
- public void fireVetoableChange(PropertyChangeEvent evt)
- throws PropertyVetoException {
+ 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();
- Object oldValue = evt.getOldValue();
- Object newValue = evt.getNewValue();
- String propertyName = evt.getPropertyName();
- if (oldValue != null && newValue != null && oldValue.equals(newValue)) {
- return;
- }
- VetoableChangeListener[] common = this.map.get(null);
- VetoableChangeListener[] named = (propertyName != null)
- ? this.map.get(propertyName)
- : null;
- fire(common, evt);
- fire(named, evt);
- }
+ VetoableChangeListener[] common = this.map.get(null);
+ VetoableChangeListener[] named = (name != null)
+ ? this.map.get(name)
+ : null;
- 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.
+ 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
+ }
}
}
}
--- a/jdk/src/share/classes/javax/swing/JApplet.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JApplet.java Tue Aug 12 17:59:58 2008 -0700
@@ -131,10 +131,7 @@
// 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
--- a/jdk/src/share/classes/javax/swing/RepaintManager.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/RepaintManager.java Tue Aug 12 17:59:58 2008 -0700
@@ -40,6 +40,8 @@
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 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 @@
* @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 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 @@
* 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 @@
* 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 @@
* 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 @@
* 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 @@
* 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 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 @@
prePaintDirtyRegions();
}
}
+ private RepaintManager getDelegate(Component c) {
+ RepaintManager delegate = SwingUtilities3.getDelegateRepaintManager(c);
+ if (this == delegate) {
+ delegate = null;
+ }
+ return delegate;
+ }
}
--- a/jdk/src/share/classes/javax/swing/SwingUtilities.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/SwingUtilities.java Tue Aug 12 17:59:58 2008 -0700
@@ -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 @@
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 @@
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 @@
// 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;
--- a/jdk/src/share/classes/javax/swing/TimerQueue.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/TimerQueue.java Tue Aug 12 17:59:58 2008 -0700
@@ -31,6 +31,7 @@
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 @@
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 @@
super();
queue = new DelayQueue<DelayedTimer>();
// Now start the TimerQueue thread.
- start();
+ runningLock = new ReentrantLock();
+ startIfNeeded();
}
@@ -87,33 +90,30 @@
}
- 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 @@
public void run() {
+ runningLock.lock();
try {
while (running) {
try {
@@ -195,14 +196,14 @@
}
}
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();
}
}
--- a/jdk/src/share/classes/javax/swing/border/CompoundBorder.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/border/CompoundBorder.java Tue Aug 12 17:59:58 2008 -0700
@@ -79,10 +79,13 @@
}
/**
- * 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());
--- a/jdk/src/share/classes/javax/swing/colorchooser/AbstractColorChooserPanel.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/colorchooser/AbstractColorChooserPanel.java Tue Aug 12 17:59:58 2008 -0700
@@ -160,7 +160,9 @@
* is editing
*/
public ColorSelectionModel getColorSelectionModel() {
- return chooser.getSelectionModel();
+ return (this.chooser != null)
+ ? this.chooser.getSelectionModel()
+ : null;
}
/**
@@ -168,7 +170,17 @@
* @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);
+ }
}
/**
--- a/jdk/src/share/classes/javax/swing/colorchooser/ColorChooserComponentFactory.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorChooserComponentFactory.java Tue Aug 12 17:59:58 2008 -0700
@@ -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 @@
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();
}
-
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorChooserPanel.java Tue Aug 12 17:59:58 2008 -0700
@@ -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);
+ }
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorModel.java Tue Aug 12 17:59:58 2008 -0700
@@ -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;
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorModelCMYK.java Tue Aug 12 17:59:58 2008 -0700
@@ -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;
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSL.java Tue Aug 12 17:59:58 2008 -0700
@@ -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;
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSV.java Tue Aug 12 17:59:58 2008 -0700
@@ -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;
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorPanel.java Tue Aug 12 17:59:58 2008 -0700
@@ -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;
+ }
+}
--- a/jdk/src/share/classes/javax/swing/colorchooser/DefaultHSBChooserPanel.java Thu Aug 07 09:42:31 2008 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -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();
- }
- }
- }
-
-}
--- a/jdk/src/share/classes/javax/swing/colorchooser/DefaultRGBChooserPanel.java Thu Aug 07 09:42:31 2008 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -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);
- }
- }
-
-}
--- a/jdk/src/share/classes/javax/swing/colorchooser/DefaultSwatchChooserPanel.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/colorchooser/DefaultSwatchChooserPanel.java Tue Aug 12 17:59:58 2008 -0700
@@ -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 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);
-
}
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/javax/swing/colorchooser/DiagramComponent.java Tue Aug 12 17:59:58 2008 -0700
@@ -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;
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/javax/swing/colorchooser/SlidingSpinner.java Tue Aug 12 17:59:58 2008 -0700
@@ -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();
+ }
+ }
+}
--- a/jdk/src/share/classes/javax/swing/colorchooser/SyntheticImage.java Thu Aug 07 09:42:31 2008 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -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> Image i = createImage(new SyntheticImage(200, 100) {
- * protected void computeRow(int y, int[] row) {
- * for(int i = width; --i>=0; ) {
- * int grey = i*255/(width-1);
- * row[i] = (255<<24)|(grey<<16)|(grey<<8)|grey;
- * }
- * }
- * }
- * </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;
- }
- }
- );
- }
-}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/javax/swing/colorchooser/ValueFormatter.java Tue Aug 12 17:59:58 2008 -0700
@@ -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;
+ }
+}
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicButtonListener.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicButtonListener.java Tue Aug 12 17:59:58 2008 -0700
@@ -165,7 +165,7 @@
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 @@
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 void mouseReleased(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
@@ -253,7 +253,7 @@
model.setPressed(false);
model.setArmed(false);
}
- };
+ }
public void mouseEntered(MouseEvent e) {
AbstractButton b = (AbstractButton) e.getSource();
@@ -263,7 +263,7 @@
}
if (model.isPressed())
model.setArmed(true);
- };
+ }
public void mouseExited(MouseEvent e) {
AbstractButton b = (AbstractButton) e.getSource();
@@ -272,7 +272,7 @@
model.setRollover(false);
}
model.setArmed(false);
- };
+ }
/**
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicButtonUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicButtonUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -237,7 +237,7 @@
/* 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 @@
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 @@
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;
}
}
}
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicColorChooserUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicColorChooserUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -299,8 +299,10 @@
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);
+ }
}
}
}
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxEditor.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxEditor.java Tue Aug 12 17:59:58 2008 -0700
@@ -92,7 +92,7 @@
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()});
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -1509,15 +1509,21 @@
|| 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.
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicDesktopIconUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicDesktopIconUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -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 @@
protected JInternalFrame.JDesktopIcon desktopIcon;
protected JInternalFrame frame;
+ private DesktopIconMover desktopIconMover;
/**
* The title pane component used in the desktop icon.
@@ -127,12 +128,21 @@
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() {
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicDirectoryModel.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicDirectoryModel.java Tue Aug 12 17:59:58 2008 -0700
@@ -43,10 +43,10 @@
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 @@
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 @@
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 @@
this.fid = fid;
}
- private void invokeLater(Runnable runnable) {
+ private void invokeLater(DoChangeContents runnable) {
runnables.addElement(runnable);
SwingUtilities.invokeLater(runnable);
}
@@ -245,9 +245,9 @@
}
// 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 @@
// 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 @@
}
}
- Vector newFileCache = new Vector(newDirectories);
+ Vector<File> newFileCache = new Vector<File>(newDirectories);
newFileCache.addAll(newFiles);
int newSize = newFileCache.size();
@@ -320,7 +320,7 @@
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 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 @@
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;
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicFileChooserUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicFileChooserUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -159,9 +159,9 @@
}
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 @@
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 @@
}
}
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 @@
}
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 @@
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 Icon getCachedIcon(File f) {
- return (Icon) iconCache.get(f);
+ return iconCache.get(f);
}
public void cacheIcon(File f, Icon i) {
@@ -1296,8 +1296,7 @@
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 @@
*/
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;
}
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicGraphicsUtils.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicGraphicsUtils.java Tue Aug 12 17:59:58 2008 -0700
@@ -266,7 +266,7 @@
return null;
}
- Icon icon = (Icon) b.getIcon();
+ Icon icon = b.getIcon();
String text = b.getText();
Font font = b.getFont();
@@ -277,7 +277,7 @@
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)
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java Tue Aug 12 17:59:58 2008 -0700
@@ -86,6 +86,7 @@
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 @@
}
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 @@
// 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 @@
}
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 CloseAction extends AbstractAction {
public CloseAction() {
- super(CLOSE_CMD);
+ super(UIManager.getString(
+ "InternalFrameTitlePane.closeButtonText"));
}
public void actionPerformed(ActionEvent e) {
@@ -616,7 +618,8 @@
*/
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 IconifyAction extends AbstractAction {
public IconifyAction() {
- super(ICONIFY_CMD);
+ super(UIManager.getString(
+ "InternalFrameTitlePane.minimizeButtonText"));
}
public void actionPerformed(ActionEvent e) {
@@ -664,7 +668,8 @@
*/
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 MoveAction extends AbstractAction {
public MoveAction() {
- super(MOVE_CMD);
+ super(UIManager.getString(
+ "InternalFrameTitlePane.moveButtonText"));
}
public void actionPerformed(ActionEvent e) {
@@ -723,7 +729,8 @@
*/
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 boolean isFocusTraversable() { return false; }
- public void requestFocus() {};
+ public void requestFocus() {}
public AccessibleContext getAccessibleContext() {
AccessibleContext ac = super.getAccessibleContext();
if (uiKey != null) {
@@ -783,6 +790,6 @@
}
return ac;
}
- }; // end NoFocusButton
+ } // end NoFocusButton
} // End Title Pane Class
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -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 @@
protected MouseInputAdapter borderListener;
protected PropertyChangeListener propertyChangeListener;
protected LayoutManager internalFrameLayout;
- protected ComponentListener componentListener;
protected MouseInputListener glassPaneDispatcher;
private InternalFrameListener internalFrameListener;
@@ -67,9 +66,9 @@
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 @@
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 @@
* @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 @@
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 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 @@
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 @@
}
}
- private static boolean isDragging = false;
private class Handler implements ComponentListener, InternalFrameListener,
LayoutManager, MouseInputListener, PropertyChangeListener,
WindowFocusListener, SwingConstants {
@@ -1230,15 +1227,6 @@
}
}
- // 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 @@
// MouseInputListener
- private Component mouseEventTarget = null;
- private Component dragSource = null;
-
public void mousePressed(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
@@ -1403,7 +1388,7 @@
// 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 @@
// 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 @@
} 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") {
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicLabelUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicLabelUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -65,6 +65,9 @@
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 @@
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 @@
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 @@
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 @@
}
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;
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicLookAndFeel.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicLookAndFeel.java Tue Aug 12 17:59:58 2008 -0700
@@ -2102,8 +2102,6 @@
* <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 @@
* 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 @@
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 @@
* 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);
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -25,9 +25,6 @@
package javax.swing.plaf.basic;
-import sun.swing.MenuItemCheckIconFactory;
-import sun.swing.SwingUtilities2;
-import static sun.swing.SwingUtilities2.BASICMENUITEMUI_MAX_TEXT_OFFSET;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
@@ -39,8 +36,7 @@
import javax.swing.plaf.*;
import javax.swing.text.View;
-import sun.swing.UIAction;
-import sun.swing.StringUIClientPropertyKey;
+import sun.swing.*;
/**
* BasicMenuItem implementation
@@ -91,24 +87,6 @@
private static final boolean VERBOSE = false; // show reuse hits/misses
private static final boolean DEBUG = false; // show bad params, misc.
- // Allows to reuse layoutInfo object.
- // Shouldn't be used directly. Use getLayoutInfo() instead.
- private final transient LayoutInfo layoutInfo = new LayoutInfo();
-
- /* Client Property keys for calculation of maximal widths */
- static final StringUIClientPropertyKey MAX_ARROW_WIDTH =
- new StringUIClientPropertyKey("maxArrowWidth");
- static final StringUIClientPropertyKey MAX_CHECK_WIDTH =
- new StringUIClientPropertyKey("maxCheckWidth");
- static final StringUIClientPropertyKey MAX_ICON_WIDTH =
- new StringUIClientPropertyKey("maxIconWidth");
- static final StringUIClientPropertyKey MAX_TEXT_WIDTH =
- new StringUIClientPropertyKey("maxTextWidth");
- static final StringUIClientPropertyKey MAX_ACC_WIDTH =
- new StringUIClientPropertyKey("maxAccWidth");
- static final StringUIClientPropertyKey MAX_LABEL_WIDTH =
- new StringUIClientPropertyKey("maxLabelWidth");
-
static void loadActionMap(LazyActionMap map) {
// NOTE: BasicMenuUI also calls into this method.
map.put(new Actions(Actions.CLICK));
@@ -199,13 +177,14 @@
//In case of column layout, .checkIconFactory is defined for this UI,
//the icon is compatible with it and useCheckAndArrow() is true,
//then the icon is handled by the checkIcon.
- boolean isColumnLayout = LayoutInfo.isColumnLayout(
+ boolean isColumnLayout = MenuItemLayoutHelper.isColumnLayout(
BasicGraphicsUtils.isLeftToRight(menuItem), menuItem);
if (isColumnLayout) {
MenuItemCheckIconFactory iconFactory =
(MenuItemCheckIconFactory) UIManager.get(prefix
+ ".checkIconFactory");
- if (iconFactory != null && useCheckAndArrow()
+ if (iconFactory != null
+ && MenuItemLayoutHelper.useCheckAndArrow(menuItem)
&& iconFactory.isCompatible(checkIcon, prefix)) {
checkIcon = iconFactory.getIcon(menuItem);
}
@@ -256,20 +235,7 @@
uninstallComponents(menuItem);
uninstallListeners();
uninstallKeyboardActions();
-
-
- // Remove values from the parent's Client Properties.
- JComponent p = getMenuItemParent(menuItem);
- if(p != null) {
- p.putClientProperty(BasicMenuItemUI.MAX_ARROW_WIDTH, null );
- p.putClientProperty(BasicMenuItemUI.MAX_CHECK_WIDTH, null );
- p.putClientProperty(BasicMenuItemUI.MAX_ACC_WIDTH, null );
- p.putClientProperty(BasicMenuItemUI.MAX_TEXT_WIDTH, null );
- p.putClientProperty(BasicMenuItemUI.MAX_ICON_WIDTH, null );
- p.putClientProperty(BasicMenuItemUI.MAX_LABEL_WIDTH, null );
- p.putClientProperty(BASICMENUITEMUI_MAX_TEXT_OFFSET, null );
- }
-
+ MenuItemLayoutHelper.clearUsedParentClientProperties(menuItem);
menuItem = null;
}
@@ -405,19 +371,6 @@
return d;
}
- // Returns parent of this component if it is not a top-level menu
- // Otherwise returns null
- private static JComponent getMenuItemParent(JMenuItem mi) {
- Container parent = mi.getParent();
- if ((parent instanceof JComponent) &&
- (!(mi instanceof JMenu) ||
- !((JMenu)mi).isTopLevelMenu())) {
- return (JComponent) parent;
- } else {
- return null;
- }
- }
-
protected Dimension getPreferredMenuItemSize(JComponent c,
Icon checkIcon,
Icon arrowIcon,
@@ -447,32 +400,36 @@
// the icon and text when user points a menu item by mouse.
JMenuItem mi = (JMenuItem) c;
- LayoutInfo li = getLayoutInfo(mi, checkIcon, arrowIcon,
- createMaxViewRect(), defaultTextIconGap, acceleratorDelimiter,
- BasicGraphicsUtils.isLeftToRight(mi), acceleratorFont,
- useCheckAndArrow(), getPropertyPrefix());
+ MenuItemLayoutHelper lh = new MenuItemLayoutHelper(mi, checkIcon,
+ arrowIcon, MenuItemLayoutHelper.createMaxRect(), defaultTextIconGap,
+ acceleratorDelimiter, BasicGraphicsUtils.isLeftToRight(mi),
+ mi.getFont(), acceleratorFont,
+ MenuItemLayoutHelper.useCheckAndArrow(menuItem),
+ getPropertyPrefix());
Dimension result = new Dimension();
// Calculate the result width
- result.width = li.leadingGap;
- addWidth(li.maxCheckWidth, li.afterCheckIconGap, result);
+ result.width = lh.getLeadingGap();
+ MenuItemLayoutHelper.addMaxWidth(lh.getCheckSize(),
+ lh.getAfterCheckIconGap(), result);
// Take into account mimimal text offset.
- if ((!li.isTopLevelMenu)
- && (li.minTextOffset > 0)
- && (result.width < li.minTextOffset)) {
- result.width = li.minTextOffset;
+ if ((!lh.isTopLevelMenu())
+ && (lh.getMinTextOffset() > 0)
+ && (result.width < lh.getMinTextOffset())) {
+ result.width = lh.getMinTextOffset();
}
- addWidth(li.maxLabelWidth, li.gap, result);
- addWidth(li.maxAccWidth, li.gap, result);
- addWidth(li.maxArrowWidth, li.gap, result);
+ MenuItemLayoutHelper.addMaxWidth(lh.getLabelSize(), lh.getGap(), result);
+ MenuItemLayoutHelper.addMaxWidth(lh.getAccSize(), lh.getGap(), result);
+ MenuItemLayoutHelper.addMaxWidth(lh.getArrowSize(), lh.getGap(), result);
// Calculate the result height
- result.height = max(li.checkRect.height, li.labelRect.height,
- li.accRect.height, li.arrowRect.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 = li.mi.getInsets();
+ Insets insets = lh.getMenuItem().getInsets();
if(insets != null) {
result.width += insets.left + insets.right;
result.height += insets.top + insets.bottom;
@@ -492,500 +449,9 @@
result.height++;
}
- li.clear();
return result;
}
- private Rectangle createMaxViewRect() {
- return new Rectangle(0,0,Short.MAX_VALUE, Short.MAX_VALUE);
- }
-
- private void addWidth(int width, int gap, Dimension result) {
- if (width > 0) {
- result.width += width + gap;
- }
- }
-
- private static int max(int... values) {
- int maxValue = Integer.MIN_VALUE;
- for (int i : values) {
- if (i > maxValue) {
- maxValue = i;
- }
- }
- return maxValue;
- }
-
- // LayoutInfo helps to calculate preferred size and to paint a menu item
- private static class LayoutInfo {
- JMenuItem mi;
- JComponent miParent;
-
- FontMetrics fm;
- FontMetrics accFm;
-
- Icon icon;
- Icon checkIcon;
- Icon arrowIcon;
- String text;
- String accText;
-
- boolean isColumnLayout;
- boolean useCheckAndArrow;
- boolean isLeftToRight;
- boolean isTopLevelMenu;
- View htmlView;
-
- int verticalAlignment;
- int horizontalAlignment;
- int verticalTextPosition;
- int horizontalTextPosition;
- int gap;
- int leadingGap;
- int afterCheckIconGap;
- int minTextOffset;
-
- Rectangle viewRect;
- Rectangle iconRect;
- Rectangle textRect;
- Rectangle accRect;
- Rectangle checkRect;
- Rectangle arrowRect;
- Rectangle labelRect;
-
- int origIconWidth;
- int origTextWidth;
- int origAccWidth;
- int origCheckWidth;
- int origArrowWidth;
-
- int maxIconWidth;
- int maxTextWidth;
- int maxAccWidth;
- int maxCheckWidth;
- int maxArrowWidth;
- int maxLabelWidth;
-
- // Empty constructor helps to create "final" LayoutInfo object
- public LayoutInfo() {
- }
-
- public LayoutInfo(JMenuItem mi, Icon checkIcon, Icon arrowIcon,
- Rectangle viewRect, int gap, String accDelimiter,
- boolean isLeftToRight, Font acceleratorFont,
- boolean useCheckAndArrow, String propertyPrefix) {
- reset(mi, checkIcon, arrowIcon, viewRect, gap, accDelimiter,
- isLeftToRight, acceleratorFont, useCheckAndArrow,
- propertyPrefix);
- }
-
- // Allows to reuse a LayoutInfo object
- public void reset(JMenuItem mi, Icon checkIcon, Icon arrowIcon,
- Rectangle viewRect, int gap, String accDelimiter,
- boolean isLeftToRight, Font acceleratorFont,
- boolean useCheckAndArrow, String propertyPrefix) {
- this.mi = mi;
- this.miParent = getMenuItemParent(mi);
- this.accText = getAccText(accDelimiter);
- this.verticalAlignment = mi.getVerticalAlignment();
- this.horizontalAlignment = mi.getHorizontalAlignment();
- this.verticalTextPosition = mi.getVerticalTextPosition();
- this.horizontalTextPosition = mi.getHorizontalTextPosition();
- this.useCheckAndArrow = useCheckAndArrow;
- this.fm = mi.getFontMetrics(mi.getFont());
- this.accFm = mi.getFontMetrics(acceleratorFont);
- this.isLeftToRight = isLeftToRight;
- this.isColumnLayout = isColumnLayout();
- this.isTopLevelMenu = (this.miParent == null)? true : false;
- this.checkIcon = checkIcon;
- this.icon = getIcon(propertyPrefix);
- this.arrowIcon = arrowIcon;
- this.text = mi.getText();
- this.gap = gap;
- this.afterCheckIconGap = getAfterCheckIconGap(propertyPrefix);
- this.minTextOffset = getMinTextOffset(propertyPrefix);
- this.htmlView = (View) mi.getClientProperty(BasicHTML.propertyKey);
-
- this.viewRect = viewRect;
- this.iconRect = new Rectangle();
- this.textRect = new Rectangle();
- this.accRect = new Rectangle();
- this.checkRect = new Rectangle();
- this.arrowRect = new Rectangle();
- this.labelRect = new Rectangle();
-
- calcWidthsAndHeights();
- this.origIconWidth = iconRect.width;
- this.origTextWidth = textRect.width;
- this.origAccWidth = accRect.width;
- this.origCheckWidth = checkRect.width;
- this.origArrowWidth = arrowRect.width;
-
- calcMaxWidths();
- this.leadingGap = getLeadingGap(propertyPrefix);
- calcMaxTextOffset();
- }
-
- // Clears fields to remove all links to other objects
- // to prevent memory leaks
- public void clear() {
- mi = null;
- miParent = null;
- fm = null;
- accFm = null;
- icon = null;
- checkIcon = null;
- arrowIcon = null;
- text = null;
- accText = null;
- htmlView = null;
- viewRect = null;
- iconRect = null;
- textRect = null;
- accRect = null;
- checkRect = null;
- arrowRect = null;
- labelRect = null;
- }
-
- private String getAccText(String acceleratorDelimiter) {
- String accText = "";
- KeyStroke accelerator = mi.getAccelerator();
- if (accelerator != null) {
- int modifiers = accelerator.getModifiers();
- if (modifiers > 0) {
- accText = KeyEvent.getKeyModifiersText(modifiers);
- accText += acceleratorDelimiter;
- }
- int keyCode = accelerator.getKeyCode();
- if (keyCode != 0) {
- accText += KeyEvent.getKeyText(keyCode);
- } else {
- accText += accelerator.getKeyChar();
- }
- }
- return accText;
- }
-
- // In case of column layout, .checkIconFactory is defined for this UI,
- // the icon is compatible with it and useCheckAndArrow() is true,
- // then the icon is handled by the checkIcon.
- private Icon getIcon(String propertyPrefix) {
- Icon icon = null;
- MenuItemCheckIconFactory iconFactory =
- (MenuItemCheckIconFactory) UIManager.get(propertyPrefix
- + ".checkIconFactory");
- if (!isColumnLayout || !useCheckAndArrow || iconFactory == null
- || !iconFactory.isCompatible(checkIcon, propertyPrefix)) {
- icon = mi.getIcon();
- }
- return icon;
- }
-
- private int getMinTextOffset(String propertyPrefix) {
- int minimumTextOffset = 0;
- Object minimumTextOffsetObject =
- UIManager.get(propertyPrefix + ".minimumTextOffset");
- if (minimumTextOffsetObject instanceof Integer) {
- minimumTextOffset = (Integer) minimumTextOffsetObject;
- }
- return minimumTextOffset;
- }
-
- private int getAfterCheckIconGap(String propertyPrefix) {
- int afterCheckIconGap = gap;
- Object afterCheckIconGapObject =
- UIManager.get(propertyPrefix + ".afterCheckIconGap");
- if (afterCheckIconGapObject instanceof Integer) {
- afterCheckIconGap = (Integer) afterCheckIconGapObject;
- }
- return afterCheckIconGap;
- }
-
- private int getLeadingGap(String propertyPrefix) {
- if (maxCheckWidth > 0) {
- return getCheckOffset(propertyPrefix);
- } else {
- return gap; // There is no any check icon
- }
- }
-
- private int getCheckOffset(String propertyPrefix) {
- int checkIconOffset = gap;
- Object checkIconOffsetObject =
- UIManager.get(propertyPrefix + ".checkIconOffset");
- if (checkIconOffsetObject instanceof Integer) {
- checkIconOffset = (Integer) checkIconOffsetObject;
- }
- return checkIconOffset;
- }
-
- private void calcWidthsAndHeights()
- {
- // iconRect
- if (icon != null) {
- iconRect.width = icon.getIconWidth();
- iconRect.height = icon.getIconHeight();
- }
-
- // accRect
- if (!accText.equals("")) {
- accRect.width = SwingUtilities2.stringWidth(
- mi, accFm, accText);
- accRect.height = accFm.getHeight();
- }
-
- // textRect
- if (text == null) {
- text = "";
- } else if (!text.equals("")) {
- if (htmlView != null) {
- // Text is HTML
- textRect.width =
- (int) htmlView.getPreferredSpan(View.X_AXIS);
- textRect.height =
- (int) htmlView.getPreferredSpan(View.Y_AXIS);
- } else {
- // Text isn't HTML
- textRect.width =
- SwingUtilities2.stringWidth(mi, fm, text);
- textRect.height = fm.getHeight();
- }
- }
-
- if (useCheckAndArrow) {
- // checkIcon
- if (checkIcon != null) {
- checkRect.width = checkIcon.getIconWidth();
- checkRect.height = checkIcon.getIconHeight();
- }
- // arrowRect
- if (arrowIcon != null) {
- arrowRect.width = arrowIcon.getIconWidth();
- arrowRect.height = arrowIcon.getIconHeight();
- }
- }
-
- // labelRect
- if (isColumnLayout) {
- labelRect.width = iconRect.width + textRect.width + gap;
- labelRect.height = max(checkRect.height, iconRect.height,
- textRect.height, accRect.height, arrowRect.height);
- } else {
- textRect = new Rectangle();
- iconRect = new Rectangle();
- SwingUtilities.layoutCompoundLabel(mi, fm, text, icon,
- verticalAlignment, horizontalAlignment,
- verticalTextPosition, horizontalTextPosition,
- viewRect, iconRect, textRect, gap);
- labelRect = iconRect.union(textRect);
- }
- }
-
- private void calcMaxWidths() {
- maxCheckWidth = calcMaxValue(BasicMenuItemUI.MAX_CHECK_WIDTH,
- checkRect.width);
- maxArrowWidth = calcMaxValue(BasicMenuItemUI.MAX_ARROW_WIDTH,
- arrowRect.width);
- maxAccWidth = calcMaxValue(BasicMenuItemUI.MAX_ACC_WIDTH,
- accRect.width);
-
- if (isColumnLayout) {
- maxIconWidth = calcMaxValue(BasicMenuItemUI.MAX_ICON_WIDTH,
- iconRect.width);
- maxTextWidth = calcMaxValue(BasicMenuItemUI.MAX_TEXT_WIDTH,
- textRect.width);
- int curGap = gap;
- if ((maxIconWidth == 0) || (maxTextWidth == 0)) {
- curGap = 0;
- }
- maxLabelWidth =
- calcMaxValue(BasicMenuItemUI.MAX_LABEL_WIDTH,
- maxIconWidth + maxTextWidth + curGap);
- } else {
- // We shouldn't use current icon and text widths
- // in maximal widths calculation for complex layout.
- maxIconWidth = getParentIntProperty(BasicMenuItemUI.MAX_ICON_WIDTH);
- maxLabelWidth = calcMaxValue(BasicMenuItemUI.MAX_LABEL_WIDTH,
- labelRect.width);
- // If maxLabelWidth is wider
- // than the widest icon + the widest text + gap,
- // we should update the maximal text witdh
- int candidateTextWidth = maxLabelWidth - maxIconWidth;
- if (maxIconWidth > 0) {
- candidateTextWidth -= gap;
- }
- maxTextWidth = calcMaxValue(BasicMenuItemUI.MAX_TEXT_WIDTH,
- candidateTextWidth);
- }
- }
-
- // Calculates and returns maximal value
- // through specified parent component client property.
- private int calcMaxValue(Object propertyName, int value) {
- // Get maximal value from parent client property
- int maxValue = getParentIntProperty(propertyName);
- // Store new maximal width in parent client property
- if (value > maxValue) {
- if (miParent != null) {
- miParent.putClientProperty(propertyName, value);
- }
- return value;
- } else {
- return maxValue;
- }
- }
-
- // Returns parent client property as int
- private int getParentIntProperty(Object propertyName) {
- Object value = null;
- if (miParent != null) {
- value = miParent.getClientProperty(propertyName);
- }
- if ((value == null) || !(value instanceof Integer)){
- value = 0;
- }
- return (Integer)value;
- }
-
- private boolean isColumnLayout() {
- return isColumnLayout(isLeftToRight, horizontalAlignment,
- horizontalTextPosition, verticalTextPosition);
- }
-
- public static boolean isColumnLayout(boolean isLeftToRight,
- JMenuItem mi) {
- assert(mi != null);
- return isColumnLayout(isLeftToRight, mi.getHorizontalAlignment(),
- mi.getHorizontalTextPosition(), mi.getVerticalTextPosition());
- }
-
- // Answers should we do column layout for a menu item or not.
- // We do it when a user doesn't set any alignments
- // and text positions manually, except the vertical alignment.
- public static boolean isColumnLayout( boolean isLeftToRight,
- int horizontalAlignment, int horizontalTextPosition,
- int verticalTextPosition) {
- if (verticalTextPosition != SwingConstants.CENTER) {
- return false;
- }
- if (isLeftToRight) {
- if (horizontalAlignment != SwingConstants.LEADING
- && horizontalAlignment != SwingConstants.LEFT) {
- return false;
- }
- if (horizontalTextPosition != SwingConstants.TRAILING
- && horizontalTextPosition != SwingConstants.RIGHT) {
- return false;
- }
- } else {
- if (horizontalAlignment != SwingConstants.LEADING
- && horizontalAlignment != SwingConstants.RIGHT) {
- return false;
- }
- if (horizontalTextPosition != SwingConstants.TRAILING
- && horizontalTextPosition != SwingConstants.LEFT) {
- return false;
- }
- }
- return true;
- }
-
- // Calculates maximal text offset.
- // It is required for some L&Fs (ex: Vista L&F).
- // The offset is meaningful only for L2R column layout.
- private void calcMaxTextOffset() {
- if (!isColumnLayout || !isLeftToRight) {
- return;
- }
-
- // Calculate the current text offset
- int offset = viewRect.x + leadingGap + maxCheckWidth
- + afterCheckIconGap + maxIconWidth + gap;
- if (maxCheckWidth == 0) {
- offset -= afterCheckIconGap;
- }
- if (maxIconWidth == 0) {
- offset -= gap;
- }
-
- // maximal text offset shouldn't be less than minimal text offset;
- if (offset < minTextOffset) {
- offset = minTextOffset;
- }
-
- // Calculate and store the maximal text offset
- calcMaxValue(BASICMENUITEMUI_MAX_TEXT_OFFSET, offset);
- }
-
- public String toString() {
- StringBuilder result = new StringBuilder();
- result.append(super.toString()).append("\n");
- result.append("accFm = ").append(accFm).append("\n");
- result.append("accRect = ").append(accRect).append("\n");
- result.append("accText = ").append(accText).append("\n");
- result.append("afterCheckIconGap = ").append(afterCheckIconGap)
- .append("\n");
- result.append("arrowIcon = ").append(arrowIcon).append("\n");
- result.append("arrowRect = ").append(arrowRect).append("\n");
- result.append("checkIcon = ").append(checkIcon).append("\n");
- result.append("checkRect = ").append(checkRect).append("\n");
- result.append("fm = ").append(fm).append("\n");
- result.append("gap = ").append(gap).append("\n");
- result.append("horizontalAlignment = ").append(horizontalAlignment)
- .append("\n");
- result.append("horizontalTextPosition = ")
- .append(horizontalTextPosition).append("\n");
- result.append("htmlView = ").append(htmlView).append("\n");
- result.append("icon = ").append(icon).append("\n");
- result.append("iconRect = ").append(iconRect).append("\n");
- result.append("isColumnLayout = ").append(isColumnLayout).append("\n");
- result.append("isLeftToRight = ").append(isLeftToRight).append("\n");
- result.append("isTopLevelMenu = ").append(isTopLevelMenu).append("\n");
- result.append("labelRect = ").append(labelRect).append("\n");
- result.append("leadingGap = ").append(leadingGap).append("\n");
- result.append("maxAccWidth = ").append(maxAccWidth).append("\n");
- result.append("maxArrowWidth = ").append(maxArrowWidth).append("\n");
- result.append("maxCheckWidth = ").append(maxCheckWidth).append("\n");
- result.append("maxIconWidth = ").append(maxIconWidth).append("\n");
- result.append("maxLabelWidth = ").append(maxLabelWidth).append("\n");
- result.append("maxTextWidth = ").append(maxTextWidth).append("\n");
- result.append("maxTextOffset = ")
- .append(getParentIntProperty(BASICMENUITEMUI_MAX_TEXT_OFFSET))
- .append("\n");
- result.append("mi = ").append(mi).append("\n");
- result.append("minTextOffset = ").append(minTextOffset).append("\n");
- result.append("miParent = ").append(miParent).append("\n");
- result.append("origAccWidth = ").append(origAccWidth).append("\n");
- result.append("origArrowWidth = ").append(origArrowWidth).append("\n");
- result.append("origCheckWidth = ").append(origCheckWidth).append("\n");
- result.append("origIconWidth = ").append(origIconWidth).append("\n");
- result.append("origTextWidth = ").append(origTextWidth).append("\n");
- result.append("text = ").append(text).append("\n");
- result.append("textRect = ").append(textRect).append("\n");
- result.append("useCheckAndArrow = ").append(useCheckAndArrow)
- .append("\n");
- result.append("verticalAlignment = ").append(verticalAlignment)
- .append("\n");
- result.append("verticalTextPosition = ")
- .append(verticalTextPosition).append("\n");
- result.append("viewRect = ").append(viewRect).append("\n");
- return result.toString();
- }
- } // End of LayoutInfo
-
- // Reuses layoutInfo object to reduce the amount of produced garbage
- private LayoutInfo getLayoutInfo(JMenuItem mi, Icon checkIcon, Icon arrowIcon,
- Rectangle viewRect, int gap, String accDelimiter,
- boolean isLeftToRight, Font acceleratorFont,
- boolean useCheckAndArrow, String propertyPrefix) {
- // layoutInfo is final and always not null
- layoutInfo.reset(mi, checkIcon, arrowIcon, viewRect,
- gap, accDelimiter, isLeftToRight, acceleratorFont,
- useCheckAndArrow, propertyPrefix);
- return layoutInfo;
- }
-
/**
* We draw the background in paintMenuItem()
* so override update (which fills the background of opaque
@@ -1016,122 +482,132 @@
Rectangle viewRect = new Rectangle(0, 0, mi.getWidth(), mi.getHeight());
applyInsets(viewRect, mi.getInsets());
- LayoutInfo li = getLayoutInfo(mi, checkIcon, arrowIcon,
- viewRect, defaultTextIconGap, acceleratorDelimiter,
- BasicGraphicsUtils.isLeftToRight(mi), acceleratorFont,
- useCheckAndArrow(), getPropertyPrefix());
- layoutMenuItem(li);
+ MenuItemLayoutHelper lh = new MenuItemLayoutHelper(mi, checkIcon,
+ arrowIcon, viewRect, defaultTextIconGap, acceleratorDelimiter,
+ BasicGraphicsUtils.isLeftToRight(mi), mi.getFont(),
+ acceleratorFont, MenuItemLayoutHelper.useCheckAndArrow(menuItem),
+ getPropertyPrefix());
+ MenuItemLayoutHelper.LayoutResult lr = lh.layoutMenuItem();
paintBackground(g, mi, background);
- paintCheckIcon(g, li, holdc, foreground);
- paintIcon(g, li, holdc);
- paintText(g, li);
- paintAccText(g, li);
- paintArrowIcon(g, li, foreground);
+ paintCheckIcon(g, lh, lr, holdc, foreground);
+ paintIcon(g, lh, lr, holdc);
+ paintText(g, lh, lr);
+ paintAccText(g, lh, lr);
+ paintArrowIcon(g, lh, lr, foreground);
// Restore original graphics font and color
g.setColor(holdc);
g.setFont(holdf);
-
- li.clear();
}
- private void paintIcon(Graphics g, LayoutInfo li, Color holdc) {
- if (li.icon != null) {
+ private void paintIcon(Graphics g, MenuItemLayoutHelper lh,
+ MenuItemLayoutHelper.LayoutResult lr, Color holdc) {
+ if (lh.getIcon() != null) {
Icon icon;
- ButtonModel model = li.mi.getModel();
+ ButtonModel model = lh.getMenuItem().getModel();
if (!model.isEnabled()) {
- icon = (Icon) li.mi.getDisabledIcon();
+ icon = lh.getMenuItem().getDisabledIcon();
} else if (model.isPressed() && model.isArmed()) {
- icon = (Icon) li.mi.getPressedIcon();
+ icon = lh.getMenuItem().getPressedIcon();
if (icon == null) {
// Use default icon
- icon = (Icon) li.mi.getIcon();
+ icon = lh.getMenuItem().getIcon();
}
} else {
- icon = (Icon) li.mi.getIcon();
+ icon = lh.getMenuItem().getIcon();
}
if (icon != null) {
- icon.paintIcon(li.mi, g, li.iconRect.x, li.iconRect.y);
+ icon.paintIcon(lh.getMenuItem(), g, lr.getIconRect().x,
+ lr.getIconRect().y);
g.setColor(holdc);
}
}
}
- private void paintCheckIcon(Graphics g, LayoutInfo li,
+ private void paintCheckIcon(Graphics g, MenuItemLayoutHelper lh,
+ MenuItemLayoutHelper.LayoutResult lr,
Color holdc, Color foreground) {
- if (li.checkIcon != null) {
- ButtonModel model = li.mi.getModel();
- if (model.isArmed()
- || (li.mi instanceof JMenu && model.isSelected())) {
+ if (lh.getCheckIcon() != null) {
+ ButtonModel model = lh.getMenuItem().getModel();
+ if (model.isArmed() || (lh.getMenuItem() instanceof JMenu
+ && model.isSelected())) {
g.setColor(foreground);
} else {
g.setColor(holdc);
}
- if (li.useCheckAndArrow) {
- li.checkIcon.paintIcon(li.mi, g, li.checkRect.x,
- li.checkRect.y);
+ if (lh.useCheckAndArrow()) {
+ lh.getCheckIcon().paintIcon(lh.getMenuItem(), g,
+ lr.getCheckRect().x, lr.getCheckRect().y);
}
g.setColor(holdc);
}
}
- private void paintAccText(Graphics g, LayoutInfo li) {
- if (!li.accText.equals("")) {
- ButtonModel model = li.mi.getModel();
- g.setFont(acceleratorFont);
+ private void paintAccText(Graphics g, MenuItemLayoutHelper lh,
+ MenuItemLayoutHelper.LayoutResult lr) {
+ if (!lh.getAccText().equals("")) {
+ ButtonModel model = lh.getMenuItem().getModel();
+ g.setFont(lh.getAccFontMetrics().getFont());
if (!model.isEnabled()) {
// *** paint the accText disabled
if (disabledForeground != null) {
g.setColor(disabledForeground);
- SwingUtilities2.drawString(li.mi, g, li.accText,
- li.accRect.x,
- li.accRect.y + li.accFm.getAscent());
+ SwingUtilities2.drawString(lh.getMenuItem(), g,
+ lh.getAccText(), lr.getAccRect().x,
+ lr.getAccRect().y + lh.getAccFontMetrics().getAscent());
} else {
- g.setColor(li.mi.getBackground().brighter());
- SwingUtilities2.drawString(li.mi, g, li.accText, li.accRect.x,
- li.accRect.y + li.accFm.getAscent());
- g.setColor(li.mi.getBackground().darker());
- SwingUtilities2.drawString(li.mi, g, li.accText,
- li.accRect.x - 1,
- li.accRect.y + li.accFm.getAscent() - 1);
+ g.setColor(lh.getMenuItem().getBackground().brighter());
+ SwingUtilities2.drawString(lh.getMenuItem(), g,
+ lh.getAccText(), lr.getAccRect().x,
+ lr.getAccRect().y + lh.getAccFontMetrics().getAscent());
+ g.setColor(lh.getMenuItem().getBackground().darker());
+ SwingUtilities2.drawString(lh.getMenuItem(), g,
+ lh.getAccText(), lr.getAccRect().x - 1,
+ lr.getAccRect().y + lh.getFontMetrics().getAscent() - 1);
}
} else {
// *** paint the accText normally
- if (model.isArmed() ||
- (li.mi instanceof JMenu && model.isSelected())) {
+ if (model.isArmed()
+ || (lh.getMenuItem() instanceof JMenu
+ && model.isSelected())) {
g.setColor(acceleratorSelectionForeground);
} else {
g.setColor(acceleratorForeground);
}
- SwingUtilities2.drawString(li.mi, g, li.accText, li.accRect.x,
- li.accRect.y + li.accFm.getAscent());
+ SwingUtilities2.drawString(lh.getMenuItem(), g, lh.getAccText(),
+ lr.getAccRect().x, lr.getAccRect().y +
+ lh.getAccFontMetrics().getAscent());
}
}
}
- private void paintText(Graphics g, LayoutInfo li) {
- if (!li.text.equals("")) {
- if (li.htmlView != null) {
+ private void paintText(Graphics g, MenuItemLayoutHelper lh,
+ MenuItemLayoutHelper.LayoutResult lr) {
+ if (!lh.getText().equals("")) {
+ if (lh.getHtmlView() != null) {
// Text is HTML
- li.htmlView.paint(g, li.textRect);
+ lh.getHtmlView().paint(g, lr.getTextRect());
} else {
// Text isn't HTML
- paintText(g, li.mi, li.textRect, li.text);
+ paintText(g, lh.getMenuItem(), lr.getTextRect(), lh.getText());
}
}
}
- private void paintArrowIcon(Graphics g, LayoutInfo li, Color foreground) {
- if (li.arrowIcon != null) {
- ButtonModel model = li.mi.getModel();
- if (model.isArmed()
- || (li.mi instanceof JMenu && model.isSelected())) {
+ private void paintArrowIcon(Graphics g, MenuItemLayoutHelper lh,
+ MenuItemLayoutHelper.LayoutResult lr,
+ Color foreground) {
+ if (lh.getArrowIcon() != null) {
+ ButtonModel model = lh.getMenuItem().getModel();
+ if (model.isArmed() || (lh.getMenuItem() instanceof JMenu
+ && model.isSelected())) {
g.setColor(foreground);
}
- if (li.useCheckAndArrow) {
- li.arrowIcon.paintIcon(li.mi, g, li.arrowRect.x, li.arrowRect.y);
+ if (lh.useCheckAndArrow()) {
+ lh.getArrowIcon().paintIcon(lh.getMenuItem(), g,
+ lr.getArrowRect().x, lr.getArrowRect().y);
}
}
}
@@ -1216,346 +692,6 @@
}
}
-
- /**
- * Layout icon, text, check icon, accelerator text and arrow icon
- * in the viewRect and return their positions.
- *
- * If horizontalAlignment, verticalTextPosition and horizontalTextPosition
- * are default (user doesn't set any manually) the layouting algorithm is:
- * Elements are layouted in the five columns:
- * check icon + icon + text + accelerator text + arrow icon
- *
- * In the other case elements are layouted in the four columns:
- * check icon + label + accelerator text + arrow icon
- * Label is icon and text rectangles union.
- *
- * The order of columns can be reversed.
- * It depends on the menu item orientation.
- */
- private void layoutMenuItem(LayoutInfo li)
- {
- li.checkRect.width = li.maxCheckWidth;
- li.accRect.width = li.maxAccWidth;
- li.arrowRect.width = li.maxArrowWidth;
-
- if (li.isColumnLayout) {
- if (li.isLeftToRight) {
- doLTRColumnLayout(li);
- } else {
- doRTLColumnLayout(li);
- }
- } else {
- if (li.isLeftToRight) {
- doLTRComplexLayout(li);
- } else {
- doRTLComplexLayout(li);
- }
- }
-
- alignAccCheckAndArrowVertically(li);
- }
-
- // Aligns the accelertor text and the check and arrow icons vertically
- // with the center of the label rect.
- private void alignAccCheckAndArrowVertically(LayoutInfo li) {
- li.accRect.y = (int)(li.labelRect.y + (float)li.labelRect.height/2
- - (float)li.accRect.height/2);
- fixVerticalAlignment(li, li.accRect);
- if (li.useCheckAndArrow) {
- li.arrowRect.y = (int)(li.labelRect.y + (float)li.labelRect.height/2
- - (float)li.arrowRect.height/2);
- li.checkRect.y = (int)(li.labelRect.y + (float)li.labelRect.height/2
- - (float)li.checkRect.height/2);
- fixVerticalAlignment(li, li.arrowRect);
- fixVerticalAlignment(li, li.checkRect);
- }
- }
-
- // Fixes vertical alignment of all menu item elements if a rect.y
- // or (rect.y + rect.height) is out of viewRect bounds
- private void fixVerticalAlignment(LayoutInfo li, Rectangle r) {
- int delta = 0;
- if (r.y < li.viewRect.y) {
- delta = li.viewRect.y - r.y;
- } else if (r.y + r.height > li.viewRect.y + li.viewRect.height) {
- delta = li.viewRect.y + li.viewRect.height - r.y - r.height;
- }
- if (delta != 0) {
- li.checkRect.y += delta;
- li.iconRect.y += delta;
- li.textRect.y += delta;
- li.accRect.y += delta;
- li.arrowRect.y += delta;
- }
- }
-
- private void doLTRColumnLayout(LayoutInfo li) {
- // Set maximal width for all the five basic rects
- // (three other ones are already maximal)
- li.iconRect.width = li.maxIconWidth;
- li.textRect.width = li.maxTextWidth;
-
- // Set X coordinates
- // All rects will be aligned at the left side
- calcXPositionsL2R(li.viewRect.x, li.leadingGap, li.gap, li.checkRect,
- li.iconRect, li.textRect);
-
- // Tune afterCheckIconGap
- if (li.checkRect.width > 0) { // there is the afterCheckIconGap
- li.iconRect.x += li.afterCheckIconGap - li.gap;
- li.textRect.x += li.afterCheckIconGap - li.gap;
- }
-
- calcXPositionsR2L(li.viewRect.x + li.viewRect.width, li.gap,
- li.arrowRect, li.accRect);
-
- // Take into account minimal text offset
- int textOffset = li.textRect.x - li.viewRect.x;
- if (!li.isTopLevelMenu && (textOffset < li.minTextOffset)) {
- li.textRect.x += li.minTextOffset - textOffset;
- }
-
- // Take into account the left side bearings for text and accelerator text.
- fixTextRects(li);
-
- // Set Y coordinate for text and icon.
- // Y coordinates for other rects
- // will be calculated later in layoutMenuItem.
- calcTextAndIconYPositions(li);
-
- // Calculate valid X and Y coordinates for labelRect
- li.labelRect = li.textRect.union(li.iconRect);
- }
-
- private void doLTRComplexLayout(LayoutInfo li) {
- li.labelRect.width = li.maxLabelWidth;
-
- // Set X coordinates
- calcXPositionsL2R(li.viewRect.x, li.leadingGap, li.gap, li.checkRect,
- li.labelRect);
-
- // Tune afterCheckIconGap
- if (li.checkRect.width > 0) { // there is the afterCheckIconGap
- li.labelRect.x += li.afterCheckIconGap - li.gap;
- }
-
- calcXPositionsR2L(li.viewRect.x + li.viewRect.width, li.gap,
- li.arrowRect, li.accRect);
-
- // Take into account minimal text offset
- int labelOffset = li.labelRect.x - li.viewRect.x;
- if (!li.isTopLevelMenu && (labelOffset < li.minTextOffset)) {
- li.labelRect.x += li.minTextOffset - labelOffset;
- }
-
- // Take into account the left side bearing for accelerator text.
- // The LSB for text is taken into account in layoutCompoundLabel() below.
- fixAccTextRect(li);
-
- // Layout icon and text with SwingUtilities.layoutCompoundLabel()
- // within the labelRect
- li.textRect = new Rectangle();
- li.iconRect = new Rectangle();
- SwingUtilities.layoutCompoundLabel(
- li.mi, li.fm, li.text, li.icon, li.verticalAlignment,
- li.horizontalAlignment, li.verticalTextPosition,
- li.horizontalTextPosition, li.labelRect,
- li.iconRect, li.textRect, li.gap);
- }
-
- private void doRTLColumnLayout(LayoutInfo li) {
- // Set maximal width for all the five basic rects
- // (three other ones are already maximal)
- li.iconRect.width = li.maxIconWidth;
- li.textRect.width = li.maxTextWidth;
-
- // Set X coordinates
- calcXPositionsR2L(li.viewRect.x + li.viewRect.width, li.leadingGap,
- li.gap, li.checkRect, li.iconRect, li.textRect);
-
- // Tune the gap after check icon
- if (li.checkRect.width > 0) { // there is the gap after check icon
- li.iconRect.x -= li.afterCheckIconGap - li.gap;
- li.textRect.x -= li.afterCheckIconGap - li.gap;
- }
-
- calcXPositionsL2R(li.viewRect.x, li.gap, li.arrowRect,
- li.accRect);
-
- // Take into account minimal text offset
- int textOffset = (li.viewRect.x + li.viewRect.width)
- - (li.textRect.x + li.textRect.width);
- if (!li.isTopLevelMenu && (textOffset < li.minTextOffset)) {
- li.textRect.x -= li.minTextOffset - textOffset;
- }
-
- // Align icon, text, accelerator text, check icon and arrow icon
- // at the right side
- rightAlignAllRects(li);
-
- // Take into account the left side bearings for text and accelerator text.
- fixTextRects(li);
-
- // Set Y coordinates for text and icon.
- // Y coordinates for other rects
- // will be calculated later in layoutMenuItem.
- calcTextAndIconYPositions(li);
-
- // Calculate valid X and Y coordinate for labelRect
- li.labelRect = li.textRect.union(li.iconRect);
- }
-
- private void doRTLComplexLayout(LayoutInfo li) {
- li.labelRect.width = li.maxLabelWidth;
-
- // Set X coordinates
- calcXPositionsR2L(li.viewRect.x + li.viewRect.width, li.leadingGap,
- li.gap, li.checkRect, li.labelRect);
-
- // Tune the gap after check icon
- if (li.checkRect.width > 0) { // there is the gap after check icon
- li.labelRect.x -= li.afterCheckIconGap - li.gap;
- }
-
- calcXPositionsL2R(li.viewRect.x, li.gap, li.arrowRect,
- li.accRect);
-
- // Take into account minimal text offset
- int labelOffset = (li.viewRect.x + li.viewRect.width)
- - (li.labelRect.x + li.labelRect.width);
- if (!li.isTopLevelMenu && (labelOffset < li.minTextOffset)) {
- li.labelRect.x -= li.minTextOffset - labelOffset;
- }
-
- // Align icon, text, accelerator text, check icon and arrow icon
- // at the right side
- rightAlignAllRects(li);
-
- // Take into account the left side bearing for accelerator text.
- // The LSB for text is taken into account in layoutCompoundLabel() below.
- fixAccTextRect(li);
-
- // Layout icon and text with SwingUtilities.layoutCompoundLabel()
- // within the labelRect
- li.textRect = new Rectangle();
- li.iconRect = new Rectangle();
- SwingUtilities.layoutCompoundLabel(
- menuItem, li.fm, li.text, li.icon, li.verticalAlignment,
- li.horizontalAlignment, li.verticalTextPosition,
- li.horizontalTextPosition, li.labelRect,
- li.iconRect, li.textRect, li.gap);
- }
-
- private void calcXPositionsL2R(int startXPos, int leadingGap,
- int gap, Rectangle... rects) {
- int curXPos = startXPos + leadingGap;
- for (Rectangle rect : rects) {
- rect.x = curXPos;
- if (rect.width > 0) {
- curXPos += rect.width + gap;
- }
- }
- }
-
- private void calcXPositionsL2R(int startXPos, int gap, Rectangle... rects) {
- calcXPositionsL2R(startXPos, gap, gap, rects);
- }
-
- private void calcXPositionsR2L(int startXPos, int leadingGap,
- int gap, Rectangle... rects) {
- int curXPos = startXPos - leadingGap;
- for (Rectangle rect : rects) {
- rect.x = curXPos - rect.width;
- if (rect.width > 0) {
- curXPos -= rect.width + gap;
- }
- }
- }
-
- private void calcXPositionsR2L(int startXPos, int gap, Rectangle... rects) {
- calcXPositionsR2L(startXPos, gap, gap, rects);
- }
-
- // Takes into account the left side bearings for text and accelerator text
- private void fixTextRects(LayoutInfo li) {
- if (li.htmlView == null) { // The text isn't a HTML
- int lsb = SwingUtilities2.getLeftSideBearing(li.mi, li.fm, li.text);
- if (lsb < 0) {
- li.textRect.x -= lsb;
- }
- }
- fixAccTextRect(li);
- }
-
- // Takes into account the left side bearing for accelerator text
- private void fixAccTextRect(LayoutInfo li) {
- int lsb = SwingUtilities2
- .getLeftSideBearing(li.mi, li.accFm, li.accText);
- if (lsb < 0) {
- li.accRect.x -= lsb;
- }
- }
-
- // Sets Y coordinates of text and icon
- // taking into account the vertical alignment
- private void calcTextAndIconYPositions(LayoutInfo li) {
- if (li.verticalAlignment == SwingUtilities.TOP) {
- li.textRect.y = (int)(li.viewRect.y
- + (float)li.labelRect.height/2
- - (float)li.textRect.height/2);
- li.iconRect.y = (int)(li.viewRect.y
- + (float)li.labelRect.height/2
- - (float)li.iconRect.height/2);
- } else if (li.verticalAlignment == SwingUtilities.CENTER) {
- li.textRect.y = (int)(li.viewRect.y
- + (float)li.viewRect.height/2
- - (float)li.textRect.height/2);
- li.iconRect.y = (int)(li.viewRect.y
- + (float)li.viewRect.height/2
- - (float)li.iconRect.height/2);
- }
- else if (li.verticalAlignment == SwingUtilities.BOTTOM) {
- li.textRect.y = (int)(li.viewRect.y + li.viewRect.height
- - (float)li.labelRect.height/2
- - (float)li.textRect.height/2);
- li.iconRect.y = (int)(li.viewRect.y + li.viewRect.height
- - (float)li.labelRect.height/2
- - (float)li.iconRect.height/2);
- }
- }
-
- // Aligns icon, text, accelerator text, check icon and arrow icon
- // at the right side
- private void rightAlignAllRects(LayoutInfo li) {
- li.iconRect.x = li.iconRect.x + li.iconRect.width - li.origIconWidth;
- li.iconRect.width = li.origIconWidth;
- li.textRect.x = li.textRect.x + li.textRect.width - li.origTextWidth;
- li.textRect.width = li.origTextWidth;
- li.accRect.x = li.accRect.x + li.accRect.width
- - li.origAccWidth;
- li.accRect.width = li.origAccWidth;
- li.checkRect.x = li.checkRect.x + li.checkRect.width
- - li.origCheckWidth;
- li.checkRect.width = li.origCheckWidth;
- li.arrowRect.x = li.arrowRect.x + li.arrowRect.width -
- li.origArrowWidth;
- li.arrowRect.width = li.origArrowWidth;
- }
-
- /*
- * Returns false if the component is a JMenu and it is a top
- * level menu (on the menubar).
- */
- private boolean useCheckAndArrow(){
- boolean b = true;
- if((menuItem instanceof JMenu) &&
- (((JMenu)menuItem).isTopLevelMenu())) {
- b = false;
- }
- return b;
- }
-
public MenuElement[] getPath() {
MenuSelectionManager m = MenuSelectionManager.defaultManager();
MenuElement oldPath[] = m.getSelectedPath();
@@ -1601,7 +737,7 @@
for(i=0,j=path.length; i<j ;i++){
for (int k=0; k<=i; k++)
System.out.print(" ");
- MenuElement me = (MenuElement) path[i];
+ MenuElement me = path[i];
if(me instanceof JMenuItem)
System.out.println(((JMenuItem)me).getText() + ", ");
else if (me == null)
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -123,9 +123,9 @@
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 @@
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 @@
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 @@
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 @@
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()
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -109,7 +109,7 @@
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 @@
* <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 @@
} 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 @@
if (len <= 0) {
return;
}
- int nl = -1;
+ int nl;
int nll = 0;
if ((nl = s.indexOf(newline)) >= 0) {
@@ -1320,7 +1320,7 @@
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 @@
}
JButton createButton() {
- JButton button = null;
+ JButton button;
if (minimumWidth > 0) {
button = new ConstrainedButton(text, minimumWidth);
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicPopupMenuUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicPopupMenuUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -225,14 +225,14 @@
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 @@
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 @@
}
if (matches == 0) {
- ; // no op
+ // no op
} else if (matches == 1) {
// Invoke the menu action
JMenuItem item = (JMenuItem)items[firstMatch];
@@ -362,7 +362,7 @@
// 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 @@
manager.setSelectedPath(newPath);
e.consume();
}
- return;
}
public void menuKeyReleased(MenuKeyEvent e) {
@@ -625,7 +624,7 @@
// 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 @@
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 @@
// 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 @@
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 @@
// 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();
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicRadioButtonUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicRadioButtonUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -150,15 +150,15 @@
}
} 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 @@
String text = b.getText();
- Icon buttonIcon = (Icon) b.getIcon();
+ Icon buttonIcon = b.getIcon();
if(buttonIcon == null) {
buttonIcon = getDefaultIcon();
}
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicSplitPaneUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicSplitPaneUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -106,13 +106,13 @@
* 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 @@
// 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 @@
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 @@
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 @@
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);
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicTabbedPaneUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicTabbedPaneUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -142,9 +142,9 @@
private Component visibleComponent;
// PENDING(api): See comment for ContainerHandler
- private Vector htmlViews;
-
- private Hashtable mnemonicToIndexMap;
+ private Vector<View> htmlViews;
+
+ private Hashtable<Integer, Integer> mnemonicToIndexMap;
/**
* InputMap used for mnemonics. Only non-null if the JTabbedPane has
@@ -546,7 +546,7 @@
* 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 @@
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 @@
tabPane.putClientProperty("html", v);
}
- SwingUtilities.layoutCompoundLabel((JComponent) tabPane,
+ SwingUtilities.layoutCompoundLabel(tabPane,
metrics, title, icon,
SwingUtilities.CENTER,
SwingUtilities.CENTER,
@@ -1694,7 +1694,7 @@
*/
protected View getTextViewForTab(int tabIndex) {
if (htmlViews != null) {
- return (View)htmlViews.elementAt(tabIndex);
+ return htmlViews.elementAt(tabIndex);
}
return null;
}
@@ -2230,8 +2230,7 @@
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 @@
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 @@
// 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 @@
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 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 @@
}
}
- 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++) {
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicTextUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicTextUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -526,16 +526,16 @@
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 @@
*
* @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 @@
}
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 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 @@
* 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 @@
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
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicToggleButtonUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicToggleButtonUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -125,31 +125,31 @@
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);
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicToolBarUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicToolBarUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -83,8 +83,8 @@
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 @@
uninstallKeyboardActions();
// Clear instance vars
- if (isFloating() == true)
+ if (isFloating())
setFloating(false, null);
floatingToolBar = null;
@@ -273,9 +273,8 @@
// 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 @@
// 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 @@
// 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 @@
// 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 @@
// 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 @@
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 @@
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 @@
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 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 @@
protected void dragTo(Point position, Point origin)
{
- if (toolBar.isFloatable() == true)
+ if (toolBar.isFloatable())
{
try
{
@@ -1003,7 +1001,7 @@
protected void floatAt(Point position, Point origin)
{
- if(toolBar.isFloatable() == true)
+ if(toolBar.isFloatable())
{
try
{
@@ -1174,7 +1172,7 @@
if (!tb.isEnabled()) {
return;
}
- if (isDragging == true) {
+ if (isDragging) {
Point position = evt.getPoint();
if (origin == null)
origin = evt.getComponent().getLocationOnScreen();
@@ -1242,7 +1240,7 @@
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;
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicTreeUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicTreeUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -1263,7 +1263,7 @@
}
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 @@
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 @@
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 @@
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 @@
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 @@
*/
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 @@
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;
}
--- a/jdk/src/share/classes/javax/swing/plaf/basic/DefaultMenuLayout.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/DefaultMenuLayout.java Tue Aug 12 17:59:58 2008 -0700
@@ -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 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 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);
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/DesktopIconMover.java Tue Aug 12 17:59:58 2008 -0700
@@ -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) {
+ }
+}
--- a/jdk/src/share/classes/javax/swing/plaf/basic/DragRecognitionSupport.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/DragRecognitionSupport.java Tue Aug 12 17:59:58 2008 -0700
@@ -73,8 +73,7 @@
* 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 @@
* 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() {
--- a/jdk/src/share/classes/javax/swing/plaf/basic/LazyActionMap.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/LazyActionMap.java Tue Aug 12 17:59:58 2008 -0700
@@ -142,7 +142,7 @@
Object loader = _loader;
_loader = null;
- Class klass = (Class)loader;
+ Class<?> klass = (Class<?>)loader;
try {
Method method = klass.getDeclaredMethod("loadActionMap",
new Class[] { LazyActionMap.class });
--- a/jdk/src/share/classes/javax/swing/plaf/metal/DefaultMetalTheme.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/metal/DefaultMetalTheme.java Tue Aug 12 17:59:58 2008 -0700
@@ -387,9 +387,9 @@
* 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));
}
}
--- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalBumps.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalBumps.java Tue Aug 12 17:59:58 2008 -0700
@@ -49,7 +49,7 @@
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 @@
}
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 @@
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);
--- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -782,7 +782,7 @@
} 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 @@
* 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 @@
// 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 @@
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 @@
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 @@
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 @@
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;
}
}
--- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalIconFactory.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalIconFactory.java Tue Aug 12 17:59:58 2008 -0700
@@ -598,7 +598,7 @@
}
// 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 @@
// 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 @@
}
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 @@
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;
--- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalInternalFrameTitlePane.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalInternalFrameTitlePane.java Tue Aug 12 17:59:58 2008 -0700
@@ -191,7 +191,7 @@
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 @@
}
// Compute height.
- int height = 0;
+ int height;
if (isPalette) {
height = paletteTitleHeight;
} else {
@@ -410,7 +410,7 @@
g.drawLine ( width - 1, 0 , width -1, 0);
- int titleLength = 0;
+ int titleLength;
int xOffset = leftToRight ? 5 : width - 5;
String frameTitle = frame.getTitle();
--- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java Tue Aug 12 17:59:58 2008 -0700
@@ -2208,9 +2208,9 @@
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 @@
}
}
- static ReferenceQueue queue = new ReferenceQueue();
+ static ReferenceQueue<LookAndFeel> queue = new ReferenceQueue<LookAndFeel>();
static void flushUnreferenced() {
AATextListener aatl;
@@ -2283,7 +2283,7 @@
}
static class AATextListener
- extends WeakReference implements PropertyChangeListener {
+ extends WeakReference<LookAndFeel> implements PropertyChangeListener {
private String key = SunToolkit.DESKTOPFONTHINTS;
@@ -2294,7 +2294,7 @@
}
public void propertyChange(PropertyChangeEvent pce) {
- LookAndFeel laf = (LookAndFeel)get();
+ LookAndFeel laf = get();
if (laf == null || laf != UIManager.getLookAndFeel()) {
dispose();
return;
@@ -2318,8 +2318,8 @@
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 @@
*/
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);
}
}
--- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalRadioButtonUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalRadioButtonUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -164,15 +164,15 @@
}
} 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) {
--- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalToolBarUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalToolBarUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -61,7 +61,7 @@
* 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 @@
// 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 @@
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);
--- a/jdk/src/share/classes/javax/swing/plaf/synth/DefaultMenuLayout.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/DefaultMenuLayout.java Tue Aug 12 17:59:58 2008 -0700
@@ -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 @@
super(target, axis);
}
- public void invalidateLayout(Container target) {
+ public Dimension preferredLayoutSize(Container target) {
if (target instanceof JPopupMenu) {
- SynthPopupMenuUI popupUI = (SynthPopupMenuUI)((JPopupMenu)target).
- getUI();
- popupUI.resetAlignmentHints();
+ 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);
- }
- public Dimension preferredLayoutSize(Container target) {
- if (target instanceof JPopupMenu && target.getComponentCount() == 0) {
- return new Dimension(0, 0);
- }
return super.preferredLayoutSize(target);
}
}
--- a/jdk/src/share/classes/javax/swing/plaf/synth/DefaultSynthStyleFactory.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/DefaultSynthStyleFactory.java Tue Aug 12 17:59:58 2008 -0700
@@ -63,7 +63,7 @@
/**
* 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 @@
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 @@
* 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 @@
/**
* 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 @@
/**
* 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 @@
* 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) {
--- a/jdk/src/share/classes/javax/swing/plaf/synth/ImagePainter.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/ImagePainter.java Tue Aug 12 17:59:58 2008 -0700
@@ -66,7 +66,7 @@
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;
--- a/jdk/src/share/classes/javax/swing/plaf/synth/Region.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/Region.java Tue Aug 12 17:59:58 2008 -0700
@@ -67,8 +67,8 @@
* @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 @@
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 @@
*/
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);
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthButtonUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthButtonUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -262,7 +262,7 @@
* 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 @@
* 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);
}
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthComboBoxUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthComboBoxUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -336,7 +336,7 @@
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()});
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthContext.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthContext.java Tue Aug 12 17:59:58 2008 -0700
@@ -39,7 +39,7 @@
* @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 @@
static {
- contextMap = new HashMap();
+ contextMap = new HashMap<Class, List<SynthContext>>();
}
@@ -58,13 +58,13 @@
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 @@
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);
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthEditorPaneUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthEditorPaneUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -45,8 +45,8 @@
* 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 @@
c.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES,
localTrue);
}
- updateStyle((JTextComponent)getComponent());
+ updateStyle(getComponent());
}
protected void uninstallDefaults() {
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthGraphicsUtils.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthGraphicsUtils.java Tue Aug 12 17:59:58 2008 -0700
@@ -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 @@
}
+ /**
+ * 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 @@
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;
}
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameTitlePane.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameTitlePane.java Tue Aug 12 17:59:58 2008 -0700
@@ -197,25 +197,25 @@
protected void addSystemMenuItems(JPopupMenu menu) {
// PENDING: this should all be localizable!
- 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');
menu.add(new JSeparator());
- mi = (JMenuItem)menu.add(closeAction);
+ mi = menu.add(closeAction);
mi.setMnemonic('C');
}
protected void showSystemMenu() {
Insets insets = frame.getInsets();
if (!frame.isIcon()) {
- systemPopupMenu.show(frame, insets.left, getY() + getHeight());
+ systemPopupMenu.show(frame, menuButton.getX(), getY() + getHeight());
} else {
systemPopupMenu.show(menuButton,
getX() - insets.left - insets.right,
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthLookAndFeel.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthLookAndFeel.java Tue Aug 12 17:59:58 2008 -0700
@@ -107,7 +107,7 @@
* Map of defaults table entries. This is populated via the load
* method.
*/
- private Map defaultsMap;
+ private Map<String, Object> defaultsMap;
private Handler _handler;
@@ -308,8 +308,8 @@
children = ((Container)c).getComponents();
}
if (children != null) {
- for(int i = 0; i < children.length; i++) {
- updateStyles(children[i]);
+ for (Component child : children) {
+ updateStyles(child);
}
}
}
@@ -581,7 +581,7 @@
}
if (defaultsMap == null) {
- defaultsMap = new HashMap();
+ defaultsMap = new HashMap<String, Object>();
}
new SynthParser().parse(input, (DefaultSynthStyleFactory) factory,
@@ -611,7 +611,7 @@
}
if (defaultsMap == null) {
- defaultsMap = new HashMap();
+ defaultsMap = new HashMap<String, Object>();
}
InputStream input = url.openStream();
@@ -771,7 +771,7 @@
*/
private static Object getAATextInfo() {
String language = Locale.getDefault().getLanguage();
- String desktop = (String)
+ String desktop =
AccessController.doPrivileged(new GetPropertyAction("sun.desktop"));
boolean isCjkLocale = (Locale.CHINESE.getLanguage().equals(language) ||
@@ -786,7 +786,7 @@
return aaTextInfo;
}
- private static ReferenceQueue queue = new ReferenceQueue();
+ private static ReferenceQueue<LookAndFeel> queue = new ReferenceQueue<LookAndFeel>();
private static void flushUnreferenced() {
AATextListener aatl;
@@ -796,7 +796,7 @@
}
private static class AATextListener
- extends WeakReference implements PropertyChangeListener {
+ extends WeakReference<LookAndFeel> implements PropertyChangeListener {
private String key = SunToolkit.DESKTOPFONTHINTS;
AATextListener(LookAndFeel laf) {
@@ -812,7 +812,7 @@
return;
}
- LookAndFeel laf = (LookAndFeel) get();
+ LookAndFeel laf = get();
if (laf == null || laf != UIManager.getLookAndFeel()) {
dispose();
return;
@@ -835,8 +835,8 @@
private static void updateWindowUI(Window window) {
updateStyles(window);
Window ownedWins[] = window.getOwnedWindows();
- for (int i = 0; i < ownedWins.length; i++) {
- updateWindowUI(ownedWins[i]);
+ for (Window w : ownedWins) {
+ updateWindowUI(w);
}
}
@@ -845,8 +845,8 @@
*/
private static void updateAllUIs() {
Frame appFrames[] = Frame.getFrames();
- for (int i = 0; i < appFrames.length; i++) {
- updateWindowUI(appFrames[i]);
+ for (Frame frame : appFrames) {
+ updateWindowUI(frame);
}
}
@@ -909,7 +909,7 @@
// register it on the new one.
KeyboardFocusManager manager =
(KeyboardFocusManager)evt.getSource();
- if (((Boolean)newValue).equals(Boolean.FALSE)) {
+ if (newValue.equals(Boolean.FALSE)) {
manager.removePropertyChangeListener(_handler);
}
else {
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemLayoutHelper.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,307 @@
+/*
+ * 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
+ * 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.synth;
+
+import sun.swing.StringUIClientPropertyKey;
+import sun.swing.MenuItemLayoutHelper;
+import sun.swing.plaf.synth.SynthIcon;
+
+import javax.swing.*;
+import javax.swing.text.View;
+import java.awt.*;
+
+/**
+ * Calculates preferred size and layouts synth menu items.
+ *
+ * All JMenuItems (and JMenus) include enough space for the insets
+ * plus one or more elements. When we say "label" below, we mean
+ * "icon and/or text."
+ *
+ * Cases to consider for SynthMenuItemUI (visualized here in a
+ * LTR orientation; the RTL case would be reversed):
+ * label
+ * check icon + label
+ * check icon + label + accelerator
+ * label + accelerator
+ *
+ * Cases to consider for SynthMenuUI (again visualized here in a
+ * LTR orientation):
+ * label + arrow
+ *
+ * Note that in the above scenarios, accelerator and arrow icon are
+ * mutually exclusive. This means that if a popup menu contains a mix
+ * of JMenus and JMenuItems, we only need to allow enough space for
+ * max(maxAccelerator, maxArrow), and both accelerators and arrow icons
+ * can occupy the same "column" of space in the menu.
+ */
+class SynthMenuItemLayoutHelper extends MenuItemLayoutHelper {
+
+ public static final StringUIClientPropertyKey MAX_ACC_OR_ARROW_WIDTH =
+ new StringUIClientPropertyKey("maxAccOrArrowWidth");
+
+ public static final ColumnAlignment LTR_ALIGNMENT_1 =
+ new ColumnAlignment(
+ SwingConstants.LEFT,
+ SwingConstants.LEFT,
+ SwingConstants.LEFT,
+ SwingConstants.RIGHT,
+ SwingConstants.RIGHT
+ );
+ public static final ColumnAlignment LTR_ALIGNMENT_2 =
+ new ColumnAlignment(
+ SwingConstants.LEFT,
+ SwingConstants.LEFT,
+ SwingConstants.LEFT,
+ SwingConstants.LEFT,
+ SwingConstants.RIGHT
+ );
+ public static final ColumnAlignment RTL_ALIGNMENT_1 =
+ new ColumnAlignment(
+ SwingConstants.RIGHT,
+ SwingConstants.RIGHT,
+ SwingConstants.RIGHT,
+ SwingConstants.LEFT,
+ SwingConstants.LEFT
+ );
+ public static final ColumnAlignment RTL_ALIGNMENT_2 =
+ new ColumnAlignment(
+ SwingConstants.RIGHT,
+ SwingConstants.RIGHT,
+ SwingConstants.RIGHT,
+ SwingConstants.RIGHT,
+ SwingConstants.LEFT
+ );
+
+ private SynthContext context;
+ private SynthContext accContext;
+ private SynthStyle style;
+ private SynthStyle accStyle;
+ private SynthGraphicsUtils gu;
+ private SynthGraphicsUtils accGu;
+ private boolean alignAcceleratorText;
+ private int maxAccOrArrowWidth;
+
+ public SynthMenuItemLayoutHelper(SynthContext context, SynthContext accContext,
+ JMenuItem mi, Icon checkIcon, Icon arrowIcon,
+ Rectangle viewRect, int gap, String accDelimiter,
+ boolean isLeftToRight, boolean useCheckAndArrow,
+ String propertyPrefix) {
+ this.context = context;
+ this.accContext = accContext;
+ this.style = context.getStyle();
+ this.accStyle = accContext.getStyle();
+ this.gu = style.getGraphicsUtils(context);
+ this.accGu = accStyle.getGraphicsUtils(accContext);
+ this.alignAcceleratorText = getAlignAcceleratorText(propertyPrefix);
+ reset(mi, checkIcon, arrowIcon, viewRect, gap, accDelimiter,
+ isLeftToRight, style.getFont(context), accStyle.getFont(accContext),
+ useCheckAndArrow, propertyPrefix);
+ setLeadingGap(0);
+ }
+
+ private boolean getAlignAcceleratorText(String propertyPrefix) {
+ return style.getBoolean(context,
+ propertyPrefix + ".alignAcceleratorText", true);
+ }
+
+ protected void calcWidthsAndHeights() {
+ // iconRect
+ if (getIcon() != null) {
+ getIconSize().setWidth(SynthIcon.getIconWidth(getIcon(), context));
+ getIconSize().setHeight(SynthIcon.getIconHeight(getIcon(), context));
+ }
+
+ // accRect
+ if (!getAccText().equals("")) {
+ getAccSize().setWidth(accGu.computeStringWidth(getAccContext(),
+ getAccFontMetrics().getFont(), getAccFontMetrics(),
+ getAccText()));
+ getAccSize().setHeight(getAccFontMetrics().getHeight());
+ }
+
+ // textRect
+ if (getText() == null) {
+ setText("");
+ } else if (!getText().equals("")) {
+ if (getHtmlView() != null) {
+ // Text is HTML
+ getTextSize().setWidth(
+ (int) getHtmlView().getPreferredSpan(View.X_AXIS));
+ getTextSize().setHeight(
+ (int) getHtmlView().getPreferredSpan(View.Y_AXIS));
+ } else {
+ // Text isn't HTML
+ getTextSize().setWidth(gu.computeStringWidth(context,
+ getFontMetrics().getFont(), getFontMetrics(),
+ getText()));
+ getTextSize().setHeight(getFontMetrics().getHeight());
+ }
+ }
+
+ if (useCheckAndArrow()) {
+ // checkIcon
+ if (getCheckIcon() != null) {
+ getCheckSize().setWidth(
+ SynthIcon.getIconWidth(getCheckIcon(), context));
+ getCheckSize().setHeight(
+ SynthIcon.getIconHeight(getCheckIcon(), context));
+ }
+ // arrowRect
+ if (getArrowIcon() != null) {
+ getArrowSize().setWidth(
+ SynthIcon.getIconWidth(getArrowIcon(), context));
+ getArrowSize().setHeight(
+ SynthIcon.getIconHeight(getArrowIcon(), context));
+ }
+ }
+
+ // labelRect
+ if (isColumnLayout()) {
+ getLabelSize().setWidth(getIconSize().getWidth()
+ + getTextSize().getWidth() + getGap());
+ getLabelSize().setHeight(MenuItemLayoutHelper.max(
+ getCheckSize().getHeight(),
+ getIconSize().getHeight(),
+ getTextSize().getHeight(),
+ getAccSize().getHeight(),
+ getArrowSize().getHeight()));
+ } else {
+ Rectangle textRect = new Rectangle();
+ Rectangle iconRect = new Rectangle();
+ gu.layoutText(context, getFontMetrics(), getText(), getIcon(),
+ getHorizontalAlignment(), getVerticalAlignment(),
+ getHorizontalTextPosition(), getVerticalTextPosition(),
+ getViewRect(), iconRect, textRect, getGap());
+ Rectangle labelRect = iconRect.union(textRect);
+ getLabelSize().setHeight(labelRect.height);
+ getLabelSize().setWidth(labelRect.width);
+ }
+ }
+
+ protected void calcMaxWidths() {
+ calcMaxWidth(getCheckSize(), MAX_CHECK_WIDTH);
+ maxAccOrArrowWidth =
+ calcMaxValue(MAX_ACC_OR_ARROW_WIDTH, getArrowSize().getWidth());
+ maxAccOrArrowWidth =
+ calcMaxValue(MAX_ACC_OR_ARROW_WIDTH, getAccSize().getWidth());
+
+ if (isColumnLayout()) {
+ calcMaxWidth(getIconSize(), MAX_ICON_WIDTH);
+ calcMaxWidth(getTextSize(), MAX_TEXT_WIDTH);
+ int curGap = getGap();
+ if ((getIconSize().getMaxWidth() == 0)
+ || (getTextSize().getMaxWidth() == 0)) {
+ curGap = 0;
+ }
+ getLabelSize().setMaxWidth(
+ calcMaxValue(MAX_LABEL_WIDTH, getIconSize().getMaxWidth()
+ + getTextSize().getMaxWidth() + curGap));
+ } else {
+ // We shouldn't use current icon and text widths
+ // in maximal widths calculation for complex layout.
+ getIconSize().setMaxWidth(getParentIntProperty(
+ MAX_ICON_WIDTH));
+ calcMaxWidth(getLabelSize(), MAX_LABEL_WIDTH);
+ // If maxLabelWidth is wider
+ // than the widest icon + the widest text + gap,
+ // we should update the maximal text witdh
+ int candidateTextWidth = getLabelSize().getMaxWidth() -
+ getIconSize().getMaxWidth();
+ if (getIconSize().getMaxWidth() > 0) {
+ candidateTextWidth -= getGap();
+ }
+ getTextSize().setMaxWidth(calcMaxValue(
+ MAX_TEXT_WIDTH, candidateTextWidth));
+ }
+ }
+
+ public SynthContext getContext() {
+ return context;
+ }
+
+ public SynthContext getAccContext() {
+ return accContext;
+ }
+
+ public SynthStyle getStyle() {
+ return style;
+ }
+
+ public SynthStyle getAccStyle() {
+ return accStyle;
+ }
+
+ public SynthGraphicsUtils getGraphicsUtils() {
+ return gu;
+ }
+
+ public SynthGraphicsUtils getAccGraphicsUtils() {
+ return accGu;
+ }
+
+ public boolean alignAcceleratorText() {
+ return alignAcceleratorText;
+ }
+
+ public int getMaxAccOrArrowWidth() {
+ return maxAccOrArrowWidth;
+ }
+
+ protected void prepareForLayout(LayoutResult lr) {
+ lr.getCheckRect().width = getCheckSize().getMaxWidth();
+ // An item can have an arrow or a check icon at once
+ if (useCheckAndArrow() && (!"".equals(getAccText()))) {
+ lr.getAccRect().width = maxAccOrArrowWidth;
+ } else {
+ lr.getArrowRect().width = maxAccOrArrowWidth;
+ }
+ }
+
+ public ColumnAlignment getLTRColumnAlignment() {
+ if (alignAcceleratorText()) {
+ return LTR_ALIGNMENT_2;
+ } else {
+ return LTR_ALIGNMENT_1;
+ }
+ }
+
+ public ColumnAlignment getRTLColumnAlignment() {
+ if (alignAcceleratorText()) {
+ return RTL_ALIGNMENT_2;
+ } else {
+ return RTL_ALIGNMENT_1;
+ }
+ }
+
+ protected void layoutIconAndTextInLabelRect(LayoutResult lr) {
+ lr.setTextRect(new Rectangle());
+ lr.setIconRect(new Rectangle());
+ gu.layoutText(context, getFontMetrics(), getText(), getIcon(),
+ getHorizontalAlignment(), getVerticalAlignment(),
+ getHorizontalTextPosition(), getVerticalTextPosition(),
+ lr.getLabelRect(), lr.getIconRect(), lr.getTextRect(), getGap());
+ }
+}
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -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
@@ -37,7 +37,7 @@
import javax.swing.plaf.basic.*;
import javax.swing.text.View;
import sun.swing.plaf.synth.*;
-import sun.swing.SwingUtilities2;
+import sun.swing.MenuItemLayoutHelper;
/**
@@ -59,542 +59,16 @@
return new SynthMenuItemUI();
}
- //
- // The next handful of static methods are used by both SynthMenuUI
- // and SynthMenuItemUI. This is necessitated by SynthMenuUI not
- // extending SynthMenuItemUI.
- //
-
- /*
- * All JMenuItems (and JMenus) include enough space for the insets
- * plus one or more elements. When we say "icon(s)" below, we mean
- * "check/radio indicator and/or user icon." If both are defined for
- * a given menu item, then in a LTR orientation the check/radio indicator
- * is on the left side followed by the user icon to the right; it is
- * just the opposite in a RTL orientation.
- *
- * Cases to consider for SynthMenuItemUI (visualized here in a
- * LTR orientation; the RTL case would be reversed):
- * text
- * icon(s) + text
- * icon(s) + text + accelerator
- * text + accelerator
- *
- * Cases to consider for SynthMenuUI (again visualized here in a
- * LTR orientation):
- * text + arrow
- * (user)icon + text + arrow
- *
- * Note that in the above scenarios, accelerator and arrow icon are
- * mutually exclusive. This means that if a popup menu contains a mix
- * of JMenus and JMenuItems, we only need to allow enough space for
- * max(maxAccelerator, maxArrow), and both accelerators and arrow icons
- * can occupy the same "column" of space in the menu.
- *
- * 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) {
- JMenuItem b = (JMenuItem) c;
- Icon icon = (Icon) b.getIcon();
- String text = b.getText();
- KeyStroke accelerator = b.getAccelerator();
- String acceleratorText = "";
-
- if (accelerator != null) {
- int modifiers = accelerator.getModifiers();
- if (modifiers > 0) {
- acceleratorText = KeyEvent.getKeyModifiersText(modifiers);
- acceleratorText += acceleratorDelimiter;
- }
- int keyCode = accelerator.getKeyCode();
- if (keyCode != 0) {
- acceleratorText += KeyEvent.getKeyText(keyCode);
- } else {
- acceleratorText += accelerator.getKeyChar();
- }
- }
-
- Font font = context.getStyle().getFont(context);
- FontMetrics fm = b.getFontMetrics(font);
- FontMetrics fmAccel = b.getFontMetrics(accContext.getStyle().
- getFont(accContext));
-
- resetRects();
-
- layoutMenuItem(
- context, fm, accContext, text, fmAccel, acceleratorText,
- icon, checkIcon, arrowIcon, b.getVerticalAlignment(),
- b.getHorizontalAlignment(), b.getVerticalTextPosition(),
- b.getHorizontalTextPosition(), viewRect, iconRect, textRect,
- acceleratorRect, checkIconRect, arrowIconRect,
- text == null ? 0 : defaultTextIconGap, defaultTextIconGap);
-
- r.setBounds(textRect);
-
- int totalIconWidth = 0;
- int maxIconHeight = 0;
- if (icon != null) {
- // Add in the user icon
- totalIconWidth += iconRect.width;
- if (textRect.width > 0) {
- // Allow for some room between the user icon and the text
- totalIconWidth += defaultTextIconGap;
- }
- maxIconHeight = Math.max(iconRect.height, maxIconHeight);
- }
- if (checkIcon != null) {
- // Add in the checkIcon
- totalIconWidth += checkIconRect.width;
- if (textRect.width > 0 || icon != null) {
- // Allow for some room between the check/radio indicator
- // and the text (or user icon, if both are specified)
- totalIconWidth += defaultTextIconGap;
- }
- maxIconHeight = Math.max(checkIconRect.height, maxIconHeight);
- }
-
- int arrowWidth = 0;
- if (arrowIcon != null) {
- // Add in the arrowIcon
- arrowWidth += defaultTextIconGap;
- arrowWidth += arrowIconRect.width;
- maxIconHeight = Math.max(arrowIconRect.height, maxIconHeight);
- }
-
- int accelSpacing = 0;
- if (acceleratorRect.width > 0) {
- // Allow for some room between the text and the accelerator
- accelSpacing += 4*defaultTextIconGap;
- }
-
- // Take text and all icons into account when determining height
- r.height = Math.max(r.height, maxIconHeight);
-
- // To make the accelerator texts appear in a column,
- // find the widest MenuItem text and the widest accelerator text.
-
- // Get the parent, which stores the information.
- Container parent = b.getParent();
-
- if (parent instanceof JPopupMenu) {
- SynthPopupMenuUI popupUI = (SynthPopupMenuUI)SynthLookAndFeel.
- getUIOfType(((JPopupMenu)parent).getUI(),
- SynthPopupMenuUI.class);
-
- if (popupUI != null) {
- // This gives us the widest MenuItem text encountered thus
- // far in the parent JPopupMenu
- r.width = popupUI.adjustTextWidth(r.width);
-
- // Add in the widest icon (includes both user and
- // check/radio icons) encountered thus far
- r.width += popupUI.adjustIconWidth(totalIconWidth);
-
- // Add in the widest text/accelerator spacing
- // encountered thus far
- r.width += popupUI.adjustAccelSpacingWidth(accelSpacing);
-
- // Add in the widest accelerator text (or arrow)
- // encountered thus far (at least one of these values
- // will always be zero, so we combine them here to
- // avoid double counting)
- int totalAccelOrArrow = acceleratorRect.width + arrowWidth;
- r.width += popupUI.adjustAcceleratorWidth(totalAccelOrArrow);
- }
- }
- else if (parent != null && !(b instanceof JMenu &&
- ((JMenu)b).isTopLevelMenu())) {
- r.width +=
- totalIconWidth + accelSpacing +
- acceleratorRect.width + arrowWidth;
- }
-
- Insets insets = b.getInsets();
- if(insets != null) {
- r.width += insets.left + insets.right;
- r.height += insets.top + insets.bottom;
- }
-
- // if the width is even, bump it up one. This is critical
- // for the focus dash line to draw properly
- if(r.width%2 == 0) {
- r.width++;
- }
-
- // if the height is even, bump it up one. This is critical
- // for the text to center properly
- if(r.height%2 == 0) {
- r.height++;
- }
- return r.getSize();
- }
-
- static void paint(SynthContext context, SynthContext accContext,
- Graphics g, Icon checkIcon, Icon arrowIcon,
- String acceleratorDelimiter,
- int defaultTextIconGap) {
- JComponent c = context.getComponent();
- JMenuItem b = (JMenuItem)c;
- ButtonModel model = b.getModel();
- Insets i = b.getInsets();
-
- resetRects();
-
- viewRect.setBounds(0, 0, b.getWidth(), b.getHeight());
-
- viewRect.x += i.left;
- viewRect.y += i.top;
- viewRect.width -= (i.right + viewRect.x);
- viewRect.height -= (i.bottom + viewRect.y);
-
- SynthStyle style = context.getStyle();
- Font f = style.getFont(context);
- g.setFont(f);
- FontMetrics fm = SwingUtilities2.getFontMetrics(c, g, f);
- FontMetrics accFM = SwingUtilities2.getFontMetrics(c, g,
- accContext.getStyle().
- getFont(accContext));
-
- // get Accelerator text
- KeyStroke accelerator = b.getAccelerator();
- String acceleratorText = "";
- if (accelerator != null) {
- int modifiers = accelerator.getModifiers();
- if (modifiers > 0) {
- acceleratorText = KeyEvent.getKeyModifiersText(modifiers);
- acceleratorText += acceleratorDelimiter;
- }
-
- int keyCode = accelerator.getKeyCode();
- if (keyCode != 0) {
- acceleratorText += KeyEvent.getKeyText(keyCode);
- } else {
- acceleratorText += accelerator.getKeyChar();
- }
- }
-
- // Layout the text and icon
- String text = layoutMenuItem(context, fm, accContext,
- b.getText(), accFM, acceleratorText, b.getIcon(),
- checkIcon, arrowIcon,
- b.getVerticalAlignment(), b.getHorizontalAlignment(),
- b.getVerticalTextPosition(), b.getHorizontalTextPosition(),
- viewRect, iconRect, textRect, acceleratorRect,
- checkIconRect, arrowIconRect,
- b.getText() == null ? 0 : defaultTextIconGap,
- defaultTextIconGap
- );
-
- // Paint the Check
- if (checkIcon != null) {
- SynthIcon.paintIcon(checkIcon, context, g, checkIconRect.x,
- checkIconRect.y, checkIconRect.width, checkIconRect.height);
- }
-
- // Paint the Icon
- if(b.getIcon() != null) {
- Icon icon;
- if(!model.isEnabled()) {
- icon = (Icon) b.getDisabledIcon();
- } else if(model.isPressed() && model.isArmed()) {
- icon = (Icon) b.getPressedIcon();
- if(icon == null) {
- // Use default icon
- icon = (Icon) b.getIcon();
- }
- } else {
- icon = (Icon) b.getIcon();
- }
-
- if (icon!=null) {
- SynthIcon.paintIcon(icon, context, g, iconRect.x,
- iconRect.y, iconRect.width, iconRect.height);
- }
- }
-
- // Draw the Text
- if(text != null) {
- View v = (View) c.getClientProperty(BasicHTML.propertyKey);
- if (v != null) {
- v.paint(g, textRect);
- } else {
- g.setColor(style.getColor(context, ColorType.TEXT_FOREGROUND));
- g.setFont(style.getFont(context));
- style.getGraphicsUtils(context).paintText(context, g, text,
- textRect.x, textRect.y, b.getDisplayedMnemonicIndex());
- }
- }
-
- // Draw the Accelerator Text
- if(acceleratorText != null && !acceleratorText.equals("")) {
- // Get the maxAccWidth from the parent to calculate the offset.
- int accOffset = 0;
- Container parent = b.getParent();
- if (parent != null && parent instanceof JPopupMenu) {
- SynthPopupMenuUI popupUI = (SynthPopupMenuUI)
- ((JPopupMenu)parent).getUI();
-
- // Note that we can only get here for SynthMenuItemUI
- // (not SynthMenuUI) since acceleratorText is defined,
- // so this cast should be safe
- SynthMenuItemUI miUI = (SynthMenuItemUI)
- SynthLookAndFeel.getUIOfType(b.getUI(),
- SynthMenuItemUI.class);
-
- if (popupUI != null && miUI != null) {
- String prop =
- miUI.getPropertyPrefix() + ".alignAcceleratorText";
- boolean align = style.getBoolean(context, prop, true);
-
- // Calculate the offset, with which the accelerator texts
- // will be drawn.
- if (align) {
- // When align==true and we're in the LTR case,
- // we add an offset here so that all accelerators
- // will be left-justified in their own column.
- int max = popupUI.getMaxAcceleratorWidth();
- if (max > 0) {
- accOffset = max - acceleratorRect.width;
- if (!SynthLookAndFeel.isLeftToRight(c)) {
- // In the RTL, flip the sign so that all
- // accelerators will be right-justified.
- accOffset = -accOffset;
- }
- }
- } //else {
- // Don't need to do anything special here; in the
- // LTR case, the accelerator is already justified
- // against the right edge of the menu (and against
- // the left edge in the RTL case).
- //}
- }
- }
-
- SynthStyle accStyle = accContext.getStyle();
-
- g.setColor(accStyle.getColor(accContext,
- ColorType.TEXT_FOREGROUND));
- g.setFont(accStyle.getFont(accContext));
- accStyle.getGraphicsUtils(accContext).paintText(
- accContext, g, acceleratorText, acceleratorRect.x -
- accOffset, acceleratorRect.y, -1);
- }
-
- // Paint the Arrow
- if (arrowIcon != null) {
- SynthIcon.paintIcon(arrowIcon, context, g, arrowIconRect.x,
- arrowIconRect.y, arrowIconRect.width, arrowIconRect.height);
+ public void uninstallUI(JComponent c) {
+ super.uninstallUI(c);
+ // Remove values from the parent's Client Properties.
+ JComponent p = MenuItemLayoutHelper.getMenuItemParent((JMenuItem) c);
+ if (p != null) {
+ p.putClientProperty(
+ SynthMenuItemLayoutHelper.MAX_ACC_OR_ARROW_WIDTH, null);
}
}
- /**
- * Compute and return the location of the icons origin, the
- * location of origin of the text baseline, and a possibly clipped
- * version of the compound labels string. Locations are computed
- * relative to the viewRect rectangle.
- */
-
- private static String layoutMenuItem(
- SynthContext context,
- FontMetrics fm,
- SynthContext accContext,
- String text,
- FontMetrics fmAccel,
- String acceleratorText,
- Icon icon,
- Icon checkIcon,
- Icon arrowIcon,
- int verticalAlignment,
- int horizontalAlignment,
- int verticalTextPosition,
- int horizontalTextPosition,
- Rectangle viewRect,
- Rectangle iconRect,
- Rectangle textRect,
- Rectangle acceleratorRect,
- Rectangle checkIconRect,
- Rectangle arrowIconRect,
- int textIconGap,
- int menuItemGap
- )
- {
- // If parent is JPopupMenu, get and store it's UI
- SynthPopupMenuUI popupUI = null;
- JComponent b = context.getComponent();
- Container parent = b.getParent();
- if(parent instanceof JPopupMenu) {
- popupUI = (SynthPopupMenuUI)SynthLookAndFeel.
- getUIOfType(((JPopupMenu)parent).getUI(),
- SynthPopupMenuUI.class);
- }
-
- context.getStyle().getGraphicsUtils(context).layoutText(
- context, fm, text, icon,horizontalAlignment, verticalAlignment,
- horizontalTextPosition, verticalTextPosition, viewRect,
- iconRect, textRect, textIconGap);
-
- /* Initialize the acceleratorText bounds rectangle textRect. If a null
- * or and empty String was specified we substitute "" here
- * and use 0,0,0,0 for acceleratorTextRect.
- */
- if( (acceleratorText == null) || acceleratorText.equals("") ) {
- acceleratorRect.width = acceleratorRect.height = 0;
- acceleratorText = "";
- }
- else {
- SynthStyle style = accContext.getStyle();
- acceleratorRect.width = style.getGraphicsUtils(accContext).
- computeStringWidth(accContext, fmAccel.getFont(), fmAccel,
- acceleratorText);
- acceleratorRect.height = fmAccel.getHeight();
- }
-
- // Initialize the checkIcon bounds rectangle width & height.
- if (checkIcon != null) {
- checkIconRect.width = SynthIcon.getIconWidth(checkIcon,
- context);
- checkIconRect.height = SynthIcon.getIconHeight(checkIcon,
- context);
- }
- else {
- checkIconRect.width = checkIconRect.height = 0;
- }
-
- // Initialize the arrowIcon bounds rectangle width & height.
- if (arrowIcon != null) {
- arrowIconRect.width = SynthIcon.getIconWidth(arrowIcon,
- context);
- arrowIconRect.height = SynthIcon.getIconHeight(arrowIcon,
- context);
- } else {
- arrowIconRect.width = arrowIconRect.height = 0;
- }
-
- // Note: layoutText() has already left room for
- // the user icon, so no need to adjust textRect below
- // to account for the user icon. However, we do have to
- // reposition textRect when the check icon is visible.
-
- Rectangle labelRect = iconRect.union(textRect);
- if( SynthLookAndFeel.isLeftToRight(context.getComponent()) ) {
- // Position the check and user icons
- iconRect.x = viewRect.x;
- if (checkIcon != null) {
- checkIconRect.x = viewRect.x;
- iconRect.x += menuItemGap + checkIconRect.width;
- textRect.x += menuItemGap + checkIconRect.width;
- }
-
- // Position the arrow icon
- arrowIconRect.x =
- viewRect.x + viewRect.width - arrowIconRect.width;
-
- // Position the accelerator text rect
- acceleratorRect.x =
- viewRect.x + viewRect.width - acceleratorRect.width;
-
- /* Align icons and text horizontally */
- if(popupUI != null) {
- int thisTextOffset = popupUI.adjustTextOffset(textRect.x
- - viewRect.x);
- textRect.x = thisTextOffset + viewRect.x;
-
- if(icon != null) {
- // REMIND: The following code currently assumes the
- // default (TRAILING) horizontalTextPosition, which means
- // it will always place the icon to the left of the text.
- // Other values of horizontalTextPosition aren't very
- // useful for menu items, so we ignore them for now, but
- // someday we might want to fix this situation.
- int thisIconOffset =
- popupUI.adjustIconOffset(iconRect.x - viewRect.x);
- iconRect.x = thisIconOffset + viewRect.x;
- }
- }
- } else {
- // Position the accelerator text rect
- acceleratorRect.x = viewRect.x;
-
- // Position the arrow icon
- arrowIconRect.x = viewRect.x;
-
- // Position the check and user icons
- iconRect.x =
- viewRect.x + viewRect.width - iconRect.width;
- if (checkIcon != null) {
- checkIconRect.x =
- viewRect.x + viewRect.width - checkIconRect.width;
- textRect.x -= menuItemGap + checkIconRect.width;
- iconRect.x -= menuItemGap + checkIconRect.width;
- }
-
- /* Align icons and text horizontally */
- if(popupUI != null) {
- int thisTextOffset = viewRect.x + viewRect.width
- - textRect.x - textRect.width;
- thisTextOffset = popupUI.adjustTextOffset(thisTextOffset);
- textRect.x = viewRect.x + viewRect.width
- - thisTextOffset - textRect.width;
- if(icon != null) {
- // REMIND: The following code currently assumes the
- // default (TRAILING) horizontalTextPosition, which means
- // it will always place the icon to the right of the text.
- // Other values of horizontalTextPosition aren't very
- // useful for menu items, so we ignore them for now, but
- // someday we might want to fix this situation.
- int thisIconOffset = viewRect.x + viewRect.width
- - iconRect.x - iconRect.width;
- thisIconOffset =
- popupUI.adjustIconOffset(thisIconOffset);
- iconRect.x = viewRect.x + viewRect.width
- - thisIconOffset - iconRect.width;
- }
- }
- }
-
- // Align the accelerator text and all icons vertically
- // with the center of the label rect.
- int midY = labelRect.y + (labelRect.height/2);
- iconRect.y = midY - (iconRect.height/2);
- acceleratorRect.y = midY - (acceleratorRect.height/2);
- arrowIconRect.y = midY - (arrowIconRect.height/2);
- checkIconRect.y = midY - (checkIconRect.height/2);
-
- return text;
- }
-
- // these rects are used for painting and preferredsize calculations.
- // they used to be regenerated constantly. Now they are reused.
- static Rectangle iconRect = new Rectangle();
- static Rectangle textRect = new Rectangle();
- static Rectangle acceleratorRect = new Rectangle();
- static Rectangle checkIconRect = new Rectangle();
- static Rectangle arrowIconRect = new Rectangle();
- static Rectangle viewRect = new Rectangle(Short.MAX_VALUE,Short.MAX_VALUE);
- static Rectangle r = new Rectangle();
-
- private static void resetRects() {
- iconRect.setBounds(0, 0, 0, 0);
- textRect.setBounds(0, 0, 0, 0);
- acceleratorRect.setBounds(0, 0, 0, 0);
- checkIconRect.setBounds(0, 0, 0, 0);
- arrowIconRect.setBounds(0, 0, 0, 0);
- viewRect.setBounds(0,0,Short.MAX_VALUE, Short.MAX_VALUE);
- r.setBounds(0, 0, 0, 0);
- }
-
-
protected void installDefaults() {
updateStyle(menuItem);
}
@@ -718,9 +192,11 @@
int defaultTextIconGap) {
SynthContext context = getContext(c);
SynthContext accContext = getContext(c, Region.MENU_ITEM_ACCELERATOR);
- Dimension value = getPreferredMenuItemSize(context, accContext,
- c, checkIcon, arrowIcon, defaultTextIconGap,
- acceleratorDelimiter);
+ Dimension value = SynthGraphicsUtils.getPreferredMenuItemSize(
+ context, accContext, c, checkIcon, arrowIcon,
+ defaultTextIconGap, acceleratorDelimiter,
+ MenuItemLayoutHelper.useCheckAndArrow(menuItem),
+ getPropertyPrefix());
context.dispose();
accContext.dispose();
return value;
@@ -751,14 +227,13 @@
String prefix = getPropertyPrefix();
Icon checkIcon = style.getIcon(context, prefix + ".checkIcon");
Icon arrowIcon = style.getIcon(context, prefix + ".arrowIcon");
- paint(context, accContext, g, checkIcon, arrowIcon,
- acceleratorDelimiter, defaultTextIconGap);
+ SynthGraphicsUtils.paint(context, accContext, g, checkIcon, arrowIcon,
+ acceleratorDelimiter, defaultTextIconGap, getPropertyPrefix());
accContext.dispose();
}
void paintBackground(SynthContext context, Graphics g, JComponent c) {
- context.getPainter().paintMenuItemBackground(context, g, 0, 0,
- c.getWidth(), c.getHeight());
+ SynthGraphicsUtils.paintBackground(context, g, c);
}
public void paintBorder(SynthContext context, Graphics g, int x,
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -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
@@ -35,7 +35,7 @@
import java.util.Arrays;
import java.util.ArrayList;
import sun.swing.plaf.synth.SynthUI;
-
+import sun.swing.MenuItemLayoutHelper;
/**
* Synth's MenuUI.
@@ -86,7 +86,7 @@
acceleratorDelimiter = style.getString(context, prefix +
".acceleratorDelimiter", "+");
- if (useCheckAndArrow()) {
+ if (MenuItemLayoutHelper.useCheckAndArrow(menuItem)) {
checkIcon = style.getIcon(context, prefix + ".checkIcon");
arrowIcon = style.getIcon(context, prefix + ".arrowIcon");
} else {
@@ -111,6 +111,16 @@
accContext.dispose();
}
+ public void uninstallUI(JComponent c) {
+ super.uninstallUI(c);
+ // Remove values from the parent's Client Properties.
+ JComponent p = MenuItemLayoutHelper.getMenuItemParent((JMenuItem) c);
+ if (p != null) {
+ p.putClientProperty(
+ SynthMenuItemLayoutHelper.MAX_ACC_OR_ARROW_WIDTH, null);
+ }
+ }
+
protected void uninstallDefaults() {
SynthContext context = getContext(menuItem, ENABLED);
style.uninstallDefaults(context);
@@ -182,9 +192,11 @@
int defaultTextIconGap) {
SynthContext context = getContext(c);
SynthContext accContext = getContext(c, Region.MENU_ITEM_ACCELERATOR);
- Dimension value = SynthMenuItemUI.getPreferredMenuItemSize(
- context, accContext, c, checkIcon, arrowIcon,
- defaultTextIconGap, acceleratorDelimiter);
+ Dimension value = SynthGraphicsUtils.getPreferredMenuItemSize(
+ context, accContext, c, checkIcon, arrowIcon,
+ defaultTextIconGap, acceleratorDelimiter,
+ MenuItemLayoutHelper.useCheckAndArrow(menuItem),
+ getPropertyPrefix());
context.dispose();
accContext.dispose();
return value;
@@ -211,21 +223,12 @@
protected void paint(SynthContext context, Graphics g) {
SynthContext accContext = getContext(menuItem,
Region.MENU_ITEM_ACCELERATOR);
- SynthStyle style = context.getStyle();
- Icon checkIcon;
- Icon arrowIcon;
- if (useCheckAndArrow()) {
- // Refetch the appropriate icons for the current state
- String prefix = getPropertyPrefix();
- checkIcon = style.getIcon(context, prefix + ".checkIcon");
- arrowIcon = style.getIcon(context, prefix + ".arrowIcon");
- } else {
- // Not needed in this case
- checkIcon = null;
- arrowIcon = null;
- }
- SynthMenuItemUI.paint(context, accContext, g, checkIcon, arrowIcon,
- acceleratorDelimiter, defaultTextIconGap);
+ // Refetch the appropriate check indicator for the current state
+ String prefix = getPropertyPrefix();
+ Icon checkIcon = style.getIcon(context, prefix + ".checkIcon");
+ Icon arrowIcon = style.getIcon(context, prefix + ".arrowIcon");
+ SynthGraphicsUtils.paint(context, accContext, g, checkIcon, arrowIcon,
+ acceleratorDelimiter, defaultTextIconGap, getPropertyPrefix());
accContext.dispose();
}
@@ -239,8 +242,4 @@
updateStyle((JMenu)e.getSource());
}
}
-
- private boolean useCheckAndArrow() {
- return !((JMenu)menuItem).isTopLevelMenu();
- }
}
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthParser.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthParser.java Tue Aug 12 17:59:58 2008 -0700
@@ -40,6 +40,7 @@
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
@@ -136,7 +137,7 @@
* Array of state infos for the current style. These are pushed to the
* style when </style> is received.
*/
- private java.util.List _stateInfos;
+ private List<ParsedSynthStyle.StateInfo> _stateInfos;
/**
* Current style.
@@ -151,7 +152,7 @@
/**
* Bindings for the current InputMap
*/
- private java.util.List _inputMapBindings;
+ private List<String> _inputMapBindings;
/**
* ID for the input map. This is cached as
@@ -177,30 +178,30 @@
/**
* List of ColorTypes. This is populated in startColorType.
*/
- private java.util.List _colorTypes;
+ private List<ColorType> _colorTypes;
/**
* defaultsPropertys are placed here.
*/
- private Map _defaultsMap;
+ private Map<String, Object> _defaultsMap;
/**
* List of SynthStyle.Painters that will be applied to the current style.
*/
- private java.util.List _stylePainters;
+ private List<ParsedSynthStyle.PainterInfo> _stylePainters;
/**
* List of SynthStyle.Painters that will be applied to the current state.
*/
- private java.util.List _statePainters;
+ private List<ParsedSynthStyle.PainterInfo> _statePainters;
SynthParser() {
_mapping = new HashMap<String,Object>();
- _stateInfos = new ArrayList();
- _colorTypes = new ArrayList();
- _inputMapBindings = new ArrayList();
- _stylePainters = new ArrayList();
- _statePainters = new ArrayList();
+ _stateInfos = new ArrayList<ParsedSynthStyle.StateInfo>();
+ _colorTypes = new ArrayList<ColorType>();
+ _inputMapBindings = new ArrayList<String>();
+ _stylePainters = new ArrayList<ParsedSynthStyle.PainterInfo>();
+ _statePainters = new ArrayList<ParsedSynthStyle.PainterInfo>();
}
/**
@@ -219,7 +220,7 @@
public void parse(InputStream inputStream,
DefaultSynthStyleFactory factory,
URL urlResourceBase, Class<?> classResourceBase,
- Map defaultsMap)
+ Map<String, Object> defaultsMap)
throws ParseException, IllegalArgumentException {
if (inputStream == null || factory == null ||
(urlResourceBase == null && classResourceBase == null)) {
@@ -333,7 +334,7 @@
* type type, this will throw an exception.
*/
private Object lookup(String key, Class type) throws SAXException {
- Object value = null;
+ Object value;
if (_handler != null) {
if ((value = _handler.lookup(key)) != null) {
return checkCast(value, type);
@@ -423,15 +424,12 @@
private void endStyle() throws SAXException {
int size = _stylePainters.size();
if (size > 0) {
- _style.setPainters((ParsedSynthStyle.PainterInfo[])
- _stylePainters.toArray(new ParsedSynthStyle.
- PainterInfo[size]));
+ _style.setPainters(_stylePainters.toArray(new ParsedSynthStyle.PainterInfo[size]));
_stylePainters.clear();
}
size = _stateInfos.size();
if (size > 0) {
- _style.setStateInfo((ParsedSynthStyle.StateInfo[])_stateInfos.
- toArray(new ParsedSynthStyle.StateInfo[size]));
+ _style.setStateInfo(_stateInfos.toArray(new ParsedSynthStyle.StateInfo[size]));
_stateInfos.clear();
}
_style = null;
@@ -501,9 +499,7 @@
private void endState() throws SAXException {
int size = _statePainters.size();
if (size > 0) {
- _stateInfo.setPainters((ParsedSynthStyle.PainterInfo[])
- _statePainters.toArray(new ParsedSynthStyle.
- PainterInfo[size]));
+ _stateInfo.setPainters(_statePainters.toArray(new ParsedSynthStyle.PainterInfo[size]));
_statePainters.clear();
}
_stateInfo = null;
@@ -684,8 +680,7 @@
int max = 0;
for (int counter = _colorTypes.size() - 1; counter >= 0;
counter--) {
- max = Math.max(max, ((ColorType)_colorTypes.get(counter)).
- getID());
+ max = Math.max(max, _colorTypes.get(counter).getID());
}
if (colors == null || colors.length <= max) {
Color[] newColors = new Color[max + 1];
@@ -696,7 +691,7 @@
}
for (int counter = _colorTypes.size() - 1; counter >= 0;
counter--) {
- colors[((ColorType)_colorTypes.get(counter)).getID()] = color;
+ colors[_colorTypes.get(counter).getID()] = color;
}
_stateInfo.setColors(colors);
}
@@ -705,7 +700,7 @@
private void startProperty(AttributeList attributes,
Object property) throws SAXException {
Object value = null;
- Object key = null;
+ String key = null;
// Type of the value: 0=idref, 1=boolean, 2=dimension, 3=insets,
// 4=integer,5=string
int iType = 0;
@@ -1027,7 +1022,7 @@
}
}
- private void addPainterOrMerge(java.util.List painters, String method,
+ private void addPainterOrMerge(List<ParsedSynthStyle.PainterInfo> painters, String method,
SynthPainter painter, int direction) {
ParsedSynthStyle.PainterInfo painterInfo;
painterInfo = new ParsedSynthStyle.PainterInfo(method,
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthPopupMenuUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthPopupMenuUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -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
@@ -58,34 +58,6 @@
*/
class SynthPopupMenuUI extends BasicPopupMenuUI implements
PropertyChangeListener, SynthUI {
- /**
- * Maximum size of the text portion of the children menu items.
- */
- private int maxTextWidth;
-
- /**
- * Maximum size of the icon portion of the children menu items.
- */
- private int maxIconWidth;
-
- /**
- * Maximum size of the spacing between the text and accelerator
- * portions of the children menu items.
- */
- private int maxAccelSpacingWidth;
-
- /**
- * Maximum size of the text for the accelerator portion of the children
- * menu items.
- */
- private int maxAcceleratorWidth;
-
- /*
- * Maximum icon and text offsets of the children menu items.
- */
- private int maxTextOffset;
- private int maxIconOffset;
-
private SynthStyle style;
public static ComponentUI createUI(JComponent x) {
@@ -153,90 +125,6 @@
return SynthLookAndFeel.getComponentState(c);
}
- /**
- * Resets the max text and accerator widths,
- * text and icon offsets.
- */
- void resetAlignmentHints() {
- maxTextWidth = maxIconWidth
- = maxAccelSpacingWidth = maxAcceleratorWidth
- = maxTextOffset = maxIconOffset = 0;
- }
-
- /**
- * Adjusts the width needed to display the maximum menu item string.
- *
- * @param width Text width.
- * @return max width
- */
- int adjustTextWidth(int width) {
- maxTextWidth = Math.max(maxTextWidth, width);
- return maxTextWidth;
- }
-
- /**
- * Adjusts the width needed to display the maximum menu item icon.
- *
- * @param width Icon width.
- * @return max width
- */
- int adjustIconWidth(int width) {
- maxIconWidth = Math.max(maxIconWidth, width);
- return maxIconWidth;
- }
-
- /**
- * Adjusts the width needed to pad between the maximum menu item
- * text and accelerator.
- *
- * @param width Spacing width.
- * @return max width
- */
- int adjustAccelSpacingWidth(int width) {
- maxAccelSpacingWidth = Math.max(maxAccelSpacingWidth, width);
- return maxAccelSpacingWidth;
- }
-
- /**
- * Adjusts the width needed to display the maximum accelerator.
- *
- * @param width Text width.
- * @return max width
- */
- int adjustAcceleratorWidth(int width) {
- maxAcceleratorWidth = Math.max(maxAcceleratorWidth, width);
- return maxAcceleratorWidth;
- }
-
- /**
- * Maximum size needed to display accelerators of children menu items.
- */
- int getMaxAcceleratorWidth() {
- return maxAcceleratorWidth;
- }
-
- /**
- * Adjusts the text offset needed to align text horizontally.
- *
- * @param offset Text offset
- * @return max offset
- */
- int adjustTextOffset(int offset) {
- maxTextOffset = Math.max(maxTextOffset, offset);
- return maxTextOffset;
- }
-
- /**
- * Adjusts the icon offset needed to align icons horizontally
- *
- * @param offset Icon offset
- * @return max offset
- */
- int adjustIconOffset(int offset) {
- maxIconOffset = Math.max(maxIconOffset, offset);
- return maxIconOffset;
- }
-
public void update(Graphics g, JComponent c) {
SynthContext context = getContext(c);
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -48,13 +48,13 @@
* 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;
/**
* Style for the JSplitPane.
@@ -96,7 +96,7 @@
// focus forward traversal key
if (managingFocusForwardTraversalKeys==null) {
- managingFocusForwardTraversalKeys = new HashSet();
+ managingFocusForwardTraversalKeys = new HashSet<KeyStroke>();
managingFocusForwardTraversalKeys.add(
KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));
}
@@ -104,7 +104,7 @@
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));
}
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthStyle.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthStyle.java Tue Aug 12 17:59:58 2008 -0700
@@ -53,7 +53,7 @@
/**
* Contains the default values for certain properties.
*/
- private static Map DEFAULT_VALUES;
+ private static Map<Object, Object> DEFAULT_VALUES;
/**
* Shared SynthGraphics.
@@ -715,7 +715,7 @@
private static Object getDefaultValue(Object key) {
synchronized(SynthStyle.class) {
if (DEFAULT_VALUES == null) {
- DEFAULT_VALUES = new HashMap();
+ DEFAULT_VALUES = new HashMap<Object, Object>();
populateDefaultValues();
}
Object value = DEFAULT_VALUES.get(key);
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -66,7 +66,7 @@
protected void installDefaults() {
// Installs the text cursor on the component
super.installDefaults();
- updateStyle((JTextComponent)getComponent());
+ updateStyle(getComponent());
}
protected void uninstallDefaults() {
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -232,7 +232,7 @@
protected void installDefaults() {
// Installs the text cursor on the component
super.installDefaults();
- updateStyle((JTextComponent)getComponent());
+ updateStyle(getComponent());
getComponent().addFocusListener(this);
}
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java Tue Aug 12 17:59:58 2008 -0700
@@ -390,7 +390,7 @@
}
private Rectangle getDropLineRect(JTree.DropLocation loc) {
- Rectangle rect = null;
+ Rectangle rect;
TreePath path = loc.getPath();
int index = loc.getChildIndex();
boolean ltr = tree.getComponentOrientation().isLeftToRight();
@@ -523,7 +523,7 @@
// Don't paint the renderer if editing this row.
boolean selected = tree.isRowSelected(row);
- JTree.DropLocation dropLocation = (JTree.DropLocation)tree.getDropLocation();
+ JTree.DropLocation dropLocation = tree.getDropLocation();
boolean isDrop = dropLocation != null
&& dropLocation.getChildIndex() == -1
&& path == dropLocation.getPath();
--- a/jdk/src/share/classes/javax/swing/text/AbstractDocument.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/AbstractDocument.java Tue Aug 12 17:59:58 2008 -0700
@@ -123,15 +123,15 @@
if (defaultI18NProperty == null) {
// determine default setting for i18n support
- Object o = java.security.AccessController.doPrivileged(
- new java.security.PrivilegedAction() {
- public Object run() {
+ String o = java.security.AccessController.doPrivileged(
+ new java.security.PrivilegedAction<String>() {
+ public String run() {
return System.getProperty(I18NProperty);
}
}
);
if (o != null) {
- defaultI18NProperty = Boolean.valueOf((String)o);
+ defaultI18NProperty = Boolean.valueOf(o);
} else {
defaultI18NProperty = Boolean.FALSE;
}
@@ -163,7 +163,7 @@
*/
public Dictionary<Object,Object> getDocumentProperties() {
if (documentProperties == null) {
- documentProperties = new Hashtable(2);
+ documentProperties = new Hashtable<Object, Object>(2);
}
return documentProperties;
}
@@ -467,8 +467,7 @@
* @since 1.4
*/
public DocumentListener[] getDocumentListeners() {
- return (DocumentListener[])listenerList.getListeners(
- DocumentListener.class);
+ return listenerList.getListeners(DocumentListener.class);
}
/**
@@ -508,8 +507,7 @@
* @since 1.4
*/
public UndoableEditListener[] getUndoableEditListeners() {
- return (UndoableEditListener[])listenerList.getListeners(
- UndoableEditListener.class);
+ return listenerList.getListeners(UndoableEditListener.class);
}
/**
@@ -610,7 +608,7 @@
DefaultDocumentEvent chng =
new DefaultDocumentEvent(offs, len, DocumentEvent.EventType.REMOVE);
- boolean isComposedTextElement = false;
+ boolean isComposedTextElement;
// Check whether the position of interest is the composed text
isComposedTextElement = Utilities.isComposedTextElement(this, offs);
@@ -1051,7 +1049,7 @@
byte levels[] = calculateBidiLevels( firstPStart, lastPEnd );
- Vector newElements = new Vector();
+ Vector<Element> newElements = new Vector<Element>();
// Calculate the first span of characters in the affected range with
// the same bidi level. If this level is the same as the level of the
@@ -1831,7 +1829,6 @@
}
out.println("["+contentStr+"]");
} catch (BadLocationException e) {
- ;
}
} else {
@@ -2460,7 +2457,7 @@
if(nchildren == 0)
return null;
- Vector tempVector = new Vector(nchildren);
+ Vector<AbstractElement> tempVector = new Vector<AbstractElement>(nchildren);
for(int counter = 0; counter < nchildren; counter++)
tempVector.addElement(children[counter]);
@@ -2749,7 +2746,7 @@
// if the number of changes gets too great, start using
// a hashtable for to locate the change for a given element.
if ((changeLookup == null) && (edits.size() > 10)) {
- changeLookup = new Hashtable();
+ changeLookup = new Hashtable<Element, ElementChange>();
int n = edits.size();
for (int i = 0; i < n; i++) {
Object o = edits.elementAt(i);
@@ -2918,7 +2915,7 @@
*/
public DocumentEvent.ElementChange getChange(Element elem) {
if (changeLookup != null) {
- return (DocumentEvent.ElementChange) changeLookup.get(elem);
+ return changeLookup.get(elem);
}
int n = edits.size();
for (int i = 0; i < n; i++) {
@@ -2937,7 +2934,7 @@
private int offset;
private int length;
- private Hashtable changeLookup;
+ private Hashtable<Element, ElementChange> changeLookup;
private DocumentEvent.EventType type;
}
--- a/jdk/src/share/classes/javax/swing/text/AsyncBoxView.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/AsyncBoxView.java Tue Aug 12 17:59:58 2008 -0700
@@ -25,6 +25,7 @@
package javax.swing.text;
import java.util.*;
+import java.util.List;
import java.awt.*;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
@@ -58,7 +59,7 @@
*/
public AsyncBoxView(Element elem, int axis) {
super(elem);
- stats = new ArrayList();
+ stats = new ArrayList<ChildState>();
this.axis = axis;
locator = new ChildLocator();
flushTask = new FlushTask();
@@ -197,7 +198,7 @@
protected ChildState getChildState(int index) {
synchronized(stats) {
if ((index >= 0) && (index < stats.size())) {
- return (ChildState) stats.get(index);
+ return stats.get(index);
}
return null;
}
@@ -357,7 +358,7 @@
synchronized(stats) {
// remove the replaced state records
for (int i = 0; i < length; i++) {
- ChildState cs = (ChildState)stats.remove(offset);
+ ChildState cs = stats.remove(offset);
float csSpan = cs.getMajorSpan();
cs.getChildView().setParent(null);
@@ -863,7 +864,7 @@
/**
* The children and their layout statistics.
*/
- java.util.List stats;
+ List<ChildState> stats;
/**
* Current span along the major axis. This
@@ -1110,7 +1111,7 @@
*/
int updateChildOffsets(float targetOffset) {
int n = getViewCount();
- int targetIndex = n - 1;;
+ int targetIndex = n - 1;
int pos = lastValidOffset.getChildView().getStartOffset();
int startIndex = getViewIndex(pos, Position.Bias.Forward);
float start = lastValidOffset.getMajorOffset();
@@ -1394,7 +1395,6 @@
private float min;
private float pref;
private float max;
- private float align;
private boolean minorValid;
// major axis
--- a/jdk/src/share/classes/javax/swing/text/ComponentView.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/ComponentView.java Tue Aug 12 17:59:58 2008 -0700
@@ -27,6 +27,7 @@
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
+import java.util.Set;
import javax.swing.SwingUtilities;
import javax.swing.event.*;
@@ -434,7 +435,7 @@
/**
* Shows or hides this component depending on the value of parameter
* <code>b</code>.
- * @param <code>b</code> If <code>true</code>, shows this component;
+ * @param b If <code>true</code>, shows this component;
* otherwise, hides this component.
* @see #isVisible
* @since JDK1.1
@@ -480,7 +481,7 @@
return yalign;
}
- public java.util.Set getFocusTraversalKeys(int id) {
+ public Set<AWTKeyStroke> getFocusTraversalKeys(int id) {
return KeyboardFocusManager.getCurrentKeyboardFocusManager().
getDefaultFocusTraversalKeys(id);
}
--- a/jdk/src/share/classes/javax/swing/text/DefaultCaret.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/DefaultCaret.java Tue Aug 12 17:59:58 2008 -0700
@@ -774,8 +774,7 @@
* @since 1.4
*/
public ChangeListener[] getChangeListeners() {
- return (ChangeListener[])listenerList.getListeners(
- ChangeListener.class);
+ return listenerList.getListeners(ChangeListener.class);
}
/**
@@ -1330,7 +1329,7 @@
if (this.dot != this.mark && component != null) {
Clipboard clip = getSystemSelection();
if (clip != null) {
- String selectedText = null;
+ String selectedText;
if (component instanceof JPasswordField
&& component.getClientProperty("JPasswordField.cutCopyAllowed") !=
Boolean.TRUE) {
--- a/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java Tue Aug 12 17:59:58 2008 -0700
@@ -68,7 +68,7 @@
private boolean commitOnEdit;
/** Class used to create new instances. */
- private Class valueClass;
+ private Class<?> valueClass;
/** NavigationFilter that forwards calls back to DefaultFormatter. */
private NavigationFilter navigationFilter;
@@ -231,7 +231,7 @@
* @return Object representation of text
*/
public Object stringToValue(String string) throws ParseException {
- Class vc = getValueClass();
+ Class<?> vc = getValueClass();
JFormattedTextField ftf = getFormattedTextField();
if (vc == null && ftf != null) {
--- a/jdk/src/share/classes/javax/swing/text/DefaultHighlighter.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/DefaultHighlighter.java Tue Aug 12 17:59:58 2008 -0700
@@ -56,7 +56,7 @@
// PENDING(prinz) - should cull ranges not visible
int len = highlights.size();
for (int i = 0; i < len; i++) {
- HighlightInfo info = (HighlightInfo) highlights.elementAt(i);
+ HighlightInfo info = highlights.elementAt(i);
if (!(info instanceof LayeredHighlightInfo)) {
// Avoid allocing unless we need it.
Rectangle a = component.getBounds();
@@ -66,7 +66,7 @@
a.width -= insets.left + insets.right;
a.height -= insets.top + insets.bottom;
for (; i < len; i++) {
- info = (HighlightInfo)highlights.elementAt(i);
+ info = highlights.elementAt(i);
if (!(info instanceof LayeredHighlightInfo)) {
Highlighter.HighlightPainter p = info.getPainter();
p.paint(g, info.getStartOffset(), info.getEndOffset(),
@@ -159,7 +159,7 @@
int p0 = -1;
int p1 = -1;
for (int i = 0; i < len; i++) {
- HighlightInfo hi = (HighlightInfo)highlights.elementAt(i);
+ HighlightInfo hi = highlights.elementAt(i);
if (hi instanceof LayeredHighlightInfo) {
LayeredHighlightInfo info = (LayeredHighlightInfo)hi;
minX = Math.min(minX, info.x);
@@ -195,7 +195,7 @@
int p0 = Integer.MAX_VALUE;
int p1 = 0;
for (int i = 0; i < len; i++) {
- HighlightInfo info = (HighlightInfo) highlights.elementAt(i);
+ HighlightInfo info = highlights.elementAt(i);
p0 = Math.min(p0, info.p0.getOffset());
p1 = Math.max(p1, info.p1.getOffset());
}
@@ -282,7 +282,7 @@
Shape viewBounds,
JTextComponent editor, View view) {
for (int counter = highlights.size() - 1; counter >= 0; counter--) {
- Object tag = highlights.elementAt(counter);
+ HighlightInfo tag = highlights.elementAt(counter);
if (tag instanceof LayeredHighlightInfo) {
LayeredHighlightInfo lhi = (LayeredHighlightInfo)tag;
int start = lhi.getStartOffset();
@@ -333,7 +333,7 @@
private final static Highlighter.Highlight[] noHighlights =
new Highlighter.Highlight[0];
- private Vector highlights = new Vector(); // Vector<HighlightInfo>
+ private Vector<HighlightInfo> highlights = new Vector<HighlightInfo>();
private JTextComponent component;
private boolean drawsLayeredHighlights;
private SafeDamager safeDamager = new SafeDamager();
@@ -573,8 +573,8 @@
* call.
*/
class SafeDamager implements Runnable {
- private Vector p0 = new Vector(10);
- private Vector p1 = new Vector(10);
+ private Vector<Position> p0 = new Vector<Position>(10);
+ private Vector<Position> p1 = new Vector<Position>(10);
private Document lastDoc = null;
/**
@@ -589,8 +589,8 @@
int len = p0.size();
for (int i = 0; i < len; i++){
mapper.damageRange(component,
- ((Position)p0.get(i)).getOffset(),
- ((Position)p1.get(i)).getOffset());
+ p0.get(i).getOffset(),
+ p1.get(i).getOffset());
}
}
}
--- a/jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java Tue Aug 12 17:59:58 2008 -0700
@@ -84,7 +84,7 @@
*/
public DefaultStyledDocument(Content c, StyleContext styles) {
super(c, styles);
- listeningStyles = new Vector();
+ listeningStyles = new Vector<Style>();
buffer = new ElementBuffer(createDefaultRoot());
Style defaultStyle = styles.getStyle(StyleContext.DEFAULT_STYLE);
setLogicalStyle(0, defaultStyle);
@@ -349,7 +349,7 @@
int prevStartOffset = prevLeaf.getStartOffset();
BranchElement prevParent = (BranchElement) prevLeaf.getParentElement();
int prevIndex = prevParent.getElementIndex(prevStartOffset);
- Element newElem = null;
+ Element newElem;
newElem = createLeafElement(prevParent, prevLeaf.getAttributes(),
prevStartOffset, lastEndOffset);
Element[] prevRemoved = { prevLeaf };
@@ -511,7 +511,7 @@
AttributeSet sCopy = s.copyAttributes();
// PENDING(prinz) - this isn't a very efficient way to iterate
- int lastEnd = Integer.MAX_VALUE;
+ int lastEnd;
for (int pos = offset; pos < (offset + length); pos = lastEnd) {
Element run = getCharacterElement(pos);
lastEnd = run.getEndOffset();
@@ -597,7 +597,7 @@
* @return the element
*/
public Element getParagraphElement(int pos) {
- Element e = null;
+ Element e;
for (e = getDefaultRootElement(); ! e.isLeaf(); ) {
int index = e.getElementIndex(pos);
e = e.getElement(index);
@@ -614,7 +614,7 @@
* @return the element
*/
public Element getCharacterElement(int pos) {
- Element e = null;
+ Element e;
for (e = getDefaultRootElement(); ! e.isLeaf(); ) {
int index = e.getElementIndex(pos);
e = e.getElement(index);
@@ -655,7 +655,7 @@
try {
Segment s = new Segment();
- Vector parseBuffer = new Vector();
+ Vector<ElementSpec> parseBuffer = new Vector<ElementSpec>();
ElementSpec lastStartSpec = null;
boolean insertingAfterNewline = false;
short lastStartDirection = ElementSpec.OriginateDirection;
@@ -670,8 +670,7 @@
offset, endOffset);
for(int counter = parseBuffer.size() - 1; counter >= 0;
counter--) {
- ElementSpec spec = (ElementSpec)parseBuffer.
- elementAt(counter);
+ ElementSpec spec = parseBuffer.elementAt(counter);
if(spec.getType() == ElementSpec.StartTagType) {
lastStartSpec = spec;
break;
@@ -709,7 +708,7 @@
n - lastOffset));
}
- ElementSpec first = (ElementSpec) parseBuffer.firstElement();
+ ElementSpec first = parseBuffer.firstElement();
int docLength = getLength();
@@ -750,7 +749,7 @@
// direction isn't originate, and the element at endOffset
// is a leaf.
if(insertingAtBoundry && endOffset < docLength) {
- ElementSpec last = (ElementSpec) parseBuffer.lastElement();
+ ElementSpec last = parseBuffer.lastElement();
if(last.getType() == ElementSpec.ContentType &&
last.getDirection() != ElementSpec.JoinPreviousDirection &&
((lastStartSpec == null && (paragraph == pParagraph ||
@@ -772,7 +771,7 @@
else if(!insertingAtBoundry && lastStartSpec != null &&
lastStartSpec.getDirection() ==
ElementSpec.JoinFractureDirection) {
- ElementSpec last = (ElementSpec) parseBuffer.lastElement();
+ ElementSpec last = parseBuffer.lastElement();
if(last.getType() == ElementSpec.ContentType &&
last.getDirection() != ElementSpec.JoinPreviousDirection &&
attr.isEqual(cattr)) {
@@ -805,7 +804,7 @@
* necessarily create the last start spec).
*/
short createSpecsForInsertAfterNewline(Element paragraph,
- Element pParagraph, AttributeSet pattr, Vector parseBuffer,
+ Element pParagraph, AttributeSet pattr, Vector<ElementSpec> parseBuffer,
int offset, int endOffset) {
// Need to find the common parent of pParagraph and paragraph.
if(paragraph.getParentElement() == pParagraph.getParentElement()) {
@@ -825,8 +824,8 @@
else {
// Will only happen for text with more than 2 levels.
// Find the common parent of a paragraph and pParagraph
- Vector leftParents = new Vector();
- Vector rightParents = new Vector();
+ Vector<Element> leftParents = new Vector<Element>();
+ Vector<Element> rightParents = new Vector<Element>();
Element e = pParagraph;
while(e != null) {
leftParents.addElement(e);
@@ -847,11 +846,10 @@
(null, ElementSpec.EndTagType));
}
// And the starts.
- ElementSpec spec = null;
+ ElementSpec spec;
for(int counter = rightParents.size() - 1;
counter >= 0; counter--) {
- spec = new ElementSpec(((Element)rightParents.
- elementAt(counter)).getAttributes(),
+ spec = new ElementSpec(rightParents.elementAt(counter).getAttributes(),
ElementSpec.StartTagType);
if(counter > 0)
spec.setDirection(ElementSpec.JoinNextDirection);
@@ -1007,7 +1005,7 @@
if (listenerList.getListenerCount(DocumentListener.class) == 0) {
for (int counter = listeningStyles.size() - 1; counter >= 0;
counter--) {
- ((Style)listeningStyles.elementAt(counter)).
+ listeningStyles.elementAt(counter).
removeChangeListener(styleChangeListener);
}
listeningStyles.removeAllElements();
@@ -1077,7 +1075,7 @@
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException {
- listeningStyles = new Vector();
+ listeningStyles = new Vector<Style>();
s.defaultReadObject();
// Reinstall style listeners.
if (styleContextChangeListener == null &&
@@ -1101,7 +1099,7 @@
protected ElementBuffer buffer;
/** Styles listening to. */
- private transient Vector listeningStyles;
+ private transient Vector<Style> listeningStyles;
/** Listens to Styles. */
private transient ChangeListener styleChangeListener;
@@ -1401,8 +1399,8 @@
*/
public ElementBuffer(Element root) {
this.root = root;
- changes = new Vector();
- path = new Stack();
+ changes = new Vector<ElemChanges>();
+ path = new Stack<ElemChanges>();
}
/**
@@ -1454,7 +1452,7 @@
elem = child;
index = elem.getElementIndex(0);
}
- ElemChanges ec = (ElemChanges) path.peek();
+ ElemChanges ec = path.peek();
Element child = ec.parent.getElement(ec.index);
ec.added.addElement(createLeafElement(ec.parent,
child.getAttributes(), getLength(),
@@ -1646,7 +1644,7 @@
index = e.getElementIndex(offs);
}
- ElemChanges ec = (ElemChanges) path.peek();
+ ElemChanges ec = path.peek();
Element child = ec.parent.getElement(ec.index);
// make sure there is something to do... if the
// offset is already at a boundary then there is
@@ -1722,15 +1720,14 @@
void endEdits(DefaultDocumentEvent de) {
int n = changes.size();
for (int i = 0; i < n; i++) {
- ElemChanges ec = (ElemChanges) changes.elementAt(i);
+ ElemChanges ec = changes.elementAt(i);
Element[] removed = new Element[ec.removed.size()];
ec.removed.copyInto(removed);
Element[] added = new Element[ec.added.size()];
ec.added.copyInto(added);
int index = ec.index;
((BranchElement) ec.parent).replace(index, removed.length, added);
- ElementEdit ee = new ElementEdit((BranchElement) ec.parent,
- index, removed, added);
+ ElementEdit ee = new ElementEdit(ec.parent, index, removed, added);
de.addEdit(ee);
}
@@ -1767,12 +1764,12 @@
this.endOffset = offset + length;
pos = offset;
if (changes == null) {
- changes = new Vector();
+ changes = new Vector<ElemChanges>();
} else {
changes.removeAllElements();
}
if (path == null) {
- path = new Stack();
+ path = new Stack<ElemChanges>();
} else {
path.removeAllElements();
}
@@ -1799,7 +1796,7 @@
}
void pop() {
- ElemChanges ec = (ElemChanges) path.peek();
+ ElemChanges ec = path.peek();
path.pop();
if ((ec.added.size() > 0) || (ec.removed.size() > 0)) {
changes.addElement(ec);
@@ -1808,7 +1805,7 @@
if(e.getElementCount() == 0) {
// if we pushed a branch element that didn't get
// used, make sure its not marked as having been added.
- ec = (ElemChanges) path.peek();
+ ec = path.peek();
ec.added.removeElement(e);
}
}
@@ -1822,7 +1819,7 @@
}
void insertElement(ElementSpec es) {
- ElemChanges ec = (ElemChanges) path.peek();
+ ElemChanges ec = path.peek();
switch(es.getType()) {
case ElementSpec.StartTagType:
switch(es.getDirection()) {
@@ -1930,7 +1927,7 @@
int index0 = elem.getElementIndex(rmOffs0);
int index1 = elem.getElementIndex(rmOffs1);
push(elem, index0);
- ElemChanges ec = (ElemChanges)path.peek();
+ ElemChanges ec = path.peek();
// if the range is contained by one element,
// we just forward the request
@@ -2068,7 +2065,7 @@
if (rj.getStartOffset() == rmOffs1) {
rj = null;
}
- Vector children = new Vector();
+ Vector<Element> children = new Vector<Element>();
// transfer the left
for (int i = 0; i < ljIndex; i++) {
@@ -2142,7 +2139,7 @@
}
Element e = createBranchElement(parent, clonee.getAttributes());
int n = clonee.getElementCount();
- ArrayList childrenList = new ArrayList(n);
+ ArrayList<Element> childrenList = new ArrayList<Element>(n);
for (int i = 0; i < n; i++) {
Element elem = clonee.getElement(i);
if (elem.getStartOffset() < rmOffs0 || elem.getEndOffset() > rmOffs1) {
@@ -2150,7 +2147,7 @@
}
}
Element[] children = new Element[childrenList.size()];
- children = (Element[])childrenList.toArray(children);
+ children = childrenList.toArray(children);
((BranchElement)e).replace(0, 0, children);
return e;
}
@@ -2355,7 +2352,7 @@
*/
void fractureDeepestLeaf(ElementSpec[] specs) {
// Split the bottommost leaf. It will be recreated elsewhere.
- ElemChanges ec = (ElemChanges) path.peek();
+ ElemChanges ec = path.peek();
Element child = ec.parent.getElement(ec.index);
// Inserts at offset 0 do not need to recreate child (it would
// have a length of 0!).
@@ -2380,7 +2377,7 @@
*/
void insertFirstContent(ElementSpec[] specs) {
ElementSpec firstSpec = specs[0];
- ElemChanges ec = (ElemChanges) path.peek();
+ ElemChanges ec = path.peek();
Element child = ec.parent.getElement(ec.index);
int firstEndOffset = offset + firstSpec.getLength();
boolean isOnlyContent = (specs.length == 1);
@@ -2463,8 +2460,8 @@
transient int offset;
transient int length;
transient int endOffset;
- transient Vector changes; // Vector<ElemChanges>
- transient Stack path; // Stack<ElemChanges>
+ transient Vector<ElemChanges> changes;
+ transient Stack<ElemChanges> path;
transient boolean insertOp;
transient boolean recreateLeafs; // For insert.
@@ -2494,8 +2491,8 @@
this.parent = parent;
this.index = index;
this.isFracture = isFracture;
- added = new Vector();
- removed = new Vector();
+ added = new Vector<Element>();
+ removed = new Vector<Element>();
}
public String toString() {
@@ -2504,8 +2501,8 @@
Element parent;
int index;
- Vector added;
- Vector removed;
+ Vector<Element> added;
+ Vector<Element> removed;
boolean isFracture;
}
@@ -2611,7 +2608,7 @@
/* This has an implicit reference to the handler object. */
private class DocReference extends WeakReference<DefaultStyledDocument> {
- DocReference(DefaultStyledDocument d, ReferenceQueue q) {
+ DocReference(DefaultStyledDocument d, ReferenceQueue<DefaultStyledDocument> q) {
super(d, q);
}
@@ -2624,19 +2621,19 @@
}
/** Class-specific reference queues. */
- private final static Map<Class, ReferenceQueue> queueMap
- = new HashMap<Class, ReferenceQueue>();
+ private final static Map<Class, ReferenceQueue<DefaultStyledDocument>> queueMap
+ = new HashMap<Class, ReferenceQueue<DefaultStyledDocument>>();
/** A weak reference to the document object. */
private DocReference doc;
AbstractChangeHandler(DefaultStyledDocument d) {
Class c = getClass();
- ReferenceQueue q;
+ ReferenceQueue<DefaultStyledDocument> q;
synchronized (queueMap) {
q = queueMap.get(c);
if (q == null) {
- q = new ReferenceQueue();
+ q = new ReferenceQueue<DefaultStyledDocument>();
queueMap.put(c, q);
}
}
@@ -2650,7 +2647,7 @@
*/
static List<ChangeListener> getStaleListeners(ChangeListener l) {
List<ChangeListener> staleListeners = new ArrayList<ChangeListener>();
- ReferenceQueue q = queueMap.get(l.getClass());
+ ReferenceQueue<DefaultStyledDocument> q = queueMap.get(l.getClass());
if (q != null) {
DocReference r;
--- a/jdk/src/share/classes/javax/swing/text/ElementIterator.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/ElementIterator.java Tue Aug 12 17:59:58 2008 -0700
@@ -72,7 +72,7 @@
private Element root;
- private Stack elementStack = null;
+ private Stack<StackItem> elementStack = null;
/**
* The StackItem class stores the element
@@ -148,9 +148,9 @@
try {
ElementIterator it = new ElementIterator(root);
if (elementStack != null) {
- it.elementStack = new Stack();
+ it.elementStack = new Stack<StackItem>();
for (int i = 0; i < elementStack.size(); i++) {
- StackItem item = (StackItem)elementStack.elementAt(i);
+ StackItem item = elementStack.elementAt(i);
StackItem clonee = (StackItem)item.clone();
it.elementStack.push(clonee);
}
@@ -173,7 +173,7 @@
return null;
}
- elementStack = new Stack();
+ elementStack = new Stack<StackItem>();
if (root.getElementCount() != 0) {
elementStack.push(new StackItem(root));
}
@@ -209,7 +209,7 @@
get a handle to the element on top of the stack.
*/
if (! elementStack.empty()) {
- StackItem item = (StackItem)elementStack.peek();
+ StackItem item = elementStack.peek();
Element elem = item.getElement();
int index = item.getIndex();
// self reference
@@ -247,7 +247,7 @@
// get a handle to the element on top of the stack
- StackItem item = (StackItem)elementStack.peek();
+ StackItem item = elementStack.peek();
Element elem = item.getElement();
int index = item.getIndex();
@@ -272,7 +272,7 @@
if (!elementStack.isEmpty()) {
/* Increment the child index for the item that
is now on top of the stack. */
- StackItem top = (StackItem)elementStack.peek();
+ StackItem top = elementStack.peek();
top.incrementIndex();
/* We now want to return its next child, therefore
call next() recursively. */
@@ -300,7 +300,7 @@
// get a handle to the element on top of the stack
//
- StackItem item = (StackItem)elementStack.peek();
+ StackItem item = elementStack.peek();
Element elem = item.getElement();
int index = item.getIndex();
@@ -320,8 +320,8 @@
/* We need to return either the item
below the top item or one of the
former's children. */
- Object top = elementStack.pop();
- item = (StackItem)elementStack.peek();
+ StackItem top = elementStack.pop();
+ item = elementStack.peek();
// restore the top item.
elementStack.push(top);
--- a/jdk/src/share/classes/javax/swing/text/FlowView.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/FlowView.java Tue Aug 12 17:59:58 2008 -0700
@@ -184,9 +184,9 @@
final int faxis = getFlowAxis();
int newSpan;
if (faxis == X_AXIS) {
- newSpan = (int)width;
+ newSpan = width;
} else {
- newSpan = (int)height;
+ newSpan = height;
}
if (layoutSpan != newSpan) {
layoutChanged(faxis);
@@ -197,7 +197,7 @@
// repair the flow if necessary
if (! isLayoutValid(faxis)) {
final int heightAxis = getAxis();
- int oldFlowHeight = (int)((heightAxis == X_AXIS)? getWidth() : getHeight());
+ int oldFlowHeight = (heightAxis == X_AXIS)? getWidth() : getHeight();
strategy.layout(this);
int newFlowHeight = (int) getPreferredSpan(heightAxis);
if (oldFlowHeight != newFlowHeight) {
--- a/jdk/src/share/classes/javax/swing/text/GapContent.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/GapContent.java Tue Aug 12 17:59:58 2008 -0700
@@ -83,7 +83,7 @@
marks = new MarkVector();
search = new MarkData(0);
- queue = new ReferenceQueue();
+ queue = new ReferenceQueue<StickyPosition>();
}
/**
@@ -262,13 +262,13 @@
* it. The update table holds only a reference
* to this data.
*/
- final class MarkData extends WeakReference {
+ final class MarkData extends WeakReference<StickyPosition> {
MarkData(int index) {
super(null);
this.index = index;
}
- MarkData(int index, StickyPosition position, ReferenceQueue queue) {
+ MarkData(int index, StickyPosition position, ReferenceQueue<? super StickyPosition> queue) {
super(position, queue);
this.index = index;
}
@@ -287,7 +287,7 @@
}
StickyPosition getPosition() {
- return (StickyPosition)get();
+ return get();
}
int index;
}
@@ -329,7 +329,7 @@
*/
private transient int unusedMarks = 0;
- private transient ReferenceQueue queue;
+ private transient ReferenceQueue<StickyPosition> queue;
final static int GROWTH_SIZE = 1024 * 512;
@@ -535,7 +535,7 @@
return 0;
}
- int cmp = 0;
+ int cmp;
MarkData last = marks.elementAt(upper);
cmp = compare(o, last);
if (cmp > 0)
@@ -691,7 +691,7 @@
s.defaultReadObject();
marks = new MarkVector();
search = new MarkData(0);
- queue = new ReferenceQueue();
+ queue = new ReferenceQueue<StickyPosition>();
}
--- a/jdk/src/share/classes/javax/swing/text/InternationalFormatter.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/InternationalFormatter.java Tue Aug 12 17:59:58 2008 -0700
@@ -27,6 +27,7 @@
import java.awt.event.ActionEvent;
import java.io.*;
import java.text.*;
+import java.text.AttributedCharacterIterator.Attribute;
import java.util.*;
import javax.swing.*;
import javax.swing.text.*;
@@ -352,13 +353,13 @@
updateMask();
}
- Map attrs = getAttributes(offset);
+ Map<Attribute, Object> attrs = getAttributes(offset);
if (attrs != null && attrs.size() > 0) {
- ArrayList al = new ArrayList();
+ ArrayList<Attribute> al = new ArrayList<Attribute>();
al.addAll(attrs.keySet());
- return (Format.Field[])al.toArray(EMPTY_FIELD_ARRAY);
+ return al.toArray(EMPTY_FIELD_ARRAY);
}
return EMPTY_FIELD_ARRAY;
}
@@ -440,7 +441,7 @@
/**
* Returns a Set of the attribute identifiers at <code>index</code>.
*/
- Map getAttributes(int index) {
+ Map<Attribute, Object> getAttributes(int index) {
if (isValidMask()) {
AttributedCharacterIterator iterator = getIterator();
--- a/jdk/src/share/classes/javax/swing/text/JTextComponent.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/JTextComponent.java Tue Aug 12 17:59:58 2008 -0700
@@ -386,7 +386,7 @@
* @since 1.4
*/
public CaretListener[] getCaretListeners() {
- return (CaretListener[])listenerList.getListeners(CaretListener.class);
+ return listenerList.getListeners(CaretListener.class);
}
/**
@@ -1171,16 +1171,15 @@
* @param actions the set of actions
*/
public static void loadKeymap(Keymap map, KeyBinding[] bindings, Action[] actions) {
- Hashtable h = new Hashtable();
- for (int i = 0; i < actions.length; i++) {
- Action a = actions[i];
+ Hashtable<String, Action> h = new Hashtable<String, Action>();
+ for (Action a : actions) {
String value = (String)a.getValue(Action.NAME);
h.put((value!=null ? value:""), a);
}
- for (int i = 0; i < bindings.length; i++) {
- Action a = (Action) h.get(bindings[i].actionName);
+ for (KeyBinding binding : bindings) {
+ Action a = h.get(binding.actionName);
if (a != null) {
- map.addActionForKeyStroke(bindings[i].key, a);
+ map.addActionForKeyStroke(binding.key, a);
}
}
}
@@ -1192,11 +1191,11 @@
* invoked from within a <code>doPrivileged</code>, and it is also
* assumed <code>klass</code> extends <code>JTextComponent</code>.
*/
- private static Boolean isProcessInputMethodEventOverridden(Class klass) {
+ private static Boolean isProcessInputMethodEventOverridden(Class<?> klass) {
if (klass == JTextComponent.class) {
return Boolean.FALSE;
}
- Boolean retValue = (Boolean)overrideMap.get(klass.getName());
+ Boolean retValue = overrideMap.get(klass.getName());
if (retValue != null) {
return retValue;
@@ -2053,7 +2052,7 @@
*/
public boolean getScrollableTracksViewportWidth() {
if (getParent() instanceof JViewport) {
- return (((JViewport)getParent()).getWidth() > getPreferredSize().width);
+ return (getParent().getWidth() > getPreferredSize().width);
}
return false;
}
@@ -2073,7 +2072,7 @@
*/
public boolean getScrollableTracksViewportHeight() {
if (getParent() instanceof JViewport) {
- return (((JViewport)getParent()).getHeight() > getPreferredSize().height);
+ return (getParent().getHeight() > getPreferredSize().height);
}
return false;
}
@@ -3033,7 +3032,7 @@
StyledDocument sdoc = (StyledDocument)model;
return sdoc.getParagraphElement(index);
} else {
- Element para = null;
+ Element para;
for (para = model.getDefaultRootElement(); ! para.isLeaf(); ) {
int pos = para.getElementIndex(index);
para = para.getElement(pos);
@@ -3535,7 +3534,7 @@
throw new BadLocationException("Location out of bounds", index);
}
// locate the Element at index
- Element indexElement = null;
+ Element indexElement;
// locate the Element at our index/offset
int elementIndex = -1; // test for initialization
for (indexElement = model.getDefaultRootElement();
@@ -3553,7 +3552,7 @@
// find the first Element before/after ours w/the same AttributeSet
// if we are already at edge of the first element in our parent
// then return that edge
- Element edgeElement = indexElement;
+ Element edgeElement;
switch (direction) {
case -1:
case 1:
@@ -3903,7 +3902,7 @@
* Maps from class name to Boolean indicating if
* <code>processInputMethodEvent</code> has been overriden.
*/
- private static Map overrideMap;
+ private static Map<String, Boolean> overrideMap;
/**
* Returns a string representation of this <code>JTextComponent</code>.
@@ -4007,9 +4006,9 @@
}
private DataFlavor getFlavor(DataFlavor[] flavors) {
if (flavors != null) {
- for (int counter = 0; counter < flavors.length; counter++) {
- if (flavors[counter].equals(DataFlavor.stringFlavor)) {
- return flavors[counter];
+ for (DataFlavor flavor : flavors) {
+ if (flavor.equals(DataFlavor.stringFlavor)) {
+ return flavor;
}
}
}
@@ -4065,7 +4064,7 @@
DefaultKeymap(String nm, Keymap parent) {
this.nm = nm;
this.parent = parent;
- bindings = new Hashtable();
+ bindings = new Hashtable<KeyStroke, Action>();
}
/**
@@ -4095,7 +4094,7 @@
}
public Action getAction(KeyStroke key) {
- Action a = (Action) bindings.get(key);
+ Action a = bindings.get(key);
if ((a == null) && (parent != null)) {
a = parent.getAction(key);
}
@@ -4105,8 +4104,8 @@
public KeyStroke[] getBoundKeyStrokes() {
KeyStroke[] keys = new KeyStroke[bindings.size()];
int i = 0;
- for (Enumeration e = bindings.keys() ; e.hasMoreElements() ;) {
- keys[i++] = (KeyStroke) e.nextElement();
+ for (Enumeration<KeyStroke> e = bindings.keys() ; e.hasMoreElements() ;) {
+ keys[i++] = e.nextElement();
}
return keys;
}
@@ -4114,8 +4113,8 @@
public Action[] getBoundActions() {
Action[] actions = new Action[bindings.size()];
int i = 0;
- for (Enumeration e = bindings.elements() ; e.hasMoreElements() ;) {
- actions[i++] = (Action) e.nextElement();
+ for (Enumeration<Action> e = bindings.elements() ; e.hasMoreElements() ;) {
+ actions[i++] = e.nextElement();
}
return actions;
}
@@ -4126,13 +4125,12 @@
}
KeyStroke[] retValue = null;
// Determine local bindings first.
- Vector keyStrokes = null;
- for (Enumeration enum_ = bindings.keys();
- enum_.hasMoreElements();) {
- Object key = enum_.nextElement();
+ Vector<KeyStroke> keyStrokes = null;
+ for (Enumeration<KeyStroke> keys = bindings.keys(); keys.hasMoreElements();) {
+ KeyStroke key = keys.nextElement();
if (bindings.get(key) == a) {
if (keyStrokes == null) {
- keyStrokes = new Vector();
+ keyStrokes = new Vector<KeyStroke>();
}
keyStrokes.addElement(key);
}
@@ -4153,7 +4151,7 @@
}
if (rCount > 0 && rCount < pStrokes.length) {
if (keyStrokes == null) {
- keyStrokes = new Vector();
+ keyStrokes = new Vector<KeyStroke>();
}
for (int counter = pStrokes.length - 1; counter >= 0;
counter--) {
@@ -4218,7 +4216,7 @@
String nm;
Keymap parent;
- Hashtable bindings;
+ Hashtable<KeyStroke, Action> bindings;
Action defaultAction;
}
@@ -4507,8 +4505,7 @@
//
public InputMethodRequests getInputMethodRequests() {
if (inputMethodRequestsHandler == null) {
- inputMethodRequestsHandler =
- (InputMethodRequests)new InputMethodRequestsHandler();
+ inputMethodRequestsHandler = new InputMethodRequestsHandler();
Document doc = getDocument();
if (doc != null) {
doc.addDocumentListener((DocumentListener)inputMethodRequestsHandler);
@@ -4923,16 +4920,16 @@
//
private boolean isProcessInputMethodEventOverridden() {
if (overrideMap == null) {
- overrideMap = Collections.synchronizedMap(new HashMap());
+ overrideMap = Collections.synchronizedMap(new HashMap<String, Boolean>());
}
- Boolean retValue = (Boolean)overrideMap.get(getClass().getName());
+ Boolean retValue = overrideMap.get(getClass().getName());
if (retValue != null) {
return retValue.booleanValue();
}
- Boolean ret = (Boolean)AccessController.doPrivileged(new
- PrivilegedAction() {
- public Object run() {
+ Boolean ret = AccessController.doPrivileged(new
+ PrivilegedAction<Boolean>() {
+ public Boolean run() {
return isProcessInputMethodEventOverridden(
JTextComponent.this.getClass());
}
--- a/jdk/src/share/classes/javax/swing/text/LayoutQueue.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/LayoutQueue.java Tue Aug 12 17:59:58 2008 -0700
@@ -35,7 +35,7 @@
*/
public class LayoutQueue {
- Vector tasks;
+ Vector<Runnable> tasks;
Thread worker;
static LayoutQueue defaultQueue;
@@ -44,7 +44,7 @@
* Construct a layout queue.
*/
public LayoutQueue() {
- tasks = new Vector();
+ tasks = new Vector<Runnable>();
}
/**
@@ -90,7 +90,7 @@
return null;
}
}
- Runnable work = (Runnable) tasks.firstElement();
+ Runnable work = tasks.firstElement();
tasks.removeElementAt(0);
return work;
}
--- a/jdk/src/share/classes/javax/swing/text/MaskFormatter.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/MaskFormatter.java Tue Aug 12 17:59:58 2008 -0700
@@ -446,7 +446,7 @@
*/
private Object stringToValue(String value, boolean completeMatch) throws
ParseException {
- int errorOffset = -1;
+ int errorOffset;
if ((errorOffset = getInvalidOffset(value, completeMatch)) == -1) {
if (!getValueContainsLiteralCharacters()) {
@@ -498,8 +498,8 @@
*/
private void updateInternalMask() throws ParseException {
String mask = getMask();
- ArrayList fixed = new ArrayList();
- ArrayList temp = fixed;
+ ArrayList<MaskCharacter> fixed = new ArrayList<MaskCharacter>();
+ ArrayList<MaskCharacter> temp = fixed;
if (mask != null) {
for (int counter = 0, maxCounter = mask.length();
--- a/jdk/src/share/classes/javax/swing/text/NumberFormatter.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/NumberFormatter.java Tue Aug 12 17:59:58 2008 -0700
@@ -299,10 +299,7 @@
if (attrs.get(NumberFormat.Field.SIGN) != null) {
size--;
}
- if (size == 0) {
- return true;
- }
- return false;
+ return size == 0;
}
return true;
}
@@ -315,10 +312,7 @@
boolean isNavigatable(int index) {
if (!super.isNavigatable(index)) {
// Don't skip the decimal, it causes wierd behavior
- if (getBufferedChar(index) == getDecimalSeparator()) {
- return true;
- }
- return false;
+ return getBufferedChar(index) == getDecimalSeparator();
}
return true;
}
@@ -341,11 +335,7 @@
Map attrs = iterator.getAttributes();
if (attrs != null && attrs.size() > 0) {
- Iterator keys = attrs.keySet().iterator();
-
- while (keys.hasNext()) {
- Object key = keys.next();
-
+ for (Object key : attrs.keySet()) {
if (key instanceof NumberFormat.Field) {
return (NumberFormat.Field)key;
}
@@ -461,7 +451,7 @@
}
}
if (string != null) {
- Class valueClass = getValueClass();
+ Class<?> valueClass = getValueClass();
if (valueClass == null) {
valueClass = value.getClass();
--- a/jdk/src/share/classes/javax/swing/text/PlainDocument.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/PlainDocument.java Tue Aug 12 17:59:58 2008 -0700
@@ -318,7 +318,7 @@
}
private AbstractElement defaultRoot;
- private Vector added = new Vector(); // Vector<Element>
- private Vector removed = new Vector(); // Vector<Element>
+ private Vector<Element> added = new Vector<Element>();
+ private Vector<Element> removed = new Vector<Element>();
private transient Segment s;
}
--- a/jdk/src/share/classes/javax/swing/text/SegmentCache.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/SegmentCache.java Tue Aug 12 17:59:58 2008 -0700
@@ -48,7 +48,7 @@
/**
* A list of the currently unused Segments.
*/
- private List segments;
+ private List<Segment> segments;
/**
@@ -80,7 +80,7 @@
* Creates and returns a SegmentCache.
*/
public SegmentCache() {
- segments = new ArrayList(11);
+ segments = new ArrayList<Segment>(11);
}
/**
@@ -92,7 +92,7 @@
int size = segments.size();
if (size > 0) {
- return (Segment)segments.remove(size - 1);
+ return segments.remove(size - 1);
}
}
return new CachedSegment();
--- a/jdk/src/share/classes/javax/swing/text/SimpleAttributeSet.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/SimpleAttributeSet.java Tue Aug 12 17:59:58 2008 -0700
@@ -56,7 +56,7 @@
*/
public static final AttributeSet EMPTY = new EmptyAttributeSet();
- private transient Hashtable table = new Hashtable(3);
+ private transient Hashtable<Object, Object> table = new Hashtable<Object, Object>(3);
/**
* Creates a new attribute set.
@@ -73,7 +73,7 @@
addAttributes(source);
}
- private SimpleAttributeSet(Hashtable table) {
+ private SimpleAttributeSet(Hashtable<Object, Object> table) {
this.table = table;
}
@@ -341,7 +341,7 @@
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException {
s.defaultReadObject();
- table = new Hashtable(3);
+ table = new Hashtable<Object, Object>(3);
StyleContext.readAttributeSet(s, this);
}
--- a/jdk/src/share/classes/javax/swing/text/StringContent.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/StringContent.java Tue Aug 12 17:59:58 2008 -0700
@@ -174,7 +174,7 @@
// some small documents won't have any sticky positions
// at all, so the buffer is created lazily.
if (marks == null) {
- marks = new Vector();
+ marks = new Vector<PosRec>();
}
return new StickyPosition(offset);
}
@@ -226,7 +226,7 @@
}
int n = marks.size();
for (int i = 0; i < n; i++) {
- PosRec mark = (PosRec) marks.elementAt(i);
+ PosRec mark = marks.elementAt(i);
if (mark.unused) {
// this record is no longer used, get rid of it
marks.removeElementAt(i);
@@ -241,7 +241,7 @@
synchronized void updateMarksForRemove(int offset, int length) {
int n = marks.size();
for (int i = 0; i < n; i++) {
- PosRec mark = (PosRec) marks.elementAt(i);
+ PosRec mark = marks.elementAt(i);
if (mark.unused) {
// this record is no longer used, get rid of it
marks.removeElementAt(i);
@@ -276,7 +276,7 @@
int end = offset + length;
Vector placeIn = (v == null) ? new Vector() : v;
for (int i = 0; i < n; i++) {
- PosRec mark = (PosRec) marks.elementAt(i);
+ PosRec mark = marks.elementAt(i);
if (mark.unused) {
// this record is no longer used, get rid of it
marks.removeElementAt(i);
@@ -312,7 +312,7 @@
private static final char[] empty = new char[0];
private char[] data;
private int count;
- transient Vector marks;
+ transient Vector<PosRec> marks;
/**
* holds the data for a mark... separately from
--- a/jdk/src/share/classes/javax/swing/text/StyleContext.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/StyleContext.java Tue Aug 12 17:59:58 2008 -0700
@@ -246,7 +246,7 @@
*/
public Font getFont(String family, int style, int size) {
fontSearch.setValue(family, style, size);
- Font f = (Font) fontTable.get(fontSearch);
+ Font f = fontTable.get(fontSearch);
if (f == null) {
// haven't seen this one yet.
Style defaultStyle =
@@ -517,12 +517,11 @@
// PENDING(prinz) should consider finding a alternative to
// generating extra garbage on search key.
SmallAttributeSet key = createSmallAttributeSet(search);
- WeakReference reference = (WeakReference)attributesPool.get(key);
+ WeakReference<SmallAttributeSet> reference = attributesPool.get(key);
SmallAttributeSet a;
- if (reference == null
- || (a = (SmallAttributeSet)reference.get()) == null) {
+ if (reference == null || (a = reference.get()) == null) {
a = key;
- attributesPool.put(a, new WeakReference(a));
+ attributesPool.put(a, new WeakReference<SmallAttributeSet>(a));
}
return a;
}
@@ -547,9 +546,7 @@
public String toString() {
removeUnusedSets();
String s = "";
- Iterator iterator = attributesPool.keySet().iterator();
- while (iterator.hasNext()) {
- SmallAttributeSet set = (SmallAttributeSet)iterator.next();
+ for (SmallAttributeSet set : attributesPool.keySet()) {
s = s + set + "\n";
}
return s;
@@ -676,8 +673,8 @@
public static void registerStaticAttributeKey(Object key) {
String ioFmt = key.getClass().getName() + "." + key.toString();
if (freezeKeyMap == null) {
- freezeKeyMap = new Hashtable();
- thawKeyMap = new Hashtable();
+ freezeKeyMap = new Hashtable<Object, String>();
+ thawKeyMap = new Hashtable<String, Object>();
}
freezeKeyMap.put(key, ioFmt);
thawKeyMap.put(ioFmt, key);
@@ -716,10 +713,10 @@
throws ClassNotFoundException, IOException
{
fontSearch = new FontKey(null, 0, 0);
- fontTable = new Hashtable();
+ fontTable = new Hashtable<FontKey, Font>();
search = new SimpleAttributeSet();
attributesPool = Collections.
- synchronizedMap(new WeakHashMap());
+ synchronizedMap(new WeakHashMap<SmallAttributeSet, WeakReference<SmallAttributeSet>>());
s.defaultReadObject();
}
@@ -731,15 +728,15 @@
*/
public static final String DEFAULT_STYLE = "default";
- private static Hashtable freezeKeyMap;
- private static Hashtable thawKeyMap;
+ private static Hashtable<Object, String> freezeKeyMap;
+ private static Hashtable<String, Object> thawKeyMap;
private Style styles;
private transient FontKey fontSearch = new FontKey(null, 0, 0);
- private transient Hashtable fontTable = new Hashtable();
+ private transient Hashtable<FontKey, Font> fontTable = new Hashtable<FontKey, Font>();
- private transient Map attributesPool = Collections.
- synchronizedMap(new WeakHashMap());
+ private transient Map<SmallAttributeSet, WeakReference<SmallAttributeSet>> attributesPool = Collections.
+ synchronizedMap(new WeakHashMap<SmallAttributeSet, WeakReference<SmallAttributeSet>>());
private transient MutableAttributeSet search = new SimpleAttributeSet();
/**
@@ -1176,8 +1173,8 @@
}
}
- private Vector keys = new Vector();
- private Vector data = new Vector();
+ private Vector<Object> keys = new Vector<Object>();
+ private Vector<Object> data = new Vector<Object>();
}
/**
@@ -1344,8 +1341,7 @@
* @since 1.4
*/
public ChangeListener[] getChangeListeners() {
- return (ChangeListener[])listenerList.getListeners(
- ChangeListener.class);
+ return listenerList.getListeners(ChangeListener.class);
}
--- a/jdk/src/share/classes/javax/swing/text/TableView.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/TableView.java Tue Aug 12 17:59:58 2008 -0700
@@ -76,7 +76,7 @@
*/
public TableView(Element elem) {
super(elem, View.Y_AXIS);
- rows = new Vector();
+ rows = new Vector<TableRow>();
gridValid = false;
}
@@ -139,7 +139,7 @@
TableRow getRow(int row) {
if (row < rows.size()) {
- return (TableRow) rows.elementAt(row);
+ return rows.elementAt(row);
}
return null;
}
@@ -227,7 +227,7 @@
for (int i = 0; i < n; i++) {
View v = getView(i);
if (v instanceof TableRow) {
- rows.addElement(v);
+ rows.addElement((TableRow) v);
TableRow rv = (TableRow) v;
rv.clearFilledColumns();
rv.setRow(i);
@@ -368,8 +368,7 @@
long min = 0;
long pref = 0;
long max = 0;
- for (int i = 0; i < columnRequirements.length; i++) {
- SizeRequirements req = columnRequirements[i];
+ for (SizeRequirements req : columnRequirements) {
min += req.minimum;
pref += req.preferred;
max += req.maximum;
@@ -578,7 +577,7 @@
int[] columnSpans;
int[] columnOffsets;
SizeRequirements[] columnRequirements;
- Vector rows;
+ Vector<TableRow> rows;
boolean gridValid;
static final private BitSet EMPTY = new BitSet();
--- a/jdk/src/share/classes/javax/swing/text/TextAction.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/TextAction.java Tue Aug 12 17:59:58 2008 -0700
@@ -103,14 +103,12 @@
* @return the augmented list
*/
public static final Action[] augmentList(Action[] list1, Action[] list2) {
- Hashtable h = new Hashtable();
- for (int i = 0; i < list1.length; i++) {
- Action a = list1[i];
+ Hashtable<String, Action> h = new Hashtable<String, Action>();
+ for (Action a : list1) {
String value = (String)a.getValue(Action.NAME);
h.put((value!=null ? value:""), a);
}
- for (int i = 0; i < list2.length; i++) {
- Action a = list2[i];
+ for (Action a : list2) {
String value = (String)a.getValue(Action.NAME);
h.put((value!=null ? value:""), a);
}
--- a/jdk/src/share/classes/javax/swing/text/TextLayoutStrategy.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/TextLayoutStrategy.java Tue Aug 12 17:59:58 2008 -0700
@@ -103,7 +103,7 @@
* constraints for each row. This is called by a FlowView.layout
* to update the child views in the flow.
*
- * @param v the view to reflow
+ * @param fv the view to reflow
*/
public void layout(FlowView fv) {
super.layout(fv);
@@ -485,9 +485,9 @@
* Returns a map with the attributes defined on the current
* character.
*/
- public Map getAttributes() {
+ public Map<Attribute, Object> getAttributes() {
Object[] ka = keys.toArray();
- Hashtable h = new Hashtable();
+ Hashtable<Attribute, Object> h = new Hashtable<Attribute, Object>();
for (int i = 0; i < ka.length; i++) {
TextAttribute a = (TextAttribute) ka[i];
Object value = getAttribute(a);
@@ -520,16 +520,16 @@
* iterator's text range. The set is empty if no
* attributes are defined.
*/
- public Set getAllAttributeKeys() {
+ public Set<Attribute> getAllAttributeKeys() {
return keys;
}
View v;
- static Set keys;
+ static Set<Attribute> keys;
static {
- keys = new HashSet();
+ keys = new HashSet<Attribute>();
keys.add(TextAttribute.FONT);
keys.add(TextAttribute.RUN_DIRECTION);
}
--- a/jdk/src/share/classes/javax/swing/text/ZoneView.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/ZoneView.java Tue Aug 12 17:59:58 2008 -0700
@@ -79,7 +79,7 @@
int maxZoneSize = 8 * 1024;
int maxZonesLoaded = 3;
- Vector loadedZones;
+ Vector<View> loadedZones;
/**
* Constructs a ZoneView.
@@ -89,7 +89,7 @@
*/
public ZoneView(Element elem, int axis) {
super(elem, axis);
- loadedZones = new Vector();
+ loadedZones = new Vector<View>();
}
/**
@@ -157,7 +157,7 @@
void unloadOldZones() {
while (loadedZones.size() > getMaxZonesLoaded()) {
- View zone = (View) loadedZones.elementAt(0);
+ View zone = loadedZones.elementAt(0);
loadedZones.removeElementAt(0);
unloadZone(zone);
}
@@ -206,7 +206,7 @@
*/
protected View createZone(int p0, int p1) {
Document doc = getDocument();
- View zone = null;
+ View zone;
try {
zone = new Zone(getElement(),
doc.createPosition(p0),
@@ -285,7 +285,7 @@
// divide the old zone into a new set of bins
Element elem = getElement();
Document doc = elem.getDocument();
- Vector zones = new Vector();
+ Vector<View> zones = new Vector<View>();
int offs = offs0;
do {
offs0 = offs;
--- a/jdk/src/share/classes/javax/swing/text/html/AccessibleHTML.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/AccessibleHTML.java Tue Aug 12 17:59:58 2008 -0700
@@ -456,7 +456,7 @@
/**
* Sets the Cursor of this object.
*
- * @param c the new Cursor for the object
+ * @param cursor the new Cursor for the object
* @see #getCursor
*/
public void setCursor(Cursor cursor) {
@@ -1076,7 +1076,7 @@
StyledDocument sdoc = (StyledDocument)model;
return sdoc.getParagraphElement(index);
} else {
- Element para = null;
+ Element para;
for (para = model.getDefaultRootElement(); ! para.isLeaf(); ) {
int pos = para.getElementIndex(index);
para = para.getElement(pos);
@@ -1465,7 +1465,7 @@
// Determine the max row/col count.
int delta = 0;
int maxCols = 0;
- int rows = 0;
+ int rows;
for (int counter = 0; counter < getChildCount(); counter++) {
TableRowElementInfo row = getRow(counter);
int prev = 0;
@@ -1929,7 +1929,7 @@
* Returns a boolean value indicating whether the specified column
* is selected.
*
- * @param r zero-based column of the table
+ * @param c zero-based column of the table
* @return the boolean value true if the specified column is selected.
* Otherwise, false.
*/
@@ -1966,7 +1966,7 @@
public int [] getSelectedAccessibleRows() {
if (validateIfNecessary()) {
int nRows = getAccessibleRowCount();
- Vector vec = new Vector();
+ Vector<Integer> vec = new Vector<Integer>();
for (int i = 0; i < nRows; i++) {
if (isAccessibleRowSelected(i)) {
@@ -1975,7 +1975,7 @@
}
int retval[] = new int[vec.size()];
for (int i = 0; i < retval.length; i++) {
- retval[i] = ((Integer)vec.elementAt(i)).intValue();
+ retval[i] = vec.elementAt(i).intValue();
}
return retval;
}
@@ -1991,7 +1991,7 @@
public int [] getSelectedAccessibleColumns() {
if (validateIfNecessary()) {
int nColumns = getAccessibleRowCount();
- Vector vec = new Vector();
+ Vector<Integer> vec = new Vector<Integer>();
for (int i = 0; i < nColumns; i++) {
if (isAccessibleColumnSelected(i)) {
@@ -2000,7 +2000,7 @@
}
int retval[] = new int[vec.size()];
for (int i = 0; i < retval.length; i++) {
- retval[i] = ((Integer)vec.elementAt(i)).intValue();
+ retval[i] = vec.elementAt(i).intValue();
}
return retval;
}
@@ -2134,15 +2134,16 @@
// Header information is modeled as a Hashtable of
// ArrayLists where each Hashtable entry represents
// a row containing one or more headers.
- private Hashtable headers = new Hashtable();
+ private Hashtable<Integer, ArrayList<TableCellElementInfo>> headers =
+ new Hashtable<Integer, ArrayList<TableCellElementInfo>>();
private int rowCount = 0;
private int columnCount = 0;
public void addHeader(TableCellElementInfo cellInfo, int rowNumber) {
Integer rowInteger = Integer.valueOf(rowNumber);
- ArrayList list = (ArrayList)headers.get(rowInteger);
+ ArrayList<TableCellElementInfo> list = headers.get(rowInteger);
if (list == null) {
- list = new ArrayList();
+ list = new ArrayList<TableCellElementInfo>();
headers.put(rowInteger, list);
}
list.add(cellInfo);
@@ -2201,9 +2202,9 @@
}
private TableCellElementInfo getElementInfoAt(int r, int c) {
- ArrayList list = (ArrayList)headers.get(Integer.valueOf(r));
+ ArrayList<TableCellElementInfo> list = headers.get(Integer.valueOf(r));
if (list != null) {
- return (TableCellElementInfo)list.get(c);
+ return list.get(c);
} else {
return null;
}
@@ -2364,7 +2365,7 @@
* Returns a boolean value indicating whether the specified column
* is selected.
*
- * @param r zero-based column of the table
+ * @param c zero-based column of the table
* @return the boolean value true if the specified column is selected.
* Otherwise, false.
*/
@@ -2585,7 +2586,6 @@
private void getAccessible(ElementInfo elementInfo) {
if (elementInfo instanceof Accessible) {
accessible = (Accessible)elementInfo;
- return;
} else {
for (int i = 0; i < elementInfo.getChildCount(); i++) {
getAccessible(elementInfo.getChild(i));
@@ -2643,7 +2643,7 @@
/**
* The children of this ElementInfo.
*/
- private ArrayList children;
+ private ArrayList<ElementInfo> children;
/**
* The Element this ElementInfo is providing information for.
*/
@@ -2754,11 +2754,11 @@
*/
public ElementInfo getChild(int index) {
if (validateIfNecessary()) {
- ArrayList children = this.children;
+ ArrayList<ElementInfo> children = this.children;
if (children != null && index >= 0 &&
index < children.size()) {
- return (ElementInfo)children.get(index);
+ return children.get(index);
}
}
return null;
@@ -2777,7 +2777,7 @@
*/
protected void addChild(ElementInfo child) {
if (children == null) {
- children = new ArrayList();
+ children = new ArrayList<ElementInfo>();
}
children.add(child);
}
@@ -2927,8 +2927,8 @@
isValid = false;
canBeValid = first;
if (children != null) {
- for (int counter = 0; counter < children.size(); counter++) {
- ((ElementInfo)children.get(counter)).invalidate(false);
+ for (ElementInfo child : children) {
+ child.invalidate(false);
}
children = null;
}
--- a/jdk/src/share/classes/javax/swing/text/html/CSS.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/CSS.java Tue Aug 12 17:59:58 2008 -0700
@@ -468,7 +468,7 @@
public CSS() {
baseFontSize = baseFontSizeIndex + 1;
// setup the css conversion table
- valueConvertor = new Hashtable();
+ valueConvertor = new Hashtable<Object, Object>();
valueConvertor.put(CSS.Attribute.FONT_SIZE, new FontSize());
valueConvertor.put(CSS.Attribute.FONT_FAMILY, new FontFamily());
valueConvertor.put(CSS.Attribute.FONT_WEIGHT, new FontWeight());
@@ -637,7 +637,7 @@
* Maps from a StyleConstants to a CSS Attribute.
*/
Attribute styleConstantsKeyToCSSKey(StyleConstants sc) {
- return (Attribute)styleConstantToCssMap.get(sc);
+ return styleConstantToCssMap.get(sc);
}
/**
@@ -645,7 +645,7 @@
*/
Object styleConstantsValueToCSSValue(StyleConstants sc,
Object styleValue) {
- Object cssKey = styleConstantsKeyToCSSKey(sc);
+ Attribute cssKey = styleConstantsKeyToCSSKey(sc);
if (cssKey != null) {
CssValue conv = (CssValue)valueConvertor.get(cssKey);
return conv.fromStyleConstants(sc, styleValue);
@@ -659,8 +659,7 @@
*/
Object cssValueToStyleConstantsValue(StyleConstants key, Object value) {
if (value instanceof CssValue) {
- return ((CssValue)value).toStyleConstants((StyleConstants)key,
- null);
+ return ((CssValue)value).toStyleConstants(key, null);
}
return null;
}
@@ -784,7 +783,7 @@
* Convert a set of HTML attributes to an equivalent
* set of CSS attributes.
*
- * @param AttributeSet containing the HTML attributes.
+ * @param htmlAttrSet AttributeSet containing the HTML attributes.
* @return AttributeSet containing the corresponding CSS attributes.
* The AttributeSet will be empty if there are no mapping
* CSS attributes.
@@ -841,8 +840,8 @@
return cssAttrSet;
}
- private static final Hashtable attributeMap = new Hashtable();
- private static final Hashtable valueMap = new Hashtable();
+ private static final Hashtable<String, Attribute> attributeMap = new Hashtable<String, Attribute>();
+ private static final Hashtable<String, Value> valueMap = new Hashtable<String, Value>();
/**
* The hashtable and the static initalization block below,
@@ -854,18 +853,18 @@
* Therefore, the value associated with each HTML.Attribute.
* key ends up being an array of CSS.Attribute.* objects.
*/
- private static final Hashtable htmlAttrToCssAttrMap = new Hashtable(20);
+ private static final Hashtable<HTML.Attribute, CSS.Attribute[]> htmlAttrToCssAttrMap = new Hashtable<HTML.Attribute, CSS.Attribute[]>(20);
/**
* The hashtable and static initialization that follows sets
* up a translation from StyleConstants (i.e. the <em>well known</em>
* attributes) to the associated CSS attributes.
*/
- private static final Hashtable styleConstantToCssMap = new Hashtable(17);
+ private static final Hashtable<Object, Attribute> styleConstantToCssMap = new Hashtable<Object, Attribute>(17);
/** Maps from HTML value to a CSS value. Used in internal mapping. */
- private static final Hashtable htmlValueToCssValueMap = new Hashtable(8);
+ private static final Hashtable<String, CSS.Value> htmlValueToCssValueMap = new Hashtable<String, CSS.Value>(8);
/** Maps from CSS value (string) to internal value. */
- private static final Hashtable cssValueToInternalValueMap = new Hashtable(13);
+ private static final Hashtable<String, CSS.Value> cssValueToInternalValueMap = new Hashtable<String, CSS.Value>(13);
static {
// load the attribute map
@@ -995,8 +994,8 @@
// Register all the CSS attribute keys for archival/unarchival
Object[] keys = CSS.Attribute.allAttributes;
try {
- for (int i = 0; i < keys.length; i++) {
- StyleContext.registerStaticAttributeKey(keys[i]);
+ for (Object key : keys) {
+ StyleContext.registerStaticAttributeKey(key);
}
} catch (Throwable e) {
e.printStackTrace();
@@ -1005,8 +1004,8 @@
// Register all the CSS Values for archival/unarchival
keys = CSS.Value.allValues;
try {
- for (int i = 0; i < keys.length; i++) {
- StyleContext.registerStaticAttributeKey(keys[i]);
+ for (Object key : keys) {
+ StyleContext.registerStaticAttributeKey(key);
}
} catch (Throwable e) {
e.printStackTrace();
@@ -1034,7 +1033,7 @@
* doesn't represent a valid attribute key
*/
public static final Attribute getAttribute(String name) {
- return (Attribute) attributeMap.get(name);
+ return attributeMap.get(name);
}
/**
@@ -1050,7 +1049,7 @@
* not mean that it doesn't represent a valid CSS value
*/
static final Value getValue(String name) {
- return (Value) valueMap.get(name);
+ return valueMap.get(name);
}
@@ -1159,7 +1158,7 @@
* to a Color.
*/
static Color stringToColor(String str) {
- Color color = null;
+ Color color;
if (str == null) {
return null;
@@ -1299,7 +1298,7 @@
static String[] parseStrings(String value) {
int current, last;
int length = (value == null) ? 0 : value.length();
- Vector temp = new Vector(4);
+ Vector<String> temp = new Vector<String>(4);
current = 0;
while (current < length) {
@@ -1423,10 +1422,10 @@
if (cssAttrList == null || htmlAttrValue == null) {
return;
}
- for (int i = 0; i < cssAttrList.length; i++) {
- Object o = getCssValue(cssAttrList[i], htmlAttrValue);
+ for (Attribute cssAttr : cssAttrList) {
+ Object o = getCssValue(cssAttr, htmlAttrValue);
if (o != null) {
- cssAttrSet.addAttribute(cssAttrList[i], o);
+ cssAttrSet.addAttribute(cssAttr , o);
}
}
}
@@ -1452,7 +1451,7 @@
* @return CSS.Attribute[]
*/
private CSS.Attribute[] getCssAttribute(HTML.Attribute hAttr) {
- return (CSS.Attribute[])htmlAttrToCssAttrMap.get(hAttr);
+ return htmlAttrToCssAttrMap.get(hAttr);
}
/**
@@ -2599,8 +2598,8 @@
* to an AttributeSet or returned to the developer.
*/
static class LengthUnit implements Serializable {
- static Hashtable lengthMapping = new Hashtable(6);
- static Hashtable w3cLengthMapping = new Hashtable(6);
+ static Hashtable<String, Float> lengthMapping = new Hashtable<String, Float>(6);
+ static Hashtable<String, Float> w3cLengthMapping = new Hashtable<String, Float>(6);
static {
lengthMapping.put("pt", new Float(1f));
// Not sure about 1.3, determined by experiementation.
@@ -2642,7 +2641,7 @@
}
if (length >= 2) {
units = value.substring(length - 2, length);
- Float scale = (Float)lengthMapping.get(units);
+ Float scale = lengthMapping.get(units);
if (scale != null) {
try {
this.value = Float.valueOf(value.substring(0,
@@ -2686,10 +2685,10 @@
}
float getValue(boolean w3cLengthUnits) {
- Hashtable mapping = (w3cLengthUnits) ? w3cLengthMapping : lengthMapping;
+ Hashtable<String, Float> mapping = (w3cLengthUnits) ? w3cLengthMapping : lengthMapping;
float scale = 1;
if (units != null) {
- Float scaleFloat = (Float)mapping.get(units);
+ Float scaleFloat = mapping.get(units);
if (scaleFloat != null) {
scale = scaleFloat.floatValue();
}
@@ -2699,10 +2698,10 @@
}
static float getValue(float value, String units, Boolean w3cLengthUnits) {
- Hashtable mapping = (w3cLengthUnits) ? w3cLengthMapping : lengthMapping;
+ Hashtable<String, Float> mapping = (w3cLengthUnits) ? w3cLengthMapping : lengthMapping;
float scale = 1;
if (units != null) {
- Float scaleFloat = (Float)mapping.get(units);
+ Float scaleFloat = mapping.get(units);
if (scaleFloat != null) {
scale = scaleFloat.floatValue();
}
@@ -3089,7 +3088,7 @@
iter.setIndex(i);
int margin0 = lastMargin;
int margin1 = (int) iter.getLeadingCollapseSpan();
- totalSpacing += Math.max(margin0, margin1);;
+ totalSpacing += Math.max(margin0, margin1);
preferred += (int) iter.getPreferredSpan(0);
minimum += iter.getMinimumSpan(0);
maximum += iter.getMaximumSpan(0);
@@ -3127,7 +3126,7 @@
* of margin collapsing, and the flexibility to adjust the sizes.
*/
long preferred = 0;
- long currentPreferred = 0;
+ long currentPreferred;
int lastMargin = 0;
int totalSpacing = 0;
int n = iter.getCount();
@@ -3199,7 +3198,7 @@
}
}
// make the adjustments
- int totalOffset = (int)iter.getBorderWidth();;
+ int totalOffset = (int)iter.getBorderWidth();
for (int i = 0; i < n; i++) {
iter.setIndex(i);
iter.setOffset( iter.getOffset() + totalOffset);
@@ -3331,7 +3330,7 @@
s.defaultReadObject();
// Reconstruct the hashtable.
int numValues = s.readInt();
- valueConvertor = new Hashtable(Math.max(1, numValues));
+ valueConvertor = new Hashtable<Object, Object>(Math.max(1, numValues));
while (numValues-- > 0) {
Object key = s.readObject();
Object value = s.readObject();
@@ -3372,7 +3371,7 @@
//
/** Maps from CSS key to CssValue. */
- private transient Hashtable valueConvertor;
+ private transient Hashtable<Object, Object> valueConvertor;
/** Size used for relative units. */
private int baseFontSize;
--- a/jdk/src/share/classes/javax/swing/text/html/HTML.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/HTML.java Tue Aug 12 17:59:58 2008 -0700
@@ -133,7 +133,7 @@
*
* @return <code>true</code> if this tag is considered to be a paragraph
* in the internal HTML model. <code>false</code> - otherwise.
- * @see javax.swing.text.html.HTMLDocument#HTMLReader#ParagraphAction
+ * @see HTMLDocument.HTMLReader.ParagraphAction
*/
boolean isParagraph() {
return (
@@ -536,10 +536,10 @@
// that the hashtable grew to was determined, and then that very size
// is used.
//
- private static final Hashtable tagHashtable = new Hashtable(73);
+ private static final Hashtable<String, Tag> tagHashtable = new Hashtable<String, Tag>(73);
/** Maps from StyleConstant key to HTML.Tag. */
- private static final Hashtable scMapping = new Hashtable(8);
+ private static final Hashtable<Object, Tag> scMapping = new Hashtable<Object, Tag>(8);
static {
@@ -598,8 +598,8 @@
*/
public static Tag getTag(String tagName) {
- Object t = tagHashtable.get(tagName);
- return (t == null ? null : (Tag)t);
+ Tag t = tagHashtable.get(tagName);
+ return (t == null ? null : t);
}
/**
@@ -613,7 +613,7 @@
* <code>null</code> if not found
*/
static Tag getTagForStyleConstantsKey(StyleConstants sc) {
- return (Tag)scMapping.get(sc);
+ return scMapping.get(sc);
}
/**
@@ -646,7 +646,7 @@
public static final String NULL_ATTRIBUTE_VALUE = "#DEFAULT";
// size determined similar to size of tagHashtable
- private static final Hashtable attHashtable = new Hashtable(77);
+ private static final Hashtable<String, Attribute> attHashtable = new Hashtable<String, Attribute>(77);
static {
@@ -687,11 +687,11 @@
* @return the <code>Attribute</code> corresponding to <code>attName</code>
*/
public static Attribute getAttributeKey(String attName) {
- Object a = attHashtable.get(attName);
+ Attribute a = attHashtable.get(attName);
if (a == null) {
return null;
}
- return (Attribute)a;
+ return a;
}
}
--- a/jdk/src/share/classes/javax/swing/text/html/HTMLDocument.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/HTMLDocument.java Tue Aug 12 17:59:58 2008 -0700
@@ -745,7 +745,7 @@
*/
private Element findFrame(String frameName) {
ElementIterator it = new ElementIterator(this);
- Element next = null;
+ Element next;
while ((next = it.next()) != null) {
AttributeSet attr = next.getAttributes();
@@ -891,7 +891,7 @@
/**
* Returns the Map associated with the given name.
- * @param the name of the desired <code>Map</code>
+ * @param name the name of the desired <code>Map</code>
* @return the <code>Map</code> or <code>null</code> if it can't
* be found, or if <code>name</code> is <code>null</code>
*/
@@ -1759,7 +1759,7 @@
* Used to store button groups for radio buttons in
* a form.
*/
- private HashMap radioButtonGroupsMap;
+ private HashMap<String, ButtonGroup> radioButtonGroupsMap;
/**
* Document property for the number of tokens to buffer
@@ -1824,7 +1824,7 @@
/**
* I18N property key.
*
- * @see AbstractDocument.I18NProperty
+ * @see AbstractDocument#I18NProperty
*/
private static final String I18NProperty = "i18n";
@@ -1915,7 +1915,7 @@
AttributeSet a = (AttributeSet)
elem.getAttributes().getAttribute(tag);
if (a == null) {
- a = (AttributeSet)elem.getAttributes();
+ a = elem.getAttributes();
}
return a;
}
@@ -2193,7 +2193,7 @@
isStyleCSS = "text/css".equals(getDefaultStyleSheetType());
this.offset = offset;
threshold = HTMLDocument.this.getTokenThreshold();
- tagMap = new Hashtable(57);
+ tagMap = new Hashtable<HTML.Tag, TagAction>(57);
TagAction na = new TagAction();
TagAction ba = new BlockAction();
TagAction pa = new ParagraphAction();
@@ -2435,7 +2435,7 @@
(StyleConstants.NameAttribute) == HTML.Tag.BODY &&
pPath[1].getEndOffset() == length) {
String lastText = getText(length - 1, 1);
- DefaultDocumentEvent event = null;
+ DefaultDocumentEvent event;
Element[] added;
Element[] removed;
int index;
@@ -2496,7 +2496,7 @@
}
private Element[] getPathTo(int offset) {
- Stack elements = new Stack();
+ Stack<Element> elements = new Stack<Element>();
Element e = getDefaultRootElement();
int index;
while (!e.isLeaf()) {
@@ -2610,7 +2610,7 @@
else {
styleAttributes = null;
}
- TagAction action = (TagAction) tagMap.get(t);
+ TagAction action = tagMap.get(t);
if (action != null) {
action.start(t, a);
@@ -2640,7 +2640,7 @@
addSpecialElement(HTML.Tag.COMMENT, sas);
}
- TagAction action = (TagAction)tagMap.get(HTML.Tag.COMMENT);
+ TagAction action = tagMap.get(HTML.Tag.COMMENT);
if (action != null) {
action.start(HTML.Tag.COMMENT, new SimpleAttributeSet());
action.end(HTML.Tag.COMMENT);
@@ -2681,7 +2681,7 @@
inBlock--;
}
}
- TagAction action = (TagAction) tagMap.get(t);
+ TagAction action = tagMap.get(t);
if (action != null) {
action.end(t);
}
@@ -2707,7 +2707,7 @@
styleAttributes = null;
}
- TagAction action = (TagAction) tagMap.get(t);
+ TagAction action = tagMap.get(t);
if (action != null) {
action.start(t, a);
action.end(t);
@@ -2802,7 +2802,7 @@
// might be defined in the FORM.
// for new group new ButtonGroup will be created (fix for 4529702)
// group name is a key in radioButtonGroupsMap
- radioButtonGroupsMap = new HashMap();
+ radioButtonGroupsMap = new HashMap<String, ButtonGroup>();
}
public void end(HTML.Tag t) {
@@ -3015,7 +3015,7 @@
if (rel.equals("stylesheet") ||
rel.equals("alternate stylesheet")) {
if (styles == null) {
- styles = new Vector(3);
+ styles = new Vector<Object>(3);
}
styles.addElement(t);
styles.addElement(a.copyAttributes());
@@ -3055,7 +3055,7 @@
public void start(HTML.Tag t, MutableAttributeSet a) {
if (inHead) {
if (styles == null) {
- styles = new Vector(3);
+ styles = new Vector<Object>(3);
}
styles.addElement(t);
styles.addElement(a.getAttribute(HTML.Attribute.TYPE));
@@ -3280,7 +3280,7 @@
String name = (String) a.getAttribute(HTML.Attribute.NAME);
String value = (String) a.getAttribute(HTML.Attribute.VALUE);
if ((name != null) && (value != null)) {
- ElementSpec objSpec = (ElementSpec) parseBuffer.lastElement();
+ ElementSpec objSpec = parseBuffer.lastElement();
MutableAttributeSet objAttr = (MutableAttributeSet) objSpec.getAttributes();
objAttr.addAttribute(name, value);
}
@@ -3360,7 +3360,7 @@
int size = HTML.getIntegerAttributeValue(attr,
HTML.Attribute.SIZE,
1);
- boolean multiple = ((String)attr.getAttribute(HTML.Attribute.MULTIPLE) != null);
+ boolean multiple = attr.getAttribute(HTML.Attribute.MULTIPLE) != null;
if ((size > 1) || multiple) {
OptionListModel m = new OptionListModel();
if (multiple) {
@@ -3460,9 +3460,9 @@
if (type.equals("radio")) {
String name = (String) attr.getAttribute(HTML.Attribute.NAME);
if ( radioButtonGroupsMap == null ) { //fix for 4772743
- radioButtonGroupsMap = new HashMap();
+ radioButtonGroupsMap = new HashMap<String, ButtonGroup>();
}
- ButtonGroup radioButtonGroup = (ButtonGroup)radioButtonGroupsMap.get(name);
+ ButtonGroup radioButtonGroup = radioButtonGroupsMap.get(name);
if (radioButtonGroup == null) {
radioButtonGroup = new ButtonGroup();
radioButtonGroupsMap.put(name,radioButtonGroup);
@@ -3604,7 +3604,7 @@
// an open/close with no content will be removed, so we
// add a space of content to keep the element being formed.
ElementSpec prev = (parseBuffer.size() > 0) ?
- (ElementSpec) parseBuffer.lastElement() : null;
+ parseBuffer.lastElement() : null;
if (prev != null && prev.getType() == ElementSpec.StartTagType) {
char[] one = new char[1];
one[0] = ' ';
@@ -3737,7 +3737,7 @@
// This attemps to clean it up.
int removeCounter = insertTagDepthDelta;
while (removeCounter < 0 && size >= 0 &&
- ((ElementSpec)parseBuffer.elementAt(size - 1)).
+ parseBuffer.elementAt(size - 1).
getType() == ElementSpec.EndTagType) {
parseBuffer.removeElementAt(--size);
removeCounter++;
@@ -3751,7 +3751,7 @@
// an extra \n in the middle of content.
int index = 0;
if (pushDepth > 0) {
- if (((ElementSpec)parseBuffer.elementAt(0)).getType() ==
+ if (parseBuffer.elementAt(0).getType() ==
ElementSpec.ContentType) {
index++;
}
@@ -3759,19 +3759,19 @@
index += (popDepth + pushDepth);
int cCount = 0;
int cStart = index;
- while (index < size && ((ElementSpec)parseBuffer.elementAt
- (index)).getType() == ElementSpec.ContentType) {
+ while (index < size && parseBuffer.elementAt
+ (index).getType() == ElementSpec.ContentType) {
index++;
cCount++;
}
if (cCount > 1) {
- while (index < size && ((ElementSpec)parseBuffer.elementAt
- (index)).getType() == ElementSpec.EndTagType) {
+ while (index < size && parseBuffer.elementAt
+ (index).getType() == ElementSpec.EndTagType) {
index++;
}
if (index == size) {
- char[] lastText = ((ElementSpec)parseBuffer.elementAt
- (cStart + cCount - 1)).getArray();
+ char[] lastText = parseBuffer.elementAt
+ (cStart + cCount - 1).getArray();
if (lastText.length == 1 && lastText[0] == NEWLINE[0]){
index = cStart + cCount - 1;
while (size > index) {
@@ -3785,8 +3785,7 @@
// Make sure there is in fact a newline
for (int counter = parseBuffer.size() - 1; counter >= 0;
counter--) {
- ElementSpec spec = (ElementSpec)parseBuffer.
- elementAt(counter);
+ ElementSpec spec = parseBuffer.elementAt(counter);
if (spec.getType() == ElementSpec.ContentType) {
if (spec.getArray()[spec.getLength() - 1] != '\n') {
SimpleAttributeSet attrs =new SimpleAttributeSet();
@@ -3817,7 +3816,7 @@
* of stylesheets.
*/
void linkCSSStyleSheet(String href) {
- URL url = null;
+ URL url;
try {
url = new URL(base, href);
} catch (MalformedURLException mfe) {
@@ -4031,7 +4030,7 @@
* indicating the type (may be null), and the elements following
* it until the next HTML.Tag are the rules as Strings.
*/
- Vector styles;
+ Vector<Object> styles;
/** True if inside the head tag. */
boolean inHead = false;
/** Set to true if the style language is text/css. Since this is
@@ -4048,10 +4047,10 @@
*/
Option option;
- protected Vector<ElementSpec> parseBuffer = new Vector(); // Vector<ElementSpec>
+ protected Vector<ElementSpec> parseBuffer = new Vector<ElementSpec>();
protected MutableAttributeSet charAttr = new TaggedAttributeSet();
- Stack charAttrStack = new Stack();
- Hashtable tagMap;
+ Stack<AttributeSet> charAttrStack = new Stack<AttributeSet>();
+ Hashtable<HTML.Tag, TagAction> tagMap;
int inBlock = 0;
/**
--- a/jdk/src/share/classes/javax/swing/text/html/HTMLEditorKit.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/HTMLEditorKit.java Tue Aug 12 17:59:58 2008 -0700
@@ -898,7 +898,7 @@
} catch (MalformedURLException m) {
u = null;
}
- HyperlinkEvent linkEvent = null;
+ HyperlinkEvent linkEvent;
if (!hdoc.isFrameDocument()) {
linkEvent = new HyperlinkEvent(
@@ -1271,11 +1271,11 @@
&& (parentContainer = container.getParent()) != null
&& (parentContainer instanceof javax.swing.JViewport)) {
JViewport viewPort = (JViewport)parentContainer;
- Object cachedObject;
if (cachedViewPort != null) {
- if ((cachedObject = cachedViewPort.get()) != null) {
+ JViewport cachedObject = cachedViewPort.get();
+ if (cachedObject != null) {
if (cachedObject != viewPort) {
- ((JComponent)cachedObject).removeComponentListener(this);
+ cachedObject.removeComponentListener(this);
}
} else {
cachedViewPort = null;
@@ -1283,7 +1283,7 @@
}
if (cachedViewPort == null) {
viewPort.addComponentListener(this);
- cachedViewPort = new WeakReference(viewPort);
+ cachedViewPort = new WeakReference<JViewport>(viewPort);
}
componentVisibleWidth = viewPort.getExtentSize().width;
@@ -1295,9 +1295,9 @@
}
} else {
if (cachedViewPort != null) {
- Object cachedObject;
- if ((cachedObject = cachedViewPort.get()) != null) {
- ((JComponent)cachedObject).removeComponentListener(this);
+ JViewport cachedObject = cachedViewPort.get();
+ if (cachedObject != null) {
+ cachedObject.removeComponentListener(this);
}
cachedViewPort = null;
}
@@ -1351,7 +1351,7 @@
* we need to keep this reference in order to remove BodyBoxView from viewPort listeners.
*
*/
- private Reference cachedViewPort = null;
+ private Reference<JViewport> cachedViewPort = null;
private boolean isListening = false;
private int viewVisibleWidth = Integer.MAX_VALUE;
private int componentVisibleWidth = Integer.MAX_VALUE;
@@ -1928,7 +1928,7 @@
int prevEndOffset = -1;
// highlight the next link or object after the current caret position
- Element nextElement = null;
+ Element nextElement;
while ((nextElement = ei.next()) != null) {
String name = nextElement.getName();
AttributeSet attr = nextElement.getAttributes();
@@ -1969,7 +1969,6 @@
comp.setCaretPosition(prevStartOffset);
moveCaretPosition(comp, kit, prevStartOffset, prevEndOffset);
kit.prevHypertextOffset = prevStartOffset;
- return;
}
}
@@ -2113,7 +2112,7 @@
if (view != null && view instanceof ObjectView) {
Component comp = ((ObjectView)view).getComponent();
if (comp != null && comp instanceof Accessible) {
- AccessibleContext ac = ((Accessible)comp).getAccessibleContext();
+ AccessibleContext ac = comp.getAccessibleContext();
if (ac != null) {
AccessibleAction aa = ac.getAccessibleAction();
if (aa != null) {
@@ -2207,7 +2206,7 @@
// invoke the next link or object action
String urlString = null;
String objString = null;
- Element currentElement = null;
+ Element currentElement;
while ((currentElement = ei.next()) != null) {
String name = currentElement.getName();
AttributeSet attr = currentElement.getAttributes();
--- a/jdk/src/share/classes/javax/swing/text/html/HTMLWriter.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/HTMLWriter.java Tue Aug 12 17:59:58 2008 -0700
@@ -46,7 +46,7 @@
* Stores all elements for which end tags have to
* be emitted.
*/
- private Stack blockElementStack = new Stack();
+ private Stack<Element> blockElementStack = new Stack<Element>();
private boolean inContent = false;
private boolean inPre = false;
/** When inPre is true, this will indicate the end offset of the pre
@@ -62,12 +62,12 @@
* character level attributes. Examples include
* <b>, <i>, <font>, and <a>.
*/
- private Vector tags = new Vector(10);
+ private Vector<HTML.Tag> tags = new Vector<HTML.Tag>(10);
/**
* Values for the tags.
*/
- private Vector tagValues = new Vector(10);
+ private Vector<Object> tagValues = new Vector<Object>(10);
/**
* Used when writing out content.
@@ -77,7 +77,7 @@
/*
* This is used in closeOutUnwantedEmbeddedTags.
*/
- private Vector tagsToRemove = new Vector(10);
+ private Vector<HTML.Tag> tagsToRemove = new Vector<HTML.Tag>(10);
/**
* Set to true after the head has been output.
@@ -133,7 +133,7 @@
public void write() throws IOException, BadLocationException {
ElementIterator it = getElementIterator();
Element current = null;
- Element next = null;
+ Element next;
wroteHead = false;
setCurrentLineLength(0);
@@ -169,7 +169,7 @@
item on top of the stack, is the parent of the
next.
*/
- Element top = (Element)blockElementStack.peek();
+ Element top = blockElementStack.peek();
while (top != next.getParentElement()) {
/*
pop() will return top.
@@ -183,7 +183,7 @@
}
endTag(top);
}
- top = (Element)blockElementStack.peek();
+ top = blockElementStack.peek();
}
} else if (current.getParentElement() == next.getParentElement()) {
/*
@@ -191,7 +191,7 @@
is correct. But, we need to make sure that if current is
on the stack, we pop it off, and put out its end tag.
*/
- Element top = (Element)blockElementStack.peek();
+ Element top = blockElementStack.peek();
if (top == current) {
blockElementStack.pop();
endTag(top);
@@ -219,7 +219,7 @@
endTag(current);
}
while (!blockElementStack.empty()) {
- current = (Element)blockElementStack.pop();
+ current = blockElementStack.pop();
if (!synthesizedElement(current)) {
AttributeSet attrs = current.getAttributes();
if (!matchNameAttribute(attrs, HTML.Tag.PRE) &&
@@ -308,7 +308,7 @@
//
if (nameTag != null && endTag != null &&
(endTag instanceof String) &&
- ((String)endTag).equals("true")) {
+ endTag.equals("true")) {
outputEndTag = true;
}
@@ -769,7 +769,7 @@
int size = tags.size();
// First, find all the tags that need to be removed.
for (int i = size - 1; i >= 0; i--) {
- t = (HTML.Tag)tags.elementAt(i);
+ t = tags.elementAt(i);
tValue = tagValues.elementAt(i);
if ((attr == null) || noMatchForTagInAttributes(attr, t, tValue)) {
firstIndex = i;
@@ -780,7 +780,7 @@
// Then close them out.
boolean removeAll = ((size - firstIndex) == tagsToRemove.size());
for (int i = size - 1; i >= firstIndex; i--) {
- t = (HTML.Tag)tags.elementAt(i);
+ t = tags.elementAt(i);
if (removeAll || tagsToRemove.contains(t)) {
tags.removeElementAt(i);
tagValues.removeElementAt(i);
@@ -794,7 +794,7 @@
// as we closed them out, but they should remain open.
size = tags.size();
for (int i = firstIndex; i < size; i++) {
- t = (HTML.Tag)tags.elementAt(i);
+ t = tags.elementAt(i);
write('<');
write(t.toString());
Object o = tagValues.elementAt(i);
@@ -813,11 +813,8 @@
* false
*/
private boolean isFormElementWithContent(AttributeSet attr) {
- if (matchNameAttribute(attr, HTML.Tag.TEXTAREA) ||
- matchNameAttribute(attr, HTML.Tag.SELECT)) {
- return true;
- }
- return false;
+ return matchNameAttribute(attr, HTML.Tag.TEXTAREA) ||
+ matchNameAttribute(attr, HTML.Tag.SELECT);
}
--- a/jdk/src/share/classes/javax/swing/text/html/Map.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/Map.java Tue Aug 12 17:59:58 2008 -0700
@@ -41,10 +41,10 @@
/** Name of the Map. */
private String name;
/** An array of AttributeSets. */
- private Vector areaAttributes;
+ private Vector<AttributeSet> areaAttributes;
/** An array of RegionContainments, will slowly grow to match the
* length of areaAttributes as needed. */
- private Vector areas;
+ private Vector<RegionContainment> areas;
public Map() {
}
@@ -68,7 +68,7 @@
return;
}
if (areaAttributes == null) {
- areaAttributes = new Vector(2);
+ areaAttributes = new Vector<AttributeSet>(2);
}
areaAttributes.addElement(as.copyAttributes());
}
@@ -81,8 +81,7 @@
int numAreas = (areas != null) ? areas.size() : 0;
for (int counter = areaAttributes.size() - 1; counter >= 0;
counter--) {
- if (((AttributeSet)areaAttributes.elementAt(counter)).
- isEqual(as)){
+ if (areaAttributes.elementAt(counter).isEqual(as)){
areaAttributes.removeElementAt(counter);
if (counter < numAreas) {
areas.removeElementAt(counter);
@@ -121,17 +120,16 @@
int numAreas = (areas != null) ? areas.size() : 0;
if (areas == null) {
- areas = new Vector(numAttributes);
+ areas = new Vector<RegionContainment>(numAttributes);
}
for (int counter = 0; counter < numAttributes; counter++) {
if (counter >= numAreas) {
areas.addElement(createRegionContainment
- ((AttributeSet)areaAttributes.elementAt(counter)));
+ (areaAttributes.elementAt(counter)));
}
- RegionContainment rc = (RegionContainment)areas.
- elementAt(counter);
+ RegionContainment rc = areas.elementAt(counter);
if (rc != null && rc.contains(x, y, width, height)) {
- return (AttributeSet)areaAttributes.elementAt(counter);
+ return areaAttributes.elementAt(counter);
}
}
}
--- a/jdk/src/share/classes/javax/swing/text/html/MinimalHTMLWriter.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/MinimalHTMLWriter.java Tue Aug 12 17:59:58 2008 -0700
@@ -97,7 +97,7 @@
* Maps from style name as held by the Document, to the archived
* style name (style name written out). These may differ.
*/
- private Hashtable styleNameMapping;
+ private Hashtable<String, String> styleNameMapping;
/**
* Creates a new MinimalHTMLWriter.
@@ -134,7 +134,7 @@
*
*/
public void write() throws IOException, BadLocationException {
- styleNameMapping = new Hashtable();
+ styleNameMapping = new Hashtable<String, String>();
writeStartTag("<html>");
writeHeader();
writeBody();
@@ -296,7 +296,7 @@
*/
it.current();
- Element next = null;
+ Element next;
writeStartTag("<body>");
@@ -715,7 +715,7 @@
if (styleNameMapping == null) {
return style;
}
- String retValue = (String)styleNameMapping.get(style);
+ String retValue = styleNameMapping.get(style);
return (retValue == null) ? style : retValue;
}
--- a/jdk/src/share/classes/javax/swing/text/html/OptionListModel.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/OptionListModel.java Tue Aug 12 17:59:58 2008 -0700
@@ -108,8 +108,7 @@
* @since 1.4
*/
public ListSelectionListener[] getListSelectionListeners() {
- return (ListSelectionListener[])listenerList.getListeners(
- ListSelectionListener.class);
+ return listenerList.getListeners(ListSelectionListener.class);
}
/**
@@ -131,7 +130,7 @@
/**
* @param firstIndex The first index in the interval.
- * @param index1 The last index in the interval.
+ * @param lastIndex The last index in the interval.
* @param isAdjusting True if this is the final change in a series of them.
* @see EventListenerList
*/
@@ -528,8 +527,8 @@
anchorIndex = leadIndex;
}
- int oldMin = Math.min(this.anchorIndex, this.leadIndex);;
- int oldMax = Math.max(this.anchorIndex, this.leadIndex);;
+ int oldMin = Math.min(this.anchorIndex, this.leadIndex);
+ int oldMax = Math.max(this.anchorIndex, this.leadIndex);
int newMin = Math.min(anchorIndex, leadIndex);
int newMax = Math.max(anchorIndex, leadIndex);
if (value.get(this.anchorIndex)) {
--- a/jdk/src/share/classes/javax/swing/text/html/StyleSheet.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/StyleSheet.java Tue Aug 12 17:59:58 2008 -0700
@@ -164,7 +164,7 @@
public StyleSheet() {
super();
selectorMapping = new SelectorMapping(0);
- resolvedStyles = new Hashtable();
+ resolvedStyles = new Hashtable<String, ResolvedStyle>();
if (css == null) {
css = new CSS();
}
@@ -190,7 +190,7 @@
try {
// Build an array of all the parent elements.
- Vector searchContext = sb.getVector();
+ Vector<Element> searchContext = sb.getVector();
for (Element p = e; p != null; p = p.getParentElement()) {
searchContext.addElement(p);
@@ -205,7 +205,7 @@
// >= 1 as the HTML.Tag for the 0th element is passed in.
for (int counter = n - 1; counter >= 1; counter--) {
- e = (Element)searchContext.elementAt(counter);
+ e = searchContext.elementAt(counter);
attr = e.getAttributes();
name = attr.getAttribute(StyleConstants.NameAttribute);
eName = name.toString();
@@ -225,7 +225,7 @@
cacheLookup.append(' ');
}
cacheLookup.append(t.toString());
- e = (Element)searchContext.elementAt(0);
+ e = searchContext.elementAt(0);
attr = e.getAttributes();
if (e.isLeaf()) {
// For leafs, we use the second tier attributes.
@@ -368,10 +368,9 @@
if (rule != null) {
mapping.setStyle(null);
if (resolvedStyles.size() > 0) {
- Enumeration values = resolvedStyles.elements();
+ Enumeration<ResolvedStyle> values = resolvedStyles.elements();
while (values.hasMoreElements()) {
- ResolvedStyle style = (ResolvedStyle)values.
- nextElement();
+ ResolvedStyle style = values.nextElement();
style.removeStyle(rule);
}
}
@@ -392,7 +391,7 @@
public void addStyleSheet(StyleSheet ss) {
synchronized(this) {
if (linkedStyleSheets == null) {
- linkedStyleSheets = new Vector();
+ linkedStyleSheets = new Vector<StyleSheet>();
}
if (!linkedStyleSheets.contains(ss)) {
int index = 0;
@@ -828,7 +827,7 @@
/**
* Creates a new attribute set based on a supplied set of attributes.
*
- * @param source the set of attributes
+ * @param attrs the set of attributes
*/
public SmallConversionSet(AttributeSet attrs) {
super(attrs);
@@ -1045,9 +1044,9 @@
*/
private synchronized void linkStyleSheetAt(StyleSheet ss, int index) {
if (resolvedStyles.size() > 0) {
- Enumeration values = resolvedStyles.elements();
+ Enumeration<ResolvedStyle> values = resolvedStyles.elements();
while (values.hasMoreElements()) {
- ResolvedStyle rule = (ResolvedStyle)values.nextElement();
+ ResolvedStyle rule = values.nextElement();
rule.insertExtendedStyleAt(ss.getRule(rule.getName()),
index);
}
@@ -1061,9 +1060,9 @@
*/
private synchronized void unlinkStyleSheet(StyleSheet ss, int index) {
if (resolvedStyles.size() > 0) {
- Enumeration values = resolvedStyles.elements();
+ Enumeration<ResolvedStyle> values = resolvedStyles.elements();
while (values.hasMoreElements()) {
- ResolvedStyle rule = (ResolvedStyle)values.nextElement();
+ ResolvedStyle rule = values.nextElement();
rule.removeExtendedStyleAt(index);
}
}
@@ -1076,7 +1075,7 @@
String[] getSimpleSelectors(String selector) {
selector = cleanSelectorString(selector);
SearchBuffer sb = SearchBuffer.obtainSearchBuffer();
- Vector selectors = sb.getVector();
+ Vector<String> selectors = sb.getVector();
int lastIndex = 0;
int length = selector.length();
while (lastIndex != -1) {
@@ -1256,7 +1255,7 @@
private synchronized Style getResolvedStyle(String selector,
Vector elements,
HTML.Tag t) {
- Style retStyle = (Style)resolvedStyles.get(selector);
+ Style retStyle = resolvedStyles.get(selector);
if (retStyle == null) {
retStyle = createResolvedStyle(selector, elements, t);
}
@@ -1268,7 +1267,7 @@
* create the resolved style, if necessary.
*/
private synchronized Style getResolvedStyle(String selector) {
- Style retStyle = (Style)resolvedStyles.get(selector);
+ Style retStyle = resolvedStyles.get(selector);
if (retStyle == null) {
retStyle = createResolvedStyle(selector);
}
@@ -1280,15 +1279,14 @@
* such that <code>elements</code> will remain ordered by
* specificity.
*/
- private void addSortedStyle(SelectorMapping mapping, Vector elements) {
+ private void addSortedStyle(SelectorMapping mapping, Vector<SelectorMapping> elements) {
int size = elements.size();
if (size > 0) {
int specificity = mapping.getSpecificity();
for (int counter = 0; counter < size; counter++) {
- if (specificity >= ((SelectorMapping)elements.elementAt
- (counter)).getSpecificity()) {
+ if (specificity >= elements.elementAt(counter).getSpecificity()) {
elements.insertElementAt(mapping, counter);
return;
}
@@ -1303,10 +1301,10 @@
* any child mappings for any of the Elements in <code>elements</code>.
*/
private synchronized void getStyles(SelectorMapping parentMapping,
- Vector styles,
+ Vector<SelectorMapping> styles,
String[] tags, String[] ids, String[] classes,
int index, int numElements,
- Hashtable alreadyChecked) {
+ Hashtable<SelectorMapping, SelectorMapping> alreadyChecked) {
// Avoid desending the same mapping twice.
if (alreadyChecked.contains(parentMapping)) {
return;
@@ -1367,8 +1365,8 @@
String[] tags,
String[] ids, String[] classes) {
SearchBuffer sb = SearchBuffer.obtainSearchBuffer();
- Vector tempVector = sb.getVector();
- Hashtable tempHashtable = sb.getHashtable();
+ Vector<SelectorMapping> tempVector = sb.getVector();
+ Hashtable<SelectorMapping, SelectorMapping> tempHashtable = sb.getHashtable();
// Determine all the Styles that are appropriate, placing them
// in tempVector
try {
@@ -1418,13 +1416,11 @@
int numStyles = tempVector.size();
AttributeSet[] attrs = new AttributeSet[numStyles + numLinkedSS];
for (int counter = 0; counter < numStyles; counter++) {
- attrs[counter] = ((SelectorMapping)tempVector.
- elementAt(counter)).getStyle();
+ attrs[counter] = tempVector.elementAt(counter).getStyle();
}
// Get the AttributeSet from linked style sheets.
for (int counter = 0; counter < numLinkedSS; counter++) {
- AttributeSet attr = ((StyleSheet)linkedStyleSheets.
- elementAt(counter)).getRule(selector);
+ AttributeSet attr = linkedStyleSheets.elementAt(counter).getRule(selector);
if (attr == null) {
attrs[counter + numStyles] = SimpleAttributeSet.EMPTY;
}
@@ -1514,11 +1510,11 @@
private Style createResolvedStyle(String selector) {
SearchBuffer sb = SearchBuffer.obtainSearchBuffer();
// Will contain the tags, ids, and classes, in that order.
- Vector elements = sb.getVector();
+ Vector<String> elements = sb.getVector();
try {
boolean done;
int dotIndex = 0;
- int spaceIndex = 0;
+ int spaceIndex;
int poundIndex = 0;
int lastIndex = 0;
int length = selector.length();
@@ -1640,9 +1636,9 @@
String[] classes = new String[numTags];
for (int index = 0, eIndex = total - 3; index < numTags;
index++, eIndex -= 3) {
- tags[index] = (String)elements.elementAt(eIndex);
- classes[index] = (String)elements.elementAt(eIndex + 1);
- ids[index] = (String)elements.elementAt(eIndex + 2);
+ tags[index] = elements.elementAt(eIndex);
+ classes[index] = elements.elementAt(eIndex + 1);
+ ids[index] = elements.elementAt(eIndex + 2);
}
return createResolvedStyle(selector, tags, ids, classes);
}
@@ -1661,9 +1657,9 @@
Style newStyle,
int specificity) {
if (resolvedStyles.size() > 0) {
- Enumeration values = resolvedStyles.elements();
+ Enumeration<ResolvedStyle> values = resolvedStyles.elements();
while (values.hasMoreElements()) {
- ResolvedStyle style = (ResolvedStyle)values.nextElement();
+ ResolvedStyle style = values.nextElement();
if (style.matches(selectorName)) {
style.insertStyle(newStyle, specificity);
}
@@ -1682,7 +1678,7 @@
private static class SearchBuffer {
/** A stack containing instances of SearchBuffer. Used in getting
* rules. */
- static Stack searchBuffers = new Stack();
+ static Stack<SearchBuffer> searchBuffers = new Stack<SearchBuffer>();
// A set of temporary variables that can be used in whatever way.
Vector vector = null;
StringBuffer stringBuffer = null;
@@ -1696,7 +1692,7 @@
SearchBuffer sb;
try {
if(!searchBuffers.empty()) {
- sb = (SearchBuffer)searchBuffers.pop();
+ sb = searchBuffers.pop();
} else {
sb = new SearchBuffer();
}
@@ -1922,7 +1918,7 @@
static boolean isLeftToRight(View v) {
boolean ret = true;
if (isOrientationAware(v)) {
- Container container = null;
+ Container container;
if (v != null && (container = v.getContainer()) != null) {
ret = container.getComponentOrientation().isLeftToRight();
}
@@ -1938,8 +1934,8 @@
*/
static boolean isOrientationAware(View v) {
boolean ret = false;
- AttributeSet attr = null;
- Object obj = null;
+ AttributeSet attr;
+ Object obj;
if (v != null
&& (attr = v.getElement().getAttributes()) != null
&& (obj = attr.getAttribute(StyleConstants.NameAttribute)) instanceof HTML.Tag
@@ -1953,7 +1949,7 @@
return ret;
}
- static enum HorizontalMargin { LEFT, RIGHT };
+ static enum HorizontalMargin { LEFT, RIGHT }
/**
* for <dir>, <menu>, <ul> etc.
@@ -2362,7 +2358,7 @@
* @param itemNum number to format
*/
String formatAlphaNumerals(int itemNum) {
- String result = "";
+ String result;
if (itemNum > 26) {
result = formatAlphaNumerals(itemNum / 26) +
@@ -2411,7 +2407,7 @@
* Converts the item number into a roman numeral
*
* @param level position
- * @param num digit to format
+ * @param digit digit to format
*/
String formatRomanDigit(int level, int digit) {
String result = "";
@@ -2625,7 +2621,7 @@
// implementation.
Document doc = v.getDocument();
SearchBuffer sb = SearchBuffer.obtainSearchBuffer();
- Vector muxList = sb.getVector();
+ Vector<AttributeSet> muxList = sb.getVector();
try {
if (doc instanceof HTMLDocument) {
StyleSheet styles = StyleSheet.this;
@@ -2641,8 +2637,8 @@
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
if (key instanceof HTML.Tag) {
- if ((HTML.Tag)key == HTML.Tag.A) {
- Object o = a.getAttribute((HTML.Tag)key);
+ if (key == HTML.Tag.A) {
+ Object o = a.getAttribute(key);
/**
In the case of an A tag, the css rules
apply only for tags that have their
@@ -3059,10 +3055,10 @@
SelectorMapping retValue = null;
if (children != null) {
- retValue = (SelectorMapping)children.get(selector);
+ retValue = children.get(selector);
}
else if (create) {
- children = new HashMap(7);
+ children = new HashMap<String, SelectorMapping>(7);
}
if (retValue == null && create) {
int specificity = getChildSpecificity(selector);
@@ -3121,7 +3117,7 @@
* Any sub selectors. Key will be String, and value will be
* another SelectorMapping.
*/
- private HashMap children;
+ private HashMap<String, SelectorMapping> children;
}
@@ -3138,11 +3134,11 @@
/** Maps from selector (as a string) to Style that includes all
* relevant styles. */
- private Hashtable resolvedStyles;
+ private Hashtable<String, ResolvedStyle> resolvedStyles;
/** Vector of StyleSheets that the rules are to reference.
*/
- private Vector linkedStyleSheets;
+ private Vector<StyleSheet> linkedStyleSheets;
/** Where the style sheet was found. Used for relative imports. */
private URL base;
@@ -3279,7 +3275,7 @@
public void endRule() {
int n = selectors.size();
for (int i = 0; i < n; i++) {
- String[] selector = (String[]) selectors.elementAt(i);
+ String[] selector = selectors.elementAt(i);
if (selector.length > 0) {
StyleSheet.this.addRule(selector, declaration, isLink);
}
@@ -3296,8 +3292,8 @@
}
- Vector selectors = new Vector();
- Vector selectorTokens = new Vector();
+ Vector<String[]> selectors = new Vector<String[]>();
+ Vector<String> selectorTokens = new Vector<String>();
/** Name of the current property. */
String propertyName;
MutableAttributeSet declaration = new SimpleAttributeSet();
--- a/jdk/src/share/classes/javax/swing/text/html/TableView.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/TableView.java Tue Aug 12 17:59:58 2008 -0700
@@ -48,7 +48,7 @@
*/
public TableView(Element elem) {
super(elem, View.Y_AXIS);
- rows = new Vector();
+ rows = new Vector<RowView>();
gridValid = false;
captionIndex = -1;
totalColumnRequirements = new SizeRequirements();
@@ -127,14 +127,14 @@
RowView getRow(int row) {
if (row < rows.size()) {
- return (RowView) rows.elementAt(row);
+ return rows.elementAt(row);
}
return null;
}
protected View getViewAtPoint(int x, int y, Rectangle alloc) {
int n = getViewCount();
- View v = null;
+ View v;
Rectangle allocation = new Rectangle();
for (int i = 0; i < n; i++) {
allocation.setBounds(alloc);
@@ -273,7 +273,7 @@
for (int i = 0; i < n; i++) {
View v = getView(i);
if (v instanceof RowView) {
- rows.addElement(v);
+ rows.addElement((RowView) v);
RowView rv = (RowView) v;
rv.clearFilledColumns();
rv.rowIndex = rows.size() - 1;
@@ -990,7 +990,7 @@
RowIterator rowIterator = new RowIterator();
ColumnIterator colIterator = new ColumnIterator();
- Vector rows;
+ Vector<RowView> rows;
// whether to display comments inside table or not.
boolean skipComments = false;
--- a/jdk/src/share/classes/javax/swing/text/html/parser/AttributeList.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/parser/AttributeList.java Tue Aug 12 17:59:58 2008 -0700
@@ -129,7 +129,7 @@
/**
* Create a hashtable of attribute types.
*/
- static Hashtable attributeTypes = new Hashtable();
+ static Hashtable<Object, Object> attributeTypes = new Hashtable<Object, Object>();
static void defineAttributeType(String nm, int val) {
Integer num = Integer.valueOf(val);
--- a/jdk/src/share/classes/javax/swing/text/html/parser/DTD.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/parser/DTD.java Tue Aug 12 17:59:58 2008 -0700
@@ -104,7 +104,7 @@
* <code>name</code> <code>String</code>
*/
public Entity getEntity(String name) {
- return (Entity)entityHash.get(name);
+ return entityHash.get(name);
}
/**
@@ -113,7 +113,7 @@
* <code>ch</code> character
*/
public Entity getEntity(int ch) {
- return (Entity)entityHash.get(Integer.valueOf(ch));
+ return entityHash.get(Integer.valueOf(ch));
}
/**
@@ -137,7 +137,7 @@
* <code>name</code>, which may be newly created
*/
public Element getElement(String name) {
- Element e = (Element)elementHash.get(name);
+ Element e = elementHash.get(name);
if (e == null) {
e = new Element(name, elements.size());
elements.addElement(e);
@@ -154,7 +154,7 @@
* <code>index</code>
*/
public Element getElement(int index) {
- return (Element)elements.elementAt(index);
+ return elements.elementAt(index);
}
/**
@@ -170,7 +170,7 @@
* if not found
*/
public Entity defineEntity(String name, int type, char data[]) {
- Entity ent = (Entity)entityHash.get(name);
+ Entity ent = entityHash.get(name);
if (ent == null) {
ent = new Entity(name, type, data);
entityHash.put(name, ent);
@@ -259,8 +259,7 @@
BitSet excl = null;
if (exclusions != null && exclusions.length > 0) {
excl = new BitSet();
- for (int i = 0; i < exclusions.length; i++) {
- String str = exclusions[i];
+ for (String str : exclusions) {
if (str.length() > 0) {
excl.set(getElement(str).getIndex());
}
@@ -269,8 +268,7 @@
BitSet incl = null;
if (inclusions != null && inclusions.length > 0) {
incl = new BitSet();
- for (int i = 0; i < inclusions.length; i++) {
- String str = inclusions[i];
+ for (String str : inclusions) {
if (str.length() > 0) {
incl.set(getElement(str).getIndex());
}
@@ -285,9 +283,9 @@
* @return the new <code>AttributeList</code>
*/
protected AttributeList defAttributeList(String name, int type, int modifier, String value, String values, AttributeList atts) {
- Vector vals = null;
+ Vector<String> vals = null;
if (values != null) {
- vals = new Vector();
+ vals = new Vector<String>();
for (StringTokenizer s = new StringTokenizer(values, "|") ; s.hasMoreTokens() ;) {
String str = s.nextToken();
if (str.length() > 0) {
@@ -318,7 +316,7 @@
/**
* The hashtable of DTDs.
*/
- static Hashtable dtdHash = new Hashtable();
+ static Hashtable<String, DTD> dtdHash = new Hashtable<String, DTD>();
public static void putDTDHash(String name, DTD dtd) {
dtdHash.put(name, dtd);
@@ -334,7 +332,7 @@
*/
public static DTD getDTD(String name) throws IOException {
name = name.toLowerCase();
- DTD dtd = (DTD)dtdHash.get(name);
+ DTD dtd = dtdHash.get(name);
if (dtd == null)
dtd = new DTD(name);
@@ -432,10 +430,10 @@
int modifier = in.readByte();
short valueId = in.readShort();
String value = (valueId == -1) ? null : names[valueId];
- Vector values = null;
+ Vector<String> values = null;
short numValues = in.readShort();
if (numValues > 0) {
- values = new Vector(numValues);
+ values = new Vector<String>(numValues);
for (int i = 0; i < numValues; i++) {
values.addElement(names[in.readShort()]);
}
--- a/jdk/src/share/classes/javax/swing/text/html/parser/Element.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/parser/Element.java Tue Aug 12 17:59:58 2008 -0700
@@ -159,7 +159,7 @@
}
- static Hashtable contentTypes = new Hashtable();
+ static Hashtable<String, Integer> contentTypes = new Hashtable<String, Integer>();
static {
contentTypes.put("CDATA", Integer.valueOf(CDATA));
@@ -169,7 +169,7 @@
}
public static int name2type(String nm) {
- Integer val = (Integer)contentTypes.get(nm);
+ Integer val = contentTypes.get(nm);
return (val != null) ? val.intValue() : 0;
}
}
--- a/jdk/src/share/classes/javax/swing/text/html/parser/Entity.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/parser/Entity.java Tue Aug 12 17:59:58 2008 -0700
@@ -107,7 +107,7 @@
}
- static Hashtable entityTypes = new Hashtable();
+ static Hashtable<String, Integer> entityTypes = new Hashtable<String, Integer>();
static {
entityTypes.put("PUBLIC", Integer.valueOf(PUBLIC));
@@ -133,7 +133,7 @@
* to "CDATA", if none exists
*/
public static int name2type(String nm) {
- Integer i = (Integer)entityTypes.get(nm);
+ Integer i = entityTypes.get(nm);
return (i == null) ? CDATA : i.intValue();
}
}
--- a/jdk/src/share/classes/javax/swing/text/html/parser/Parser.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/parser/Parser.java Tue Aug 12 17:59:58 2008 -0700
@@ -649,12 +649,10 @@
if (!strict) {
ContentModel content = stack.contentModel();
- Vector elemVec = new Vector();
+ Vector<Element> elemVec = new Vector<Element>();
if (content != null) {
content.getElements(elemVec);
- for (Enumeration v = elemVec.elements(); v.hasMoreElements();) {
- Element e = (Element)v.nextElement();
-
+ for (Element e : elemVec) {
// Ensure that this element has not been included as
// part of the exclusions in the DTD.
//
@@ -1349,9 +1347,9 @@
continue;
}
- AttributeList att = null;
- String attname = null;
- String attvalue = null;
+ AttributeList att;
+ String attname;
+ String attvalue;
if (parseIdentifier(true)) {
attname = getString(0);
@@ -1549,7 +1547,7 @@
* Parse a start or end tag.
*/
void parseTag() throws IOException {
- Element elem = null;
+ Element elem;
boolean net = false;
boolean warned = false;
boolean unknown = false;
--- a/jdk/src/share/classes/javax/swing/text/html/parser/TagStack.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/parser/TagStack.java Tue Aug 12 17:59:58 2008 -0700
@@ -124,22 +124,6 @@
return (exclusions != null) && exclusions.get(elem.getIndex());
}
- /**
- * Update the Vector elemVec with all the elements that
- * are part of the inclusions listed in DTD for the element
- * currently on the TagStack.
- */
- boolean included(Vector elemVec, DTD dtd) {
-
- for (int i = 0 ; i < inclusions.size(); i++) {
- if (inclusions.get(i)) {
- elemVec.addElement(dtd.getElement(i));
- System.out.println("Element add thru' inclusions: " + dtd.getElement(i).getName());
- }
- }
- return (!elemVec.isEmpty());
- }
-
/**
* Advance the state by reducing the given element.
--- a/jdk/src/share/classes/javax/swing/text/rtf/MockAttributeSet.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/rtf/MockAttributeSet.java Tue Aug 12 17:59:58 2008 -0700
@@ -35,7 +35,7 @@
class MockAttributeSet
implements AttributeSet, MutableAttributeSet
{
- public Dictionary backing;
+ public Dictionary<Object, Object> backing;
public boolean isEmpty()
{
--- a/jdk/src/share/classes/javax/swing/text/rtf/RTFAttributes.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/rtf/RTFAttributes.java Tue Aug 12 17:59:58 2008 -0700
@@ -36,7 +36,7 @@
static RTFAttribute attributes[];
static {
- Vector a = new Vector();
+ Vector<RTFAttribute> a = new Vector<RTFAttribute>();
int CHR = RTFAttribute.D_CHARACTER;
int PGF = RTFAttribute.D_PARAGRAPH;
int SEC = RTFAttribute.D_SECTION;
@@ -131,14 +131,13 @@
attributes = attrs;
}
- static Dictionary attributesByKeyword()
+ static Dictionary<String, RTFAttribute> attributesByKeyword()
{
- Dictionary d = new Hashtable(attributes.length);
- int i, m;
+ Dictionary<String, RTFAttribute> d = new Hashtable<String, RTFAttribute>(attributes.length);
- m = attributes.length;
- for(i = 0; i < m; i++)
- d.put(attributes[i].rtfName(), attributes[i]);
+ for (RTFAttribute attribute : attributes) {
+ d.put(attribute.rtfName(), attribute);
+ }
return d;
}
--- a/jdk/src/share/classes/javax/swing/text/rtf/RTFGenerator.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/rtf/RTFGenerator.java Tue Aug 12 17:59:58 2008 -0700
@@ -52,11 +52,11 @@
{
/* These dictionaries map Colors, font names, or Style objects
to Integers */
- Dictionary colorTable;
+ Dictionary<Object, Integer> colorTable;
int colorCount;
- Dictionary fontTable;
+ Dictionary<String, Integer> fontTable;
int fontCount;
- Dictionary styleTable;
+ Dictionary<AttributeSet, Integer> styleTable;
int styleCount;
/* where all the text is going */
@@ -90,7 +90,7 @@
would require allocating an object for every character
written (slow!). */
static class CharacterKeywordPair
- { public char character; public String keyword; };
+ { public char character; public String keyword; }
static protected CharacterKeywordPair[] textKeywords;
static {
@@ -98,7 +98,7 @@
Dictionary textKeywordDictionary = RTFReader.textKeywords;
Enumeration keys = textKeywordDictionary.keys();
- Vector tempPairs = new Vector();
+ Vector<CharacterKeywordPair> tempPairs = new Vector<CharacterKeywordPair>();
while(keys.hasMoreElements()) {
CharacterKeywordPair pair = new CharacterKeywordPair();
pair.keyword = (String)keys.nextElement();
@@ -133,14 +133,14 @@
public RTFGenerator(OutputStream to)
{
- colorTable = new Hashtable();
+ colorTable = new Hashtable<Object, Integer>();
colorTable.put(defaultRTFColor, Integer.valueOf(0));
colorCount = 1;
- fontTable = new Hashtable();
+ fontTable = new Hashtable<String, Integer>();
fontCount = 0;
- styleTable = new Hashtable();
+ styleTable = new Hashtable<AttributeSet, Integer>();
/* TODO: put default style in style table */
styleCount = 0;
@@ -197,7 +197,7 @@
private void tallyStyles(AttributeSet a) {
while (a != null) {
if (a instanceof Style) {
- Integer aNum = (Integer)styleTable.get(a);
+ Integer aNum = styleTable.get(a);
if (aNum == null) {
styleCount = styleCount + 1;
aNum = new Integer(styleCount);
@@ -225,7 +225,7 @@
{
while(a != null) {
if (a instanceof Style) {
- Integer aNum = (Integer)styleTable.get(a);
+ Integer aNum = styleTable.get(a);
if (aNum != null) {
if (domain == null ||
domain.equals(a.getAttribute(Constants.StyleType)))
@@ -319,11 +319,11 @@
/* write font table */
String[] sortedFontTable = new String[fontCount];
- Enumeration fonts = fontTable.keys();
+ Enumeration<String> fonts = fontTable.keys();
String font;
while(fonts.hasMoreElements()) {
- font = (String)fonts.nextElement();
- Integer num = (Integer)(fontTable.get(font));
+ font = fonts.nextElement();
+ Integer num = fontTable.get(font);
sortedFontTable[num.intValue()] = font;
}
writeBegingroup();
@@ -344,7 +344,7 @@
Color color;
while(colors.hasMoreElements()) {
color = (Color)colors.nextElement();
- Integer num = (Integer)(colorTable.get(color));
+ Integer num = colorTable.get(color);
sortedColorTable[num.intValue()] = color;
}
writeBegingroup();
@@ -366,10 +366,10 @@
if (styleCount > 1) {
writeBegingroup();
writeControlWord("stylesheet");
- Enumeration styles = styleTable.keys();
+ Enumeration<AttributeSet> styles = styleTable.keys();
while(styles.hasMoreElements()) {
Style style = (Style)styles.nextElement();
- int styleNumber = ((Integer)styleTable.get(style)).intValue();
+ int styleNumber = styleTable.get(style).intValue();
writeBegingroup();
String styleType = (String)style.getAttribute(Constants.StyleType);
if (styleType == null)
@@ -398,7 +398,7 @@
basis = style.getResolveParent();
if (basis != null && basis instanceof Style) {
- Integer basedOn = (Integer)styleTable.get(basis);
+ Integer basedOn = styleTable.get(basis);
if (basedOn != null) {
writeControlWord("sbasedon", basedOn.intValue());
}
@@ -406,7 +406,7 @@
Style nextStyle = (Style)style.getAttribute(Constants.StyleNext);
if (nextStyle != null) {
- Integer nextNum = (Integer)styleTable.get(nextStyle);
+ Integer nextNum = styleTable.get(nextStyle);
if (nextNum != null) {
writeControlWord("snext", nextNum.intValue());
}
@@ -725,7 +725,7 @@
if ((parm = attrDiff(current, newAttributes,
StyleConstants.FontFamily, null)) != null) {
- Number fontNum = (Number)fontTable.get(parm);
+ Integer fontNum = fontTable.get(parm);
writeControlWord("f", fontNum.intValue());
}
@@ -746,7 +746,7 @@
if (parm == MagicToken)
colorNum = 0;
else
- colorNum = ((Number)colorTable.get(parm)).intValue();
+ colorNum = colorTable.get(parm).intValue();
writeControlWord("cb", colorNum);
}
@@ -756,7 +756,7 @@
if (parm == MagicToken)
colorNum = 0;
else
- colorNum = ((Number)colorTable.get(parm)).intValue();
+ colorNum = colorTable.get(parm).intValue();
writeControlWord("cf", colorNum);
}
}
--- a/jdk/src/share/classes/javax/swing/text/rtf/RTFParser.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/rtf/RTFParser.java Tue Aug 12 17:59:58 2008 -0700
@@ -92,7 +92,7 @@
// table of non-text characters in rtf
static final boolean rtfSpecialsTable[];
static {
- rtfSpecialsTable = (boolean[])noSpecialsTable.clone();
+ rtfSpecialsTable = noSpecialsTable.clone();
rtfSpecialsTable['\n'] = true;
rtfSpecialsTable['\r'] = true;
rtfSpecialsTable['{'] = true;
--- a/jdk/src/share/classes/javax/swing/text/rtf/RTFReader.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/text/rtf/RTFReader.java Tue Aug 12 17:59:58 2008 -0700
@@ -54,7 +54,7 @@
/** Miscellaneous information about the parser's state. This
* dictionary is saved and restored when an RTF group begins
* or ends. */
- Dictionary parserState; /* Current parser state */
+ Dictionary<Object, Object> parserState; /* Current parser state */
/** This is the "dst" item from parserState. rtfDestination
* is the current rtf destination. It is cached in an instance
* variable for speed. */
@@ -63,7 +63,7 @@
MutableAttributeSet documentAttributes;
/** This Dictionary maps Integer font numbers to String font names. */
- Dictionary fontTable;
+ Dictionary<Integer, String> fontTable;
/** This array maps color indices to Color objects. */
Color[] colorTable;
/** This array maps character style numbers to Style objects. */
@@ -86,7 +86,7 @@
* Unicode character. */
int skippingCharacters;
- static private Dictionary straightforwardAttributes;
+ static private Dictionary<String, RTFAttribute> straightforwardAttributes;
static {
straightforwardAttributes = RTFAttributes.attributesByKeyword();
}
@@ -96,9 +96,9 @@
/* this should be final, but there's a bug in javac... */
/** textKeywords maps RTF keywords to single-character strings,
* for those keywords which simply insert some text. */
- static Dictionary textKeywords = null;
+ static Dictionary<String, String> textKeywords = null;
static {
- textKeywords = new Hashtable();
+ textKeywords = new Hashtable<String, String>();
textKeywords.put("\\", "\\");
textKeywords.put("{", "{");
textKeywords.put("}", "}");
@@ -129,10 +129,10 @@
static final String TabAlignmentKey = "tab_alignment";
static final String TabLeaderKey = "tab_leader";
- static Dictionary characterSets;
+ static Dictionary<String, char[]> characterSets;
static boolean useNeXTForAnsi = false;
static {
- characterSets = new Hashtable();
+ characterSets = new Hashtable<String, char[]>();
}
/* TODO: per-font font encodings ( \fcharset control word ) ? */
@@ -148,8 +148,8 @@
int i;
target = destination;
- parserState = new Hashtable();
- fontTable = new Hashtable();
+ parserState = new Hashtable<Object, Object>();
+ fontTable = new Hashtable<Integer, String>();
rtfversion = -1;
@@ -220,7 +220,7 @@
Object oldSaveState = parserState.get("_savedState");
if (oldSaveState != null)
parserState.remove("_savedState");
- Dictionary saveState = (Dictionary)((Hashtable)parserState).clone();
+ Dictionary<String, Object> saveState = (Dictionary<String, Object>)((Hashtable)parserState).clone();
if (oldSaveState != null)
saveState.put("_savedState", oldSaveState);
parserState.put("_savedState", saveState);
@@ -242,7 +242,7 @@
skippingCharacters = 0;
}
- Dictionary restoredState = (Dictionary)parserState.get("_savedState");
+ Dictionary<Object, Object> restoredState = (Dictionary<Object, Object>)parserState.get("_savedState");
Destination restoredDestination = (Destination)restoredState.get("dst");
if (restoredDestination != rtfDestination) {
rtfDestination.close(); /* allow the destination to clean up */
@@ -281,7 +281,7 @@
while(docProps.hasMoreElements()) {
Object propName = docProps.nextElement();
target.putProperty(propName,
- documentAttributes.getAttribute((String)propName));
+ documentAttributes.getAttribute(propName));
}
/* RTFParser should have ensured that all our groups are closed */
@@ -301,7 +301,7 @@
*/
public boolean handleKeyword(String keyword)
{
- Object item;
+ String item;
boolean ignoreGroupIfUnknownKeywordSave = ignoreGroupIfUnknownKeyword;
if (skippingCharacters > 0) {
@@ -312,7 +312,7 @@
ignoreGroupIfUnknownKeyword = false;
if ((item = textKeywords.get(keyword)) != null) {
- handleText((String)item);
+ handleText(item);
return true;
}
@@ -556,14 +556,12 @@
getCharacterSet(final String name)
throws IOException
{
- char[] set;
-
- set = (char [])characterSets.get(name);
+ char[] set = characterSets.get(name);
if (set == null) {
InputStream charsetStream;
- charsetStream = (InputStream)java.security.AccessController.
- doPrivileged(new java.security.PrivilegedAction() {
- public Object run() {
+ charsetStream = java.security.AccessController.
+ doPrivileged(new java.security.PrivilegedAction<InputStream>() {
+ public InputStream run() {
return RTFReader.class.getResourceAsStream
("charsets/" + name + ".txt");
}
@@ -686,7 +684,7 @@
class FonttblDestination implements Destination
{
int nextFontNumber;
- Object fontNumberKey = null;
+ Integer fontNumberKey = null;
String nextFontFamily;
public void handleBinaryBlob(byte[] data)
@@ -716,7 +714,6 @@
nextFontNumber = -1;
nextFontFamily = null;
- return;
}
public boolean handleKeyword(String keyword)
@@ -747,10 +744,10 @@
dump its contents to the debugging log. */
public void close()
{
- Enumeration nums = fontTable.keys();
+ Enumeration<Integer> nums = fontTable.keys();
warning("Done reading font table.");
while(nums.hasMoreElements()) {
- Integer num = (Integer)nums.nextElement();
+ Integer num = nums.nextElement();
warning("Number " + num + ": " + fontTable.get(num));
}
}
@@ -761,19 +758,19 @@
class ColortblDestination implements Destination
{
int red, green, blue;
- Vector proTemTable;
+ Vector<Color> proTemTable;
public ColortblDestination()
{
red = 0;
green = 0;
blue = 0;
- proTemTable = new Vector();
+ proTemTable = new Vector<Color>();
}
public void handleText(String text)
{
- int index = 0;
+ int index;
for (index = 0; index < text.length(); index ++) {
if (text.charAt(index) == ';') {
@@ -823,11 +820,11 @@
extends DiscardingDestination
implements Destination
{
- Dictionary definedStyles;
+ Dictionary<Integer, StyleDefiningDestination> definedStyles;
public StylesheetDestination()
{
- definedStyles = new Hashtable();
+ definedStyles = new Hashtable<Integer, StyleDefiningDestination>();
}
public void begingroup()
@@ -837,19 +834,18 @@
public void close()
{
- Vector chrStyles, pgfStyles, secStyles;
- chrStyles = new Vector();
- pgfStyles = new Vector();
- secStyles = new Vector();
- Enumeration styles = definedStyles.elements();
+ Vector<Style> chrStyles = new Vector<Style>();
+ Vector<Style> pgfStyles = new Vector<Style>();
+ Vector<Style> secStyles = new Vector<Style>();
+ Enumeration<StyleDefiningDestination> styles = definedStyles.elements();
while(styles.hasMoreElements()) {
StyleDefiningDestination style;
Style defined;
- style = (StyleDefiningDestination)styles.nextElement();
+ style = styles.nextElement();
defined = style.realize();
warning("Style "+style.number+" ("+style.styleName+"): "+defined);
String stype = (String)defined.getAttribute(Constants.StyleType);
- Vector toSet;
+ Vector<Style> toSet;
if (stype.equals(Constants.STSection)) {
toSet = secStyles;
} else if (stype.equals(Constants.STCharacter)) {
@@ -989,7 +985,7 @@
if (basedOn != STYLENUMBER_NONE) {
StyleDefiningDestination styleDest;
- styleDest = (StyleDefiningDestination)definedStyles.get(Integer.valueOf(basedOn));
+ styleDest = definedStyles.get(Integer.valueOf(basedOn));
if (styleDest != null && styleDest != this) {
basis = styleDest.realize();
}
@@ -1016,7 +1012,7 @@
if (nextStyle != STYLENUMBER_NONE) {
StyleDefiningDestination styleDest;
- styleDest = (StyleDefiningDestination)definedStyles.get(Integer.valueOf(nextStyle));
+ styleDest = definedStyles.get(Integer.valueOf(nextStyle));
if (styleDest != null) {
next = styleDest.realize();
}
@@ -1122,9 +1118,8 @@
}
{
- Object item = straightforwardAttributes.get(keyword);
- if (item != null) {
- RTFAttribute attr = (RTFAttribute)item;
+ RTFAttribute attr = straightforwardAttributes.get(keyword);
+ if (attr != null) {
boolean ok;
switch(attr.domain()) {
@@ -1191,9 +1186,8 @@
}
{
- Object item = straightforwardAttributes.get(keyword);
- if (item != null) {
- RTFAttribute attr = (RTFAttribute)item;
+ RTFAttribute attr = straightforwardAttributes.get(keyword);
+ if (attr != null) {
boolean ok;
switch(attr.domain()) {
@@ -1267,12 +1261,12 @@
parserState.remove("tab_leader");
TabStop newStop = new TabStop(tabPosition, tabAlignment, tabLeader);
- Dictionary tabs;
+ Dictionary<Object, Object> tabs;
Integer stopCount;
- tabs = (Dictionary)parserState.get("_tabs");
+ tabs = (Dictionary<Object, Object>)parserState.get("_tabs");
if (tabs == null) {
- tabs = new Hashtable();
+ tabs = new Hashtable<Object, Object>();
parserState.put("_tabs", tabs);
stopCount = Integer.valueOf(1);
} else {
@@ -1369,7 +1363,7 @@
/* note setFontFamily() can not handle a null font */
String fontFamily;
if (fontnum != null)
- fontFamily = (String)fontTable.get(fontnum);
+ fontFamily = fontTable.get(fontnum);
else
fontFamily = null;
if (fontFamily != null)
@@ -1474,9 +1468,9 @@
handleKeyword("fs", 24); /* 12 pt. */
- Enumeration attributes = straightforwardAttributes.elements();
+ Enumeration<RTFAttribute> attributes = straightforwardAttributes.elements();
while(attributes.hasMoreElements()) {
- RTFAttribute attr = (RTFAttribute)attributes.nextElement();
+ RTFAttribute attr = attributes.nextElement();
if (attr.domain() == RTFAttribute.D_CHARACTER)
attr.setDefault(characterAttributes);
}
@@ -1498,9 +1492,9 @@
StyleConstants.setAlignment(paragraphAttributes,
StyleConstants.ALIGN_LEFT);
- Enumeration attributes = straightforwardAttributes.elements();
+ Enumeration<RTFAttribute> attributes = straightforwardAttributes.elements();
while(attributes.hasMoreElements()) {
- RTFAttribute attr = (RTFAttribute)attributes.nextElement();
+ RTFAttribute attr = attributes.nextElement();
if (attr.domain() == RTFAttribute.D_PARAGRAPH)
attr.setDefault(characterAttributes);
}
@@ -1511,9 +1505,9 @@
* \sectd keyword. */
protected void resetSectionAttributes()
{
- Enumeration attributes = straightforwardAttributes.elements();
+ Enumeration<RTFAttribute> attributes = straightforwardAttributes.elements();
while(attributes.hasMoreElements()) {
- RTFAttribute attr = (RTFAttribute)attributes.nextElement();
+ RTFAttribute attr = attributes.nextElement();
if (attr.domain() == RTFAttribute.D_SECTION)
attr.setDefault(characterAttributes);
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/awt/EventQueueDelegate.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,71 @@
+/*
+ * 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 sun.awt;
+
+import java.awt.AWTEvent;
+import java.awt.EventQueue;
+
+
+public class EventQueueDelegate {
+ private static final Object EVENT_QUEUE_DELEGATE_KEY =
+ new StringBuilder("EventQueueDelegate.Delegate");
+
+ public static void setDelegate(Delegate delegate) {
+ AppContext.getAppContext().put(EVENT_QUEUE_DELEGATE_KEY, delegate);
+ }
+ public static Delegate getDelegate() {
+ return
+ (Delegate) AppContext.getAppContext().get(EVENT_QUEUE_DELEGATE_KEY);
+ }
+ public interface Delegate {
+ /**
+ * This method allows for changing {@code EventQueue} events order.
+ *
+ * @param eventQueue current {@code EventQueue}
+ * @return next {@code event} for the {@code EventDispatchThread}
+ */
+
+ public AWTEvent getNextEvent(EventQueue eventQueue) throws InterruptedException;
+
+ /**
+ * Notifies delegate before EventQueue.dispatch method.
+ *
+ * Note: this method may mutate the event
+ *
+ * @param event to be dispatched by {@code dispatch} method
+ * @return handle to be passed to {@code afterDispatch} method
+ */
+ public Object beforeDispatch(AWTEvent event) throws InterruptedException;
+
+ /**
+ * Notifies delegate after EventQueue.dispatch method.
+ *
+ * @param event {@code event} dispatched by the {@code dispatch} method
+ * @param handle object which came from {@code beforeDispatch} method
+ */
+ public void afterDispatch(AWTEvent event, Object handle) throws InterruptedException;
+ }
+}
--- a/jdk/src/share/classes/sun/awt/im/InputMethodManager.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/sun/awt/im/InputMethodManager.java Tue Aug 12 17:59:58 2008 -0700
@@ -358,6 +358,7 @@
AppContext requesterAppContext = SunToolkit.targetToAppContext(requester);
synchronized (lock) {
SunToolkit.postEvent(requesterAppContext, event);
+ lock.wait();
}
Throwable eventThrowable = event.getThrowable();
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/swing/MenuItemLayoutHelper.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,1302 @@
+/*
+ * 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
+ * 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 sun.swing;
+
+import static sun.swing.SwingUtilities2.BASICMENUITEMUI_MAX_TEXT_OFFSET;
+
+import javax.swing.*;
+import javax.swing.plaf.basic.BasicHTML;
+import javax.swing.text.View;
+import java.awt.*;
+import java.awt.event.KeyEvent;
+import java.util.Map;
+import java.util.HashMap;
+
+/**
+ * Calculates preferred size and layouts menu items.
+ */
+public class MenuItemLayoutHelper {
+
+ /* Client Property keys for calculation of maximal widths */
+ public static final StringUIClientPropertyKey MAX_ARROW_WIDTH =
+ new StringUIClientPropertyKey("maxArrowWidth");
+ public static final StringUIClientPropertyKey MAX_CHECK_WIDTH =
+ new StringUIClientPropertyKey("maxCheckWidth");
+ public static final StringUIClientPropertyKey MAX_ICON_WIDTH =
+ new StringUIClientPropertyKey("maxIconWidth");
+ public static final StringUIClientPropertyKey MAX_TEXT_WIDTH =
+ new StringUIClientPropertyKey("maxTextWidth");
+ public static final StringUIClientPropertyKey MAX_ACC_WIDTH =
+ new StringUIClientPropertyKey("maxAccWidth");
+ public static final StringUIClientPropertyKey MAX_LABEL_WIDTH =
+ new StringUIClientPropertyKey("maxLabelWidth");
+
+ private JMenuItem mi;
+ private JComponent miParent;
+
+ private Font font;
+ private Font accFont;
+ private FontMetrics fm;
+ private FontMetrics accFm;
+
+ private Icon icon;
+ private Icon checkIcon;
+ private Icon arrowIcon;
+ private String text;
+ private String accText;
+
+ private boolean isColumnLayout;
+ private boolean useCheckAndArrow;
+ private boolean isLeftToRight;
+ private boolean isTopLevelMenu;
+ private View htmlView;
+
+ private int verticalAlignment;
+ private int horizontalAlignment;
+ private int verticalTextPosition;
+ private int horizontalTextPosition;
+ private int gap;
+ private int leadingGap;
+ private int afterCheckIconGap;
+ private int minTextOffset;
+
+ private Rectangle viewRect;
+
+ private RectSize iconSize;
+ private RectSize textSize;
+ private RectSize accSize;
+ private RectSize checkSize;
+ private RectSize arrowSize;
+ private RectSize labelSize;
+
+ /**
+ * The empty protected constructor is necessary for derived classes.
+ */
+ protected MenuItemLayoutHelper() {
+ }
+
+ public MenuItemLayoutHelper(JMenuItem mi, Icon checkIcon, Icon arrowIcon,
+ Rectangle viewRect, int gap, String accDelimiter,
+ boolean isLeftToRight, Font font, Font accFont,
+ boolean useCheckAndArrow, String propertyPrefix) {
+ reset(mi, checkIcon, arrowIcon, viewRect, gap, accDelimiter,
+ isLeftToRight, font, accFont, useCheckAndArrow, propertyPrefix);
+ }
+
+ protected void reset(JMenuItem mi, Icon checkIcon, Icon arrowIcon,
+ Rectangle viewRect, int gap, String accDelimiter,
+ boolean isLeftToRight, Font font, Font accFont,
+ boolean useCheckAndArrow, String propertyPrefix) {
+ this.mi = mi;
+ this.miParent = getMenuItemParent(mi);
+ this.accText = getAccText(accDelimiter);
+ this.verticalAlignment = mi.getVerticalAlignment();
+ this.horizontalAlignment = mi.getHorizontalAlignment();
+ this.verticalTextPosition = mi.getVerticalTextPosition();
+ this.horizontalTextPosition = mi.getHorizontalTextPosition();
+ this.useCheckAndArrow = useCheckAndArrow;
+ this.font = font;
+ this.accFont = accFont;
+ this.fm = mi.getFontMetrics(font);
+ this.accFm = mi.getFontMetrics(accFont);
+ this.isLeftToRight = isLeftToRight;
+ this.isColumnLayout = isColumnLayout(isLeftToRight,
+ horizontalAlignment, horizontalTextPosition,
+ verticalTextPosition);
+ this.isTopLevelMenu = (this.miParent == null) ? true : false;
+ this.checkIcon = checkIcon;
+ this.icon = getIcon(propertyPrefix);
+ this.arrowIcon = arrowIcon;
+ this.text = mi.getText();
+ this.gap = gap;
+ this.afterCheckIconGap = getAfterCheckIconGap(propertyPrefix);
+ this.minTextOffset = getMinTextOffset(propertyPrefix);
+ this.htmlView = (View) mi.getClientProperty(BasicHTML.propertyKey);
+ this.viewRect = viewRect;
+
+ this.iconSize = new RectSize();
+ this.textSize = new RectSize();
+ this.accSize = new RectSize();
+ this.checkSize = new RectSize();
+ this.arrowSize = new RectSize();
+ this.labelSize = new RectSize();
+ calcWidthsAndHeights();
+ setOriginalWidths();
+ calcMaxWidths();
+
+ this.leadingGap = getLeadingGap(propertyPrefix);
+ calcMaxTextOffset(viewRect);
+ }
+
+ private void setOriginalWidths() {
+ iconSize.origWidth = iconSize.width;
+ textSize.origWidth = textSize.width;
+ accSize.origWidth = accSize.width;
+ checkSize.origWidth = checkSize.width;
+ arrowSize.origWidth = arrowSize.width;
+ }
+
+ private String getAccText(String acceleratorDelimiter) {
+ String accText = "";
+ KeyStroke accelerator = mi.getAccelerator();
+ if (accelerator != null) {
+ int modifiers = accelerator.getModifiers();
+ if (modifiers > 0) {
+ accText = KeyEvent.getKeyModifiersText(modifiers);
+ accText += acceleratorDelimiter;
+ }
+ int keyCode = accelerator.getKeyCode();
+ if (keyCode != 0) {
+ accText += KeyEvent.getKeyText(keyCode);
+ } else {
+ accText += accelerator.getKeyChar();
+ }
+ }
+ return accText;
+ }
+
+ private Icon getIcon(String propertyPrefix) {
+ // In case of column layout, .checkIconFactory is defined for this UI,
+ // the icon is compatible with it and useCheckAndArrow() is true,
+ // then the icon is handled by the checkIcon.
+ Icon icon = null;
+ MenuItemCheckIconFactory iconFactory =
+ (MenuItemCheckIconFactory) UIManager.get(propertyPrefix
+ + ".checkIconFactory");
+ if (!isColumnLayout || !useCheckAndArrow || iconFactory == null
+ || !iconFactory.isCompatible(checkIcon, propertyPrefix)) {
+ icon = mi.getIcon();
+ }
+ return icon;
+ }
+
+ private int getMinTextOffset(String propertyPrefix) {
+ int minimumTextOffset = 0;
+ Object minimumTextOffsetObject =
+ UIManager.get(propertyPrefix + ".minimumTextOffset");
+ if (minimumTextOffsetObject instanceof Integer) {
+ minimumTextOffset = (Integer) minimumTextOffsetObject;
+ }
+ return minimumTextOffset;
+ }
+
+ private int getAfterCheckIconGap(String propertyPrefix) {
+ int afterCheckIconGap = gap;
+ Object afterCheckIconGapObject =
+ UIManager.get(propertyPrefix + ".afterCheckIconGap");
+ if (afterCheckIconGapObject instanceof Integer) {
+ afterCheckIconGap = (Integer) afterCheckIconGapObject;
+ }
+ return afterCheckIconGap;
+ }
+
+ private int getLeadingGap(String propertyPrefix) {
+ if (checkSize.getMaxWidth() > 0) {
+ return getCheckOffset(propertyPrefix);
+ } else {
+ return gap; // There is no any check icon
+ }
+ }
+
+ private int getCheckOffset(String propertyPrefix) {
+ int checkIconOffset = gap;
+ Object checkIconOffsetObject =
+ UIManager.get(propertyPrefix + ".checkIconOffset");
+ if (checkIconOffsetObject instanceof Integer) {
+ checkIconOffset = (Integer) checkIconOffsetObject;
+ }
+ return checkIconOffset;
+ }
+
+ protected void calcWidthsAndHeights() {
+ // iconRect
+ if (icon != null) {
+ iconSize.width = icon.getIconWidth();
+ iconSize.height = icon.getIconHeight();
+ }
+
+ // accRect
+ if (!accText.equals("")) {
+ accSize.width = SwingUtilities2.stringWidth(mi, accFm, accText);
+ accSize.height = accFm.getHeight();
+ }
+
+ // textRect
+ if (text == null) {
+ text = "";
+ } else if (!text.equals("")) {
+ if (htmlView != null) {
+ // Text is HTML
+ textSize.width =
+ (int) htmlView.getPreferredSpan(View.X_AXIS);
+ textSize.height =
+ (int) htmlView.getPreferredSpan(View.Y_AXIS);
+ } else {
+ // Text isn't HTML
+ textSize.width = SwingUtilities2.stringWidth(mi, fm, text);
+ textSize.height = fm.getHeight();
+ }
+ }
+
+ if (useCheckAndArrow) {
+ // checkIcon
+ if (checkIcon != null) {
+ checkSize.width = checkIcon.getIconWidth();
+ checkSize.height = checkIcon.getIconHeight();
+ }
+ // arrowRect
+ if (arrowIcon != null) {
+ arrowSize.width = arrowIcon.getIconWidth();
+ arrowSize.height = arrowIcon.getIconHeight();
+ }
+ }
+
+ // labelRect
+ if (isColumnLayout) {
+ labelSize.width = iconSize.width + textSize.width + gap;
+ labelSize.height = max(checkSize.height, iconSize.height,
+ textSize.height, accSize.height, arrowSize.height);
+ } else {
+ Rectangle textRect = new Rectangle();
+ Rectangle iconRect = new Rectangle();
+ SwingUtilities.layoutCompoundLabel(mi, fm, text, icon,
+ verticalAlignment, horizontalAlignment,
+ verticalTextPosition, horizontalTextPosition,
+ viewRect, iconRect, textRect, gap);
+ Rectangle labelRect = iconRect.union(textRect);
+ labelSize.height = labelRect.height;
+ labelSize.width = labelRect.width;
+ }
+ }
+
+ protected void calcMaxWidths() {
+ calcMaxWidth(checkSize, MAX_CHECK_WIDTH);
+ calcMaxWidth(arrowSize, MAX_ARROW_WIDTH);
+ calcMaxWidth(accSize, MAX_ACC_WIDTH);
+
+ if (isColumnLayout) {
+ calcMaxWidth(iconSize, MAX_ICON_WIDTH);
+ calcMaxWidth(textSize, MAX_TEXT_WIDTH);
+ int curGap = gap;
+ if ((iconSize.getMaxWidth() == 0)
+ || (textSize.getMaxWidth() == 0)) {
+ curGap = 0;
+ }
+ labelSize.maxWidth =
+ calcMaxValue(MAX_LABEL_WIDTH, iconSize.maxWidth
+ + textSize.maxWidth + curGap);
+ } else {
+ // We shouldn't use current icon and text widths
+ // in maximal widths calculation for complex layout.
+ iconSize.maxWidth = getParentIntProperty(MAX_ICON_WIDTH);
+ calcMaxWidth(labelSize, MAX_LABEL_WIDTH);
+ // If maxLabelWidth is wider
+ // than the widest icon + the widest text + gap,
+ // we should update the maximal text witdh
+ int candidateTextWidth = labelSize.maxWidth - iconSize.maxWidth;
+ if (iconSize.maxWidth > 0) {
+ candidateTextWidth -= gap;
+ }
+ textSize.maxWidth = calcMaxValue(MAX_TEXT_WIDTH, candidateTextWidth);
+ }
+ }
+
+ protected void calcMaxWidth(RectSize rs, Object key) {
+ rs.maxWidth = calcMaxValue(key, rs.width);
+ }
+
+ /**
+ * Calculates and returns maximal value through specified parent component
+ * client property.
+ *
+ * @param propertyName name of the property, which stores the maximal value.
+ * @param value a value which pretends to be maximal
+ * @return maximal value among the parent property and the value.
+ */
+ protected int calcMaxValue(Object propertyName, int value) {
+ // Get maximal value from parent client property
+ int maxValue = getParentIntProperty(propertyName);
+ // Store new maximal width in parent client property
+ if (value > maxValue) {
+ if (miParent != null) {
+ miParent.putClientProperty(propertyName, value);
+ }
+ return value;
+ } else {
+ return maxValue;
+ }
+ }
+
+ /**
+ * Returns parent client property as int.
+ * @param propertyName name of the parent property.
+ * @return value of the property as int.
+ */
+ protected int getParentIntProperty(Object propertyName) {
+ Object value = null;
+ if (miParent != null) {
+ value = miParent.getClientProperty(propertyName);
+ }
+ if ((value == null) || !(value instanceof Integer)) {
+ value = 0;
+ }
+ return (Integer) value;
+ }
+
+ public static boolean isColumnLayout(boolean isLeftToRight,
+ JMenuItem mi) {
+ assert(mi != null);
+ return isColumnLayout(isLeftToRight, mi.getHorizontalAlignment(),
+ mi.getHorizontalTextPosition(), mi.getVerticalTextPosition());
+ }
+
+ /**
+ * Answers should we do column layout for a menu item or not.
+ * We do it when a user doesn't set any alignments
+ * and text positions manually, except the vertical alignment.
+ */
+ public static boolean isColumnLayout(boolean isLeftToRight,
+ int horizontalAlignment,
+ int horizontalTextPosition,
+ int verticalTextPosition) {
+ if (verticalTextPosition != SwingConstants.CENTER) {
+ return false;
+ }
+ if (isLeftToRight) {
+ if (horizontalAlignment != SwingConstants.LEADING
+ && horizontalAlignment != SwingConstants.LEFT) {
+ return false;
+ }
+ if (horizontalTextPosition != SwingConstants.TRAILING
+ && horizontalTextPosition != SwingConstants.RIGHT) {
+ return false;
+ }
+ } else {
+ if (horizontalAlignment != SwingConstants.LEADING
+ && horizontalAlignment != SwingConstants.RIGHT) {
+ return false;
+ }
+ if (horizontalTextPosition != SwingConstants.TRAILING
+ && horizontalTextPosition != SwingConstants.LEFT) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Calculates maximal text offset.
+ * It is required for some L&Fs (ex: Vista L&F).
+ * The offset is meaningful only for L2R column layout.
+ *
+ * @param viewRect the rectangle, the maximal text offset
+ * will be calculated for.
+ */
+ private void calcMaxTextOffset(Rectangle viewRect) {
+ if (!isColumnLayout || !isLeftToRight) {
+ return;
+ }
+
+ // Calculate the current text offset
+ int offset = viewRect.x + leadingGap + checkSize.maxWidth
+ + afterCheckIconGap + iconSize.maxWidth + gap;
+ if (checkSize.maxWidth == 0) {
+ offset -= afterCheckIconGap;
+ }
+ if (iconSize.maxWidth == 0) {
+ offset -= gap;
+ }
+
+ // maximal text offset shouldn't be less than minimal text offset;
+ if (offset < minTextOffset) {
+ offset = minTextOffset;
+ }
+
+ // Calculate and store the maximal text offset
+ calcMaxValue(SwingUtilities2.BASICMENUITEMUI_MAX_TEXT_OFFSET, offset);
+ }
+
+ /**
+ * Layout icon, text, check icon, accelerator text and arrow icon
+ * in the viewRect and return their positions.
+ *
+ * If horizontalAlignment, verticalTextPosition and horizontalTextPosition
+ * are default (user doesn't set any manually) the layouting algorithm is:
+ * Elements are layouted in the five columns:
+ * check icon + icon + text + accelerator text + arrow icon
+ *
+ * In the other case elements are layouted in the four columns:
+ * check icon + label + accelerator text + arrow icon
+ * Label is union of icon and text.
+ *
+ * The order of columns can be reversed.
+ * It depends on the menu item orientation.
+ */
+ public LayoutResult layoutMenuItem() {
+ LayoutResult lr = createLayoutResult();
+ prepareForLayout(lr);
+
+ if (isColumnLayout()) {
+ if (isLeftToRight()) {
+ doLTRColumnLayout(lr, getLTRColumnAlignment());
+ } else {
+ doRTLColumnLayout(lr, getRTLColumnAlignment());
+ }
+ } else {
+ if (isLeftToRight()) {
+ doLTRComplexLayout(lr, getLTRColumnAlignment());
+ } else {
+ doRTLComplexLayout(lr, getRTLColumnAlignment());
+ }
+ }
+
+ alignAccCheckAndArrowVertically(lr);
+ return lr;
+ }
+
+ private LayoutResult createLayoutResult() {
+ return new LayoutResult(
+ new Rectangle(iconSize.width, iconSize.height),
+ new Rectangle(textSize.width, textSize.height),
+ new Rectangle(accSize.width, accSize.height),
+ new Rectangle(checkSize.width, checkSize.height),
+ new Rectangle(arrowSize.width, arrowSize.height),
+ new Rectangle(labelSize.width, labelSize.height)
+ );
+ }
+
+ public ColumnAlignment getLTRColumnAlignment() {
+ return ColumnAlignment.LEFT_ALIGNMENT;
+ }
+
+ public ColumnAlignment getRTLColumnAlignment() {
+ return ColumnAlignment.RIGHT_ALIGNMENT;
+ }
+
+ protected void prepareForLayout(LayoutResult lr) {
+ lr.checkRect.width = checkSize.maxWidth;
+ lr.accRect.width = accSize.maxWidth;
+ lr.arrowRect.width = arrowSize.maxWidth;
+ }
+
+ /**
+ * Aligns the accelertor text and the check and arrow icons vertically
+ * with the center of the label rect.
+ */
+ private void alignAccCheckAndArrowVertically(LayoutResult lr) {
+ lr.accRect.y = (int)(lr.labelRect.y
+ + (float)lr.labelRect.height/2
+ - (float)lr.accRect.height/2);
+ fixVerticalAlignment(lr, lr.accRect);
+ if (useCheckAndArrow) {
+ lr.arrowRect.y = (int)(lr.labelRect.y
+ + (float)lr.labelRect.height/2
+ - (float)lr.arrowRect.height/2);
+ lr.checkRect.y = (int)(lr.labelRect.y
+ + (float)lr.labelRect.height/2
+ - (float)lr.checkRect.height/2);
+ fixVerticalAlignment(lr, lr.arrowRect);
+ fixVerticalAlignment(lr, lr.checkRect);
+ }
+ }
+
+ /**
+ * Fixes vertical alignment of all menu item elements if rect.y
+ * or (rect.y + rect.height) is out of viewRect bounds
+ */
+ private void fixVerticalAlignment(LayoutResult lr, Rectangle r) {
+ int delta = 0;
+ if (r.y < viewRect.y) {
+ delta = viewRect.y - r.y;
+ } else if (r.y + r.height > viewRect.y + viewRect.height) {
+ delta = viewRect.y + viewRect.height - r.y - r.height;
+ }
+ if (delta != 0) {
+ lr.checkRect.y += delta;
+ lr.iconRect.y += delta;
+ lr.textRect.y += delta;
+ lr.accRect.y += delta;
+ lr.arrowRect.y += delta;
+ lr.labelRect.y += delta;
+ }
+ }
+
+ private void doLTRColumnLayout(LayoutResult lr, ColumnAlignment alignment) {
+ // Set maximal width for all the five basic rects
+ // (three other ones are already maximal)
+ lr.iconRect.width = iconSize.maxWidth;
+ lr.textRect.width = textSize.maxWidth;
+
+ // Set X coordinates
+ // All rects will be aligned at the left side
+ calcXPositionsLTR(viewRect.x, leadingGap, gap, lr.checkRect,
+ lr.iconRect, lr.textRect);
+
+ // Tune afterCheckIconGap
+ if (lr.checkRect.width > 0) { // there is the afterCheckIconGap
+ lr.iconRect.x += afterCheckIconGap - gap;
+ lr.textRect.x += afterCheckIconGap - gap;
+ }
+
+ calcXPositionsRTL(viewRect.x + viewRect.width, leadingGap, gap,
+ lr.arrowRect, lr.accRect);
+
+ // Take into account minimal text offset
+ int textOffset = lr.textRect.x - viewRect.x;
+ if (!isTopLevelMenu && (textOffset < minTextOffset)) {
+ lr.textRect.x += minTextOffset - textOffset;
+ }
+
+ alignRects(lr, alignment);
+
+ // Set Y coordinate for text and icon.
+ // Y coordinates for other rects
+ // will be calculated later in layoutMenuItem.
+ calcTextAndIconYPositions(lr);
+
+ // Calculate valid X and Y coordinates for labelRect
+ lr.setLabelRect(lr.textRect.union(lr.iconRect));
+ }
+
+ private void doLTRComplexLayout(LayoutResult lr, ColumnAlignment alignment) {
+ lr.labelRect.width = labelSize.maxWidth;
+
+ // Set X coordinates
+ calcXPositionsLTR(viewRect.x, leadingGap, gap, lr.checkRect,
+ lr.labelRect);
+
+ // Tune afterCheckIconGap
+ if (lr.checkRect.width > 0) { // there is the afterCheckIconGap
+ lr.labelRect.x += afterCheckIconGap - gap;
+ }
+
+ calcXPositionsRTL(viewRect.x + viewRect.width,
+ leadingGap, gap, lr.arrowRect, lr.accRect);
+
+ // Take into account minimal text offset
+ int labelOffset = lr.labelRect.x - viewRect.x;
+ if (!isTopLevelMenu && (labelOffset < minTextOffset)) {
+ lr.labelRect.x += minTextOffset - labelOffset;
+ }
+
+ alignRects(lr, alignment);
+
+ // Center labelRect vertically
+ calcLabelYPosition(lr);
+
+ layoutIconAndTextInLabelRect(lr);
+ }
+
+ private void doRTLColumnLayout(LayoutResult lr, ColumnAlignment alignment) {
+ // Set maximal width for all the five basic rects
+ // (three other ones are already maximal)
+ lr.iconRect.width = iconSize.maxWidth;
+ lr.textRect.width = textSize.maxWidth;
+
+ // Set X coordinates
+ calcXPositionsRTL(viewRect.x + viewRect.width, leadingGap, gap,
+ lr.checkRect, lr.iconRect, lr.textRect);
+
+ // Tune the gap after check icon
+ if (lr.checkRect.width > 0) { // there is the gap after check icon
+ lr.iconRect.x -= afterCheckIconGap - gap;
+ lr.textRect.x -= afterCheckIconGap - gap;
+ }
+
+ calcXPositionsLTR(viewRect.x, leadingGap, gap, lr.arrowRect,
+ lr.accRect);
+
+ // Take into account minimal text offset
+ int textOffset = (viewRect.x + viewRect.width)
+ - (lr.textRect.x + lr.textRect.width);
+ if (!isTopLevelMenu && (textOffset < minTextOffset)) {
+ lr.textRect.x -= minTextOffset - textOffset;
+ }
+
+ alignRects(lr, alignment);
+
+ // Set Y coordinates for text and icon.
+ // Y coordinates for other rects
+ // will be calculated later in layoutMenuItem.
+ calcTextAndIconYPositions(lr);
+
+ // Calculate valid X and Y coordinate for labelRect
+ lr.setLabelRect(lr.textRect.union(lr.iconRect));
+ }
+
+ private void doRTLComplexLayout(LayoutResult lr, ColumnAlignment alignment) {
+ lr.labelRect.width = labelSize.maxWidth;
+
+ // Set X coordinates
+ calcXPositionsRTL(viewRect.x + viewRect.width, leadingGap, gap,
+ lr.checkRect, lr.labelRect);
+
+ // Tune the gap after check icon
+ if (lr.checkRect.width > 0) { // there is the gap after check icon
+ lr.labelRect.x -= afterCheckIconGap - gap;
+ }
+
+ calcXPositionsLTR(viewRect.x, leadingGap, gap, lr.arrowRect, lr.accRect);
+
+ // Take into account minimal text offset
+ int labelOffset = (viewRect.x + viewRect.width)
+ - (lr.labelRect.x + lr.labelRect.width);
+ if (!isTopLevelMenu && (labelOffset < minTextOffset)) {
+ lr.labelRect.x -= minTextOffset - labelOffset;
+ }
+
+ alignRects(lr, alignment);
+
+ // Center labelRect vertically
+ calcLabelYPosition(lr);
+
+ layoutIconAndTextInLabelRect(lr);
+ }
+
+ private void alignRects(LayoutResult lr, ColumnAlignment alignment) {
+ alignRect(lr.checkRect, alignment.getCheckAlignment(),
+ checkSize.getOrigWidth());
+ alignRect(lr.iconRect, alignment.getIconAlignment(),
+ iconSize.getOrigWidth());
+ alignRect(lr.textRect, alignment.getTextAlignment(),
+ textSize.getOrigWidth());
+ alignRect(lr.accRect, alignment.getAccAlignment(),
+ accSize.getOrigWidth());
+ alignRect(lr.arrowRect, alignment.getArrowAlignment(),
+ arrowSize.getOrigWidth());
+ }
+
+ private void alignRect(Rectangle rect, int alignment, int origWidth) {
+ if (alignment != SwingUtilities.LEFT) {
+ rect.x = rect.x + rect.width - origWidth;
+ rect.width = origWidth;
+ }
+ }
+
+ protected void layoutIconAndTextInLabelRect(LayoutResult lr) {
+ lr.setTextRect(new Rectangle());
+ lr.setIconRect(new Rectangle());
+ SwingUtilities.layoutCompoundLabel(
+ mi, fm, text,icon, verticalAlignment, horizontalAlignment,
+ verticalTextPosition, horizontalTextPosition, lr.labelRect,
+ lr.iconRect, lr.textRect, gap);
+ }
+
+ private void calcXPositionsLTR(int startXPos, int leadingGap,
+ int gap, Rectangle... rects) {
+ int curXPos = startXPos + leadingGap;
+ for (Rectangle rect : rects) {
+ rect.x = curXPos;
+ if (rect.width > 0) {
+ curXPos += rect.width + gap;
+ }
+ }
+ }
+
+ private void calcXPositionsRTL(int startXPos, int leadingGap,
+ int gap, Rectangle... rects) {
+ int curXPos = startXPos - leadingGap;
+ for (Rectangle rect : rects) {
+ rect.x = curXPos - rect.width;
+ if (rect.width > 0) {
+ curXPos -= rect.width + gap;
+ }
+ }
+ }
+
+ /**
+ * Sets Y coordinates of text and icon
+ * taking into account the vertical alignment
+ */
+ private void calcTextAndIconYPositions(LayoutResult lr) {
+ if (verticalAlignment == SwingUtilities.TOP) {
+ lr.textRect.y = (int)(viewRect.y
+ + (float)lr.labelRect.height/2
+ - (float)lr.textRect.height/2);
+ lr.iconRect.y = (int)(viewRect.y
+ + (float)lr.labelRect.height/2
+ - (float)lr.iconRect.height/2);
+ } else if (verticalAlignment == SwingUtilities.CENTER) {
+ lr.textRect.y = (int)(viewRect.y
+ + (float)viewRect.height/2
+ - (float)lr.textRect.height/2);
+ lr.iconRect.y = (int)(viewRect.y
+ + (float)viewRect.height/2
+ - (float)lr.iconRect.height/2);
+ }
+ else if (verticalAlignment == SwingUtilities.BOTTOM) {
+ lr.textRect.y = (int)(viewRect.y
+ + viewRect.height
+ - (float)lr.labelRect.height/2
+ - (float)lr.textRect.height/2);
+ lr.iconRect.y = (int)(viewRect.y
+ + viewRect.height
+ - (float)lr.labelRect.height/2
+ - (float)lr.iconRect.height/2);
+ }
+ }
+
+ /**
+ * Sets labelRect Y coordinate
+ * taking into account the vertical alignment
+ */
+ private void calcLabelYPosition(LayoutResult lr) {
+ if (verticalAlignment == SwingUtilities.TOP) {
+ lr.labelRect.y = viewRect.y;
+ } else if (verticalAlignment == SwingUtilities.CENTER) {
+ lr.labelRect.y = (int)(viewRect.y
+ + (float)viewRect.height/2
+ - (float)lr.labelRect.height/2);
+ } else if (verticalAlignment == SwingUtilities.BOTTOM) {
+ lr.labelRect.y = viewRect.y + viewRect.height
+ - lr.labelRect.height;
+ }
+ }
+
+ /**
+ * Returns parent of this component if it is not a top-level menu
+ * Otherwise returns null.
+ * @param menuItem the menu item whose parent will be returned.
+ * @return parent of this component if it is not a top-level menu
+ * Otherwise returns null.
+ */
+ public static JComponent getMenuItemParent(JMenuItem menuItem) {
+ Container parent = menuItem.getParent();
+ if ((parent instanceof JComponent) &&
+ (!(menuItem instanceof JMenu) ||
+ !((JMenu)menuItem).isTopLevelMenu())) {
+ return (JComponent) parent;
+ } else {
+ return null;
+ }
+ }
+
+ public static void clearUsedParentClientProperties(JMenuItem menuItem) {
+ clearUsedClientProperties(getMenuItemParent(menuItem));
+ }
+
+ public static void clearUsedClientProperties(JComponent c) {
+ if (c != null) {
+ c.putClientProperty(MAX_ARROW_WIDTH, null);
+ c.putClientProperty(MAX_CHECK_WIDTH, null);
+ c.putClientProperty(MAX_ACC_WIDTH, null);
+ c.putClientProperty(MAX_TEXT_WIDTH, null);
+ c.putClientProperty(MAX_ICON_WIDTH, null);
+ c.putClientProperty(MAX_LABEL_WIDTH, null);
+ c.putClientProperty(BASICMENUITEMUI_MAX_TEXT_OFFSET, null);
+ }
+ }
+
+ /**
+ * Finds and returns maximal integer value in the given array.
+ * @param values array where the search will be performed.
+ * @return maximal vaule.
+ */
+ public static int max(int... values) {
+ int maxValue = Integer.MIN_VALUE;
+ for (int i : values) {
+ if (i > maxValue) {
+ maxValue = i;
+ }
+ }
+ return maxValue;
+ }
+
+ public static Rectangle createMaxRect() {
+ return new Rectangle(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE);
+ }
+
+ public static void addMaxWidth(RectSize size, int gap, Dimension result) {
+ if (size.maxWidth > 0) {
+ result.width += size.maxWidth + gap;
+ }
+ }
+
+ public static void addWidth(int width, int gap, Dimension result) {
+ if (width > 0) {
+ result.width += width + gap;
+ }
+ }
+
+ public JMenuItem getMenuItem() {
+ return mi;
+ }
+
+ public JComponent getMenuItemParent() {
+ return miParent;
+ }
+
+ public Font getFont() {
+ return font;
+ }
+
+ public Font getAccFont() {
+ return accFont;
+ }
+
+ public FontMetrics getFontMetrics() {
+ return fm;
+ }
+
+ public FontMetrics getAccFontMetrics() {
+ return accFm;
+ }
+
+ public Icon getIcon() {
+ return icon;
+ }
+
+ public Icon getCheckIcon() {
+ return checkIcon;
+ }
+
+ public Icon getArrowIcon() {
+ return arrowIcon;
+ }
+
+ public String getText() {
+ return text;
+ }
+
+ public String getAccText() {
+ return accText;
+ }
+
+ public boolean isColumnLayout() {
+ return isColumnLayout;
+ }
+
+ public boolean useCheckAndArrow() {
+ return useCheckAndArrow;
+ }
+
+ public boolean isLeftToRight() {
+ return isLeftToRight;
+ }
+
+ public boolean isTopLevelMenu() {
+ return isTopLevelMenu;
+ }
+
+ public View getHtmlView() {
+ return htmlView;
+ }
+
+ public int getVerticalAlignment() {
+ return verticalAlignment;
+ }
+
+ public int getHorizontalAlignment() {
+ return horizontalAlignment;
+ }
+
+ public int getVerticalTextPosition() {
+ return verticalTextPosition;
+ }
+
+ public int getHorizontalTextPosition() {
+ return horizontalTextPosition;
+ }
+
+ public int getGap() {
+ return gap;
+ }
+
+ public int getLeadingGap() {
+ return leadingGap;
+ }
+
+ public int getAfterCheckIconGap() {
+ return afterCheckIconGap;
+ }
+
+ public int getMinTextOffset() {
+ return minTextOffset;
+ }
+
+ public Rectangle getViewRect() {
+ return viewRect;
+ }
+
+ public RectSize getIconSize() {
+ return iconSize;
+ }
+
+ public RectSize getTextSize() {
+ return textSize;
+ }
+
+ public RectSize getAccSize() {
+ return accSize;
+ }
+
+ public RectSize getCheckSize() {
+ return checkSize;
+ }
+
+ public RectSize getArrowSize() {
+ return arrowSize;
+ }
+
+ public RectSize getLabelSize() {
+ return labelSize;
+ }
+
+ protected void setMenuItem(JMenuItem mi) {
+ this.mi = mi;
+ }
+
+ protected void setMenuItemParent(JComponent miParent) {
+ this.miParent = miParent;
+ }
+
+ protected void setFont(Font font) {
+ this.font = font;
+ }
+
+ protected void setAccFont(Font accFont) {
+ this.accFont = accFont;
+ }
+
+ protected void setFontMetrics(FontMetrics fm) {
+ this.fm = fm;
+ }
+
+ protected void setAccFontMetrics(FontMetrics accFm) {
+ this.accFm = accFm;
+ }
+
+ protected void setIcon(Icon icon) {
+ this.icon = icon;
+ }
+
+ protected void setCheckIcon(Icon checkIcon) {
+ this.checkIcon = checkIcon;
+ }
+
+ protected void setArrowIcon(Icon arrowIcon) {
+ this.arrowIcon = arrowIcon;
+ }
+
+ protected void setText(String text) {
+ this.text = text;
+ }
+
+ protected void setAccText(String accText) {
+ this.accText = accText;
+ }
+
+ protected void setColumnLayout(boolean columnLayout) {
+ isColumnLayout = columnLayout;
+ }
+
+ protected void setUseCheckAndArrow(boolean useCheckAndArrow) {
+ this.useCheckAndArrow = useCheckAndArrow;
+ }
+
+ protected void setLeftToRight(boolean leftToRight) {
+ isLeftToRight = leftToRight;
+ }
+
+ protected void setTopLevelMenu(boolean topLevelMenu) {
+ isTopLevelMenu = topLevelMenu;
+ }
+
+ protected void setHtmlView(View htmlView) {
+ this.htmlView = htmlView;
+ }
+
+ protected void setVerticalAlignment(int verticalAlignment) {
+ this.verticalAlignment = verticalAlignment;
+ }
+
+ protected void setHorizontalAlignment(int horizontalAlignment) {
+ this.horizontalAlignment = horizontalAlignment;
+ }
+
+ protected void setVerticalTextPosition(int verticalTextPosition) {
+ this.verticalTextPosition = verticalTextPosition;
+ }
+
+ protected void setHorizontalTextPosition(int horizontalTextPosition) {
+ this.horizontalTextPosition = horizontalTextPosition;
+ }
+
+ protected void setGap(int gap) {
+ this.gap = gap;
+ }
+
+ protected void setLeadingGap(int leadingGap) {
+ this.leadingGap = leadingGap;
+ }
+
+ protected void setAfterCheckIconGap(int afterCheckIconGap) {
+ this.afterCheckIconGap = afterCheckIconGap;
+ }
+
+ protected void setMinTextOffset(int minTextOffset) {
+ this.minTextOffset = minTextOffset;
+ }
+
+ protected void setViewRect(Rectangle viewRect) {
+ this.viewRect = viewRect;
+ }
+
+ protected void setIconSize(RectSize iconSize) {
+ this.iconSize = iconSize;
+ }
+
+ protected void setTextSize(RectSize textSize) {
+ this.textSize = textSize;
+ }
+
+ protected void setAccSize(RectSize accSize) {
+ this.accSize = accSize;
+ }
+
+ protected void setCheckSize(RectSize checkSize) {
+ this.checkSize = checkSize;
+ }
+
+ protected void setArrowSize(RectSize arrowSize) {
+ this.arrowSize = arrowSize;
+ }
+
+ protected void setLabelSize(RectSize labelSize) {
+ this.labelSize = labelSize;
+ }
+
+ /**
+ * Returns false if the component is a JMenu and it is a top
+ * level menu (on the menubar).
+ */
+ public static boolean useCheckAndArrow(JMenuItem menuItem) {
+ boolean b = true;
+ if ((menuItem instanceof JMenu) &&
+ (((JMenu) menuItem).isTopLevelMenu())) {
+ b = false;
+ }
+ return b;
+ }
+
+ public static class LayoutResult {
+ private Rectangle iconRect;
+ private Rectangle textRect;
+ private Rectangle accRect;
+ private Rectangle checkRect;
+ private Rectangle arrowRect;
+ private Rectangle labelRect;
+
+ public LayoutResult() {
+ iconRect = new Rectangle();
+ textRect = new Rectangle();
+ accRect = new Rectangle();
+ checkRect = new Rectangle();
+ arrowRect = new Rectangle();
+ labelRect = new Rectangle();
+ }
+
+ public LayoutResult(Rectangle iconRect, Rectangle textRect,
+ Rectangle accRect, Rectangle checkRect,
+ Rectangle arrowRect, Rectangle labelRect) {
+ this.iconRect = iconRect;
+ this.textRect = textRect;
+ this.accRect = accRect;
+ this.checkRect = checkRect;
+ this.arrowRect = arrowRect;
+ this.labelRect = labelRect;
+ }
+
+ public Rectangle getIconRect() {
+ return iconRect;
+ }
+
+ public void setIconRect(Rectangle iconRect) {
+ this.iconRect = iconRect;
+ }
+
+ public Rectangle getTextRect() {
+ return textRect;
+ }
+
+ public void setTextRect(Rectangle textRect) {
+ this.textRect = textRect;
+ }
+
+ public Rectangle getAccRect() {
+ return accRect;
+ }
+
+ public void setAccRect(Rectangle accRect) {
+ this.accRect = accRect;
+ }
+
+ public Rectangle getCheckRect() {
+ return checkRect;
+ }
+
+ public void setCheckRect(Rectangle checkRect) {
+ this.checkRect = checkRect;
+ }
+
+ public Rectangle getArrowRect() {
+ return arrowRect;
+ }
+
+ public void setArrowRect(Rectangle arrowRect) {
+ this.arrowRect = arrowRect;
+ }
+
+ public Rectangle getLabelRect() {
+ return labelRect;
+ }
+
+ public void setLabelRect(Rectangle labelRect) {
+ this.labelRect = labelRect;
+ }
+
+ public Map<String, Rectangle> getAllRects() {
+ Map<String, Rectangle> result = new HashMap<String, Rectangle>();
+ result.put("checkRect", checkRect);
+ result.put("iconRect", iconRect);
+ result.put("textRect", textRect);
+ result.put("accRect", accRect);
+ result.put("arrowRect", arrowRect);
+ result.put("labelRect", labelRect);
+ return result;
+ }
+ }
+
+ public static class ColumnAlignment {
+ private int checkAlignment;
+ private int iconAlignment;
+ private int textAlignment;
+ private int accAlignment;
+ private int arrowAlignment;
+
+ public static final ColumnAlignment LEFT_ALIGNMENT =
+ new ColumnAlignment(
+ SwingConstants.LEFT,
+ SwingConstants.LEFT,
+ SwingConstants.LEFT,
+ SwingConstants.LEFT,
+ SwingConstants.LEFT
+ );
+
+ public static final ColumnAlignment RIGHT_ALIGNMENT =
+ new ColumnAlignment(
+ SwingConstants.RIGHT,
+ SwingConstants.RIGHT,
+ SwingConstants.RIGHT,
+ SwingConstants.RIGHT,
+ SwingConstants.RIGHT
+ );
+
+ public ColumnAlignment(int checkAlignment, int iconAlignment,
+ int textAlignment, int accAlignment,
+ int arrowAlignment) {
+ this.checkAlignment = checkAlignment;
+ this.iconAlignment = iconAlignment;
+ this.textAlignment = textAlignment;
+ this.accAlignment = accAlignment;
+ this.arrowAlignment = arrowAlignment;
+ }
+
+ public int getCheckAlignment() {
+ return checkAlignment;
+ }
+
+ public int getIconAlignment() {
+ return iconAlignment;
+ }
+
+ public int getTextAlignment() {
+ return textAlignment;
+ }
+
+ public int getAccAlignment() {
+ return accAlignment;
+ }
+
+ public int getArrowAlignment() {
+ return arrowAlignment;
+ }
+ }
+
+ public static class RectSize {
+ private int width;
+ private int height;
+ private int origWidth;
+ private int maxWidth;
+
+ public RectSize() {
+ }
+
+ public RectSize(int width, int height, int origWidth, int maxWidth) {
+ this.width = width;
+ this.height = height;
+ this.origWidth = origWidth;
+ this.maxWidth = maxWidth;
+ }
+
+ public int getWidth() {
+ return width;
+ }
+
+ public int getHeight() {
+ return height;
+ }
+
+ public int getOrigWidth() {
+ return origWidth;
+ }
+
+ public int getMaxWidth() {
+ return maxWidth;
+ }
+
+ public void setWidth(int width) {
+ this.width = width;
+ }
+
+ public void setHeight(int height) {
+ this.height = height;
+ }
+
+ public void setOrigWidth(int origWidth) {
+ this.origWidth = origWidth;
+ }
+
+ public void setMaxWidth(int maxWidth) {
+ this.maxWidth = maxWidth;
+ }
+
+ public String toString() {
+ return "[w=" + width + ",h=" + height + ",ow="
+ + origWidth + ",mw=" + maxWidth + "]";
+ }
+ }
+}
--- a/jdk/src/share/classes/sun/swing/plaf/synth/DefaultSynthStyle.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/sun/swing/plaf/synth/DefaultSynthStyle.java Tue Aug 12 17:59:58 2008 -0700
@@ -44,7 +44,7 @@
* @author Scott Violet
*/
public class DefaultSynthStyle extends SynthStyle implements Cloneable {
- private static final Object PENDING = new String("Pending");
+ private static final String PENDING = "Pending";
/**
* Should the component be opaque?
@@ -690,8 +690,8 @@
StateInfo[] states = getStateInfo();
if (states != null) {
buf.append("states[");
- for (int i = 0; i < states.length; i++) {
- buf.append(states[i].toString()).append(',');
+ for (StateInfo state : states) {
+ buf.append(state.toString()).append(',');
}
buf.append(']').append(',');
}
@@ -888,7 +888,7 @@
* Returns the number of states that are similar between the
* ComponentState this StateInfo represents and val.
*/
- private final int getMatchCount(int val) {
+ private int getMatchCount(int val) {
// This comes from BigInteger.bitCnt
val &= state;
val -= (0xaaaaaaaa & val) >>> 1;
--- a/jdk/src/share/classes/sun/swing/plaf/synth/SynthFileChooserUIImpl.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/src/share/classes/sun/swing/plaf/synth/SynthFileChooserUIImpl.java Tue Aug 12 17:59:58 2008 -0700
@@ -735,7 +735,7 @@
* 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();
@@ -778,7 +778,7 @@
// 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) {
@@ -791,7 +791,7 @@
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);
@@ -799,7 +799,7 @@
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--) {
@@ -818,12 +818,12 @@
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;
}
@@ -940,8 +940,8 @@
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;
}
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/EventQueue/6638195/bug6638195.java Tue Aug 12 17:59:58 2008 -0700
@@ -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.
+ *
+ * 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.
+ */
+
+/* @test
+ *
+ * @bug 6638195
+ * @author Igor Kushnirskiy
+ * @summary tests if EventQueueDelegate.Delegate is invoked.
+ */
+
+import sun.awt.EventQueueDelegate;
+import com.sun.java.swing.SwingUtilities3;
+
+import java.util.*;
+import java.util.concurrent.*;
+import java.awt.*;
+
+public class bug6638195 {
+ public static void main(String[] args) throws Exception {
+ MyEventQueueDelegate delegate = new MyEventQueueDelegate();
+ EventQueueDelegate.setDelegate(delegate);
+ runTest(delegate);
+
+ delegate = new MyEventQueueDelegate();
+ SwingUtilities3.setEventQueueDelegate(getObjectMap(delegate));
+ runTest(delegate);
+ }
+
+ private static void runTest(MyEventQueueDelegate delegate) throws Exception {
+ EventQueue.invokeLater(
+ new Runnable() {
+ public void run() {
+ }
+ });
+ final CountDownLatch latch = new CountDownLatch(1);
+ EventQueue.invokeLater(
+ new Runnable() {
+ public void run() {
+ latch.countDown();
+ }
+ });
+ latch.await();
+ if (! delegate.allInvoked()) {
+ throw new RuntimeException("failed");
+ }
+ }
+
+ static Map<String, Map<String, Object>> getObjectMap(
+ final EventQueueDelegate.Delegate delegate) {
+ Map<String, Map<String, Object>> objectMap =
+ new HashMap<String, Map<String, Object>>();
+ Map<String, Object> methodMap;
+
+ final AWTEvent[] afterDispatchEventArgument = new AWTEvent[1];
+ final Object[] afterDispatchHandleArgument = new Object[1];
+ Callable<Void> afterDispatchCallable =
+ new Callable<Void>() {
+ public Void call() {
+ delegate.afterDispatch(afterDispatchEventArgument[0],
+ afterDispatchHandleArgument[0]);
+ return null;
+ }
+ };
+ methodMap = new HashMap<String, Object>();
+ methodMap.put("event", afterDispatchEventArgument);
+ methodMap.put("handle", afterDispatchHandleArgument);
+ methodMap.put("method", afterDispatchCallable);
+ objectMap.put("afterDispatch", methodMap);
+
+ final AWTEvent[] beforeDispatchEventArgument = new AWTEvent[1];
+ Callable<Object> beforeDispatchCallable =
+ new Callable<Object>() {
+ public Object call() {
+ return delegate.beforeDispatch(
+ beforeDispatchEventArgument[0]);
+ }
+ };
+ methodMap = new HashMap<String, Object>();
+ methodMap.put("event", beforeDispatchEventArgument);
+ methodMap.put("method", beforeDispatchCallable);
+ objectMap.put("beforeDispatch", methodMap);
+
+ final EventQueue[] getNextEventEventQueueArgument = new EventQueue[1];
+ Callable<AWTEvent> getNextEventCallable =
+ new Callable<AWTEvent>() {
+ public AWTEvent call() throws Exception {
+ return delegate.getNextEvent(
+ getNextEventEventQueueArgument[0]);
+ }
+ };
+ methodMap = new HashMap<String, Object>();
+ methodMap.put("eventQueue", getNextEventEventQueueArgument);
+ methodMap.put("method", getNextEventCallable);
+ objectMap.put("getNextEvent", methodMap);
+
+ return objectMap;
+ }
+ static class MyEventQueueDelegate implements EventQueueDelegate.Delegate {
+ private volatile boolean getNextEventInvoked = false;
+ private volatile boolean beforeDispatchInvoked = false;
+ private volatile boolean afterDispatchInvoked = false;
+ public AWTEvent getNextEvent(EventQueue eventQueue)
+ throws InterruptedException {
+ getNextEventInvoked = true;
+ return eventQueue.getNextEvent();
+ }
+ public Object beforeDispatch(AWTEvent event) {
+ beforeDispatchInvoked = true;
+ return null;
+ }
+ public void afterDispatch(AWTEvent event, Object handle) {
+ afterDispatchInvoked = true;
+ }
+ private boolean allInvoked() {
+ return getNextEventInvoked && beforeDispatchInvoked && afterDispatchInvoked;
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/beans/VetoableChangeSupport/Test6630275.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,81 @@
+/*
+ * 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.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 6630275
+ * @summary Tests VetoableChangeSupport specification
+ * @author Sergey Malenkov
+ */
+
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyVetoException;
+import java.beans.VetoableChangeListener;
+import java.beans.VetoableChangeSupport;
+
+public class Test6630275 {
+ private static final String PROPERTY = "property"; // NON-NLS: predefined property name
+
+ public static void main(String[] args) {
+ CheckListener first = new CheckListener(false);
+ CheckListener second = new CheckListener(true);
+ CheckListener third = new CheckListener(false);
+
+ VetoableChangeSupport vcs = new VetoableChangeSupport(Test6630275.class);
+ vcs.addVetoableChangeListener(first);
+ vcs.addVetoableChangeListener(PROPERTY, first);
+ vcs.addVetoableChangeListener(PROPERTY, second);
+ vcs.addVetoableChangeListener(PROPERTY, third);
+ try {
+ vcs.fireVetoableChange(PROPERTY, true, false);
+ } catch (PropertyVetoException exception) {
+ first.validate();
+ second.validate();
+ third.validate();
+ return; // expected exception
+ }
+ throw new Error("exception should be thrown");
+ }
+
+ private static class CheckListener implements VetoableChangeListener {
+ private final boolean veto;
+ private boolean odd; // even/odd check for notification
+
+ private CheckListener(boolean veto) {
+ this.veto = veto;
+ }
+
+ private void validate() {
+ if (this.veto != this.odd)
+ throw new Error(this.odd
+ ? "undo event expected"
+ : "unexpected undo event");
+ }
+
+ public void vetoableChange(PropertyChangeEvent event) throws PropertyVetoException {
+ this.odd = !this.odd;
+ if (this.veto)
+ throw new PropertyVetoException("disable all changes", event);
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/beans/XMLEncoder/Test4994637.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,58 @@
+/*
+ * 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.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 4994637
+ * @summary Tests custom map encoding
+ * @author Sergey Malenkov
+ */
+
+import java.util.HashMap;
+
+public final class Test4994637 extends AbstractTest<HashMap> {
+ public static void main(String[] args) {
+ new Test4994637().test(true);
+ }
+
+ @Override
+ protected CustomMap getObject() {
+ return new CustomMap();
+ }
+
+ @Override
+ protected CustomMap getAnotherObject() {
+ CustomMap map = new CustomMap();
+ map.clear();
+ map.put(null, "zero");
+ return map;
+ }
+
+ public static final class CustomMap extends HashMap<String, String> {
+ public CustomMap() {
+ put("1", "one");
+ put("2", "two");
+ put("3", "three");
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/beans/XMLEncoder/java_awt_BorderLayout.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,82 @@
+/*
+ * 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.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 4916852
+ * @summary Tests BorderLayout encoding
+ * @author Sergey Malenkov
+ */
+
+import java.awt.BorderLayout;
+import javax.swing.JLabel;
+
+public final class java_awt_BorderLayout extends AbstractTest<BorderLayout> {
+ 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,
+ };
+
+ public static void main(String[] args) {
+ new java_awt_BorderLayout().test(true);
+ }
+
+ @Override
+ protected BorderLayout getObject() {
+ BorderLayout layout = new BorderLayout();
+ update(layout, BorderLayout.EAST);
+ update(layout, BorderLayout.WEST);
+ update(layout, BorderLayout.NORTH);
+ update(layout, BorderLayout.SOUTH);
+ return layout;
+ }
+
+ @Override
+ protected BorderLayout getAnotherObject() {
+ BorderLayout layout = getObject();
+ update(layout, BorderLayout.CENTER);
+ return layout;
+ }
+
+ @Override
+ protected void validate(BorderLayout before, BorderLayout after) {
+ super.validate(before, after);
+
+ BeanValidator validator = new BeanValidator();
+ for (String constraint : CONSTRAINTS) {
+ validator.validate(before.getLayoutComponent(constraint),
+ after.getLayoutComponent(constraint));
+ }
+ }
+
+ private static void update(BorderLayout layout, String constraints) {
+ layout.addLayoutComponent(new JLabel(constraints), constraints);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/beans/XMLEncoder/java_awt_Component.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,58 @@
+/*
+ * 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.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 4916852
+ * @summary Tests Component encoding (background, foreground and font)
+ * @author Sergey Malenkov
+ */
+
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Font;
+
+public final class java_awt_Component extends AbstractTest<Component> {
+ public static void main(String[] args) {
+ new java_awt_Component().test(true);
+ }
+
+ @Override
+ protected Component getObject() {
+ Component component = new MyComponent();
+ component.setBackground(Color.WHITE);
+ component.setFont(new Font(null, Font.BOLD, 5));
+ return component;
+ }
+
+ @Override
+ protected Component getAnotherObject() {
+ Component component = new MyComponent();
+ component.setForeground(Color.BLACK);
+ component.setFont(new Font(null, Font.ITALIC, 6));
+ return component;
+ }
+
+ public static final class MyComponent extends Component {
+ }
+}
\ No newline at end of file
--- a/jdk/test/java/beans/XMLEncoder/java_util_HashMap.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/test/java/beans/XMLEncoder/java_util_HashMap.java Tue Aug 12 17:59:58 2008 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright 2006-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * Copyright 2006-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
@@ -23,7 +23,7 @@
/*
* @test
- * @bug 4631471 4921212
+ * @bug 4631471 4921212 4994637
* @summary Tests HashMap encoding
* @author Sergey Malenkov
*/
@@ -36,10 +36,17 @@
new java_util_HashMap().test(true);
}
+ @Override
protected Map<String, String> getObject() {
- return new HashMap<String, String>();
+ Map<String, String> map = new HashMap<String, String>();
+ map.put(null, null);
+ map.put("key", "value");
+ map.put("key-null", "null-value");
+ map.put("way", "remove");
+ return map;
}
+ @Override
protected Map<String, String> getAnotherObject() {
Map<String, String> map = new HashMap<String, String>();
map.put(null, "null-value");
@@ -48,6 +55,7 @@
return map;
}
+ @Override
protected void validate(Map<String, String> before, Map<String, String> after) {
super.validate(before, after);
validate(before);
@@ -55,10 +63,18 @@
}
private static void validate(Map<String, String> map) {
- if (!map.isEmpty()) {
+ switch (map.size()) {
+ case 3:
validate(map, null, "null-value");
validate(map, "key", "value");
validate(map, "key-null", null);
+ break;
+ case 4:
+ validate(map, null, null);
+ validate(map, "key", "value");
+ validate(map, "key-null", "null-value");
+ validate(map, "way", "remove");
+ break;
}
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JButton/6604281/bug6604281.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,76 @@
+/*
+ * 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.
+ *
+ * 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.
+ */
+
+/* @test
+ @bug 6604281
+ @summary NimbusL&F :Regression in Focus traversal in JFileChooser in pit build
+ @author Pavel Porvatov
+ @run main bug6604281
+*/
+
+import javax.swing.*;
+import javax.swing.plaf.IconUIResource;
+import javax.swing.plaf.synth.SynthLookAndFeel;
+import java.awt.*;
+import java.awt.image.BufferedImage;
+import java.lang.reflect.InvocationTargetException;
+
+public class bug6604281 {
+ public static void main(String[] args) throws InvocationTargetException, InterruptedException {
+ SwingUtilities.invokeAndWait(new Runnable() {
+ public void run() {
+ SynthLookAndFeel laf = new SynthLookAndFeel();
+ try {
+ UIManager.setLookAndFeel(laf);
+ } catch (Exception e) {
+ fail(e.getMessage());
+ }
+
+ // Prepare image
+ BufferedImage image = new BufferedImage(32, 32, BufferedImage.TYPE_INT_RGB);
+
+ Graphics2D graphics = (Graphics2D) image.getGraphics();
+
+ graphics.setColor(Color.BLUE);
+ graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
+ graphics.setColor(Color.RED);
+ graphics.drawLine(0, 0, image.getWidth(), image.getHeight());
+
+ // Use IconUIResource as an icon, because with ImageIcon bug is not reproduced
+ JButton button1 = new JButton(new IconUIResource(new ImageIcon(image)));
+
+ JButton button2 = new JButton(new IconUIResource(new ImageIcon(image)));
+
+ button2.setEnabled(false);
+
+ if (button1.getPreferredSize().getHeight() != button2.getPreferredSize().getHeight()) {
+ fail("Two similar buttons have different size");
+ }
+ }
+ });
+ }
+
+ private static void fail(String s) {
+ throw new RuntimeException("Test failed: " + s);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JColorChooser/Test4165217.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2003-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.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 4165217
+ * @summary Tests JColorChooser serialization
+ * @author Ilya Boyandin
+ */
+
+import java.awt.Color;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.Random;
+import javax.swing.JColorChooser;
+
+public class Test4165217 {
+ public static void main(String[] args) {
+ JColorChooser chooser = new JColorChooser();
+ chooser.setColor(new Color(new Random().nextInt()));
+
+ Color before = chooser.getColor();
+ Color after = copy(chooser).getColor();
+
+ if (!after.equals(before)) {
+ throw new Error("color is changed after serialization");
+ }
+ }
+
+ private static JColorChooser copy(JColorChooser chooser) {
+ try {
+ return (JColorChooser) deserialize(serialize(chooser));
+ }
+ catch (ClassNotFoundException exception) {
+ throw new Error("unexpected exception during class creation", exception);
+ }
+ catch (IOException exception) {
+ throw new Error("unexpected exception during serialization", exception);
+ }
+ }
+
+ private static byte[] serialize(Object object) throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+ oos.writeObject(object);
+ oos.flush();
+ return baos.toByteArray();
+ }
+
+ private static Object deserialize(byte[] array) throws IOException, ClassNotFoundException {
+ ByteArrayInputStream bais = new ByteArrayInputStream(array);
+ ObjectInputStream ois = new ObjectInputStream(bais);
+ return ois.readObject();
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JColorChooser/Test4177735.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,95 @@
+/*
+ * 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
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 4177735
+ * @summary Tests that JColorChooser leaves no threads when disposed
+ * @author Shannon Hickey
+ */
+
+import java.awt.Point;
+import javax.swing.JColorChooser;
+import javax.swing.JDialog;
+import javax.swing.SwingUtilities;
+import javax.swing.colorchooser.AbstractColorChooserPanel;
+
+public class Test4177735 implements Runnable {
+ private static final long DELAY = 1000L;
+
+ public static void main(String[] args) throws Exception {
+ JColorChooser chooser = new JColorChooser();
+ AbstractColorChooserPanel[] panels = chooser.getChooserPanels();
+ chooser.setChooserPanels(new AbstractColorChooserPanel[] { panels[1] });
+
+ JDialog dialog = show(chooser);
+ pause(DELAY);
+
+ dialog.dispose();
+ pause(DELAY);
+
+ Test4177735 test = new Test4177735();
+ SwingUtilities.invokeAndWait(test);
+ if (test.count != 0) {
+ throw new Error("JColorChooser leaves " + test.count + " threads running");
+ }
+ }
+
+ static JDialog show(JColorChooser chooser) {
+ JDialog dialog = JColorChooser.createDialog(null, null, false, chooser, null, null);
+ dialog.setVisible(true);
+ // block till displayed
+ Point point = null;
+ while (point == null) {
+ try {
+ point = dialog.getLocationOnScreen();
+ }
+ catch (IllegalStateException exception) {
+ pause(DELAY);
+ }
+ }
+ return dialog;
+ }
+
+ private static void pause(long delay) {
+ try {
+ Thread.sleep(delay);
+ }
+ catch (InterruptedException exception) {
+ }
+ }
+
+ private int count;
+
+ public void run() {
+ ThreadGroup group = Thread.currentThread().getThreadGroup();
+ Thread[] threads = new Thread[group.activeCount()];
+ int count = group.enumerate(threads, false);
+ for (int i = 0; i < count; i++) {
+ String name = threads[i].getName();
+ if ("SyntheticImageGenerator".equals(name)) { // NON-NLS: thread name
+ this.count++;
+ }
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JColorChooser/Test4193384.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2000-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.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 4193384 4200976
+ * @summary Tests the color conversions and the preview panel foreground color
+ * @author Mark Davidson
+ */
+
+import java.awt.Color;
+import javax.swing.JColorChooser;
+import javax.swing.JLabel;
+
+public class Test4193384 {
+ public static void main(String[] args) {
+ test(new Color[] {
+ new Color(11, 12, 13),
+ new Color(204, 0, 204),
+ new Color(0, 51, 51)
+ });
+ }
+
+ private static void test(Color[] colors) {
+ JLabel label = new JLabel("Preview Panel"); // NON-NLS: simple label
+
+ JColorChooser chooser = new JColorChooser();
+ chooser.setPreviewPanel(label);
+
+ float[] hsb = new float[3];
+ for (int i = 0; i < colors.length; i++) {
+ Color color = colors[i];
+ // Make sure sure that there wasn't a regression
+ // in java.awt.Color and the conversion methods
+ Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), hsb);
+ if (!color.equals(Color.getHSBColor(hsb[0], hsb[1], hsb[2]))) {
+ throw new Error("color conversion is failed");
+ }
+ // 4193384 regression test
+ if (!color.equals(new JColorChooser(color).getColor())) {
+ throw new Error("constructor sets incorrect initial color");
+ }
+ // 4200976 regression test
+ chooser.setColor(color);
+ if (!color.equals(label.getForeground())) {
+ throw new Error("a custom preview panel doesn't handle colors");
+ }
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JColorChooser/Test4234761.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,60 @@
+/*
+ * 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
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 4234761
+ * @summary RGB values sholdn't be changed in transition to HSB tab
+ * @author Oleg Mokhovikov
+ */
+
+import java.awt.Color;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import javax.swing.JColorChooser;
+import javax.swing.JDialog;
+import javax.swing.JTabbedPane;
+
+public class Test4234761 implements PropertyChangeListener {
+ private static final Color COLOR = new Color(51, 51, 51);
+
+ public static void main(String[] args) {
+ JColorChooser chooser = new JColorChooser(COLOR);
+ JDialog dialog = Test4177735.show(chooser);
+
+ PropertyChangeListener listener = new Test4234761();
+ chooser.addPropertyChangeListener("color", listener); // NON-NLS: property name
+
+ JTabbedPane tabbedPane = (JTabbedPane) chooser.getComponent(0);
+ tabbedPane.setSelectedIndex(1); // HSB tab index
+
+ if (!chooser.getColor().equals(COLOR)) {
+ listener.propertyChange(null);
+ }
+ dialog.dispose();
+ }
+
+ public void propertyChange(PropertyChangeEvent event) {
+ throw new Error("RGB value is changed after transition to HSB tab");
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JColorChooser/Test4380468.html Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,17 @@
+<html>
+<body>
+1. Click the HSB tab at the ColorChooser.
+2. Click in the lower left corner of the gradient palette
+ in order to select a color such that all three RGB values
+ are single digit colors (such as 0, 0, 0 or 5, 3, 1).
+3. Click another tab, then click back to the HSB tab.
+4. Now click the lighter colors that should have
+ 2 and 3 digit RGB values (in the upper right corner).
+
+If all digits of each RGB value are shown then test passes.
+If only the last digit of their values are shown then test fails.
+
+<applet width="500" height="400" code="Test4380468.class">
+</applet>
+</body>
+</html>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JColorChooser/Test4380468.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2000-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.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 4380468
+ * @summary JColorChooser's HSB panel should display all RGB digits
+ * @author Andrey Pikalev
+ * @run applet/manual=yesno Test4380468.html
+ */
+
+import java.awt.Color;
+import javax.swing.JApplet;
+import javax.swing.JColorChooser;
+
+public class Test4380468 extends JApplet {
+ public void init() {
+ add(new JColorChooser(Color.GREEN));
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JColorChooser/Test4461329.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,46 @@
+/*
+ * 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
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 4461329
+ * @summary Tests getPreviewPanel() and setPreviewPanel() methods
+ * @author Leif Samuelsson
+ */
+
+import javax.swing.JButton;
+import javax.swing.JColorChooser;
+
+public class Test4461329 {
+ public static void main(String[] args) {
+ JColorChooser chooser = new JColorChooser();
+ if (null == chooser.getPreviewPanel()) {
+ throw new Error("Failed: getPreviewPanel() returned null");
+ }
+ JButton button = new JButton("Color"); // NON-NLS: simple label
+ chooser.setPreviewPanel(button);
+ if (button != chooser.getPreviewPanel()) {
+ throw new Error("Failed in setPreviewPanel()");
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JColorChooser/Test4711996.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2003-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.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 4711996
+ * @summary Checks if IllegalArgumentException is thrown when updating JColorChooserUI
+ * @author Konstantin Eremin
+ */
+
+import javax.swing.JColorChooser;
+import javax.swing.colorchooser.AbstractColorChooserPanel;
+
+public class Test4711996 {
+ public static void main(String[] args) {
+ JColorChooser chooser = new JColorChooser();
+ AbstractColorChooserPanel[] panels = chooser.getChooserPanels();
+ chooser.removeChooserPanel(panels[0]);
+ chooser.updateUI();
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JColorChooser/Test4759306.html Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,8 @@
+<html>
+<body>
+If you see the preview panel, then test failed, otherwise it passed.
+
+<applet width="500" height="400" code="Test4759306.class">
+</applet>
+</body>
+</html>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JColorChooser/Test4759306.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,42 @@
+/*
+ * 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
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 4759306
+ * @summary Checks if JColorChooser.setPreviewPanel removes the old one
+ * @author Konstantin Eremin
+ @run applet/manual=yesno Test4759306.html
+ */
+
+import javax.swing.JApplet;
+import javax.swing.JColorChooser;
+import javax.swing.JPanel;
+
+public class Test4759306 extends JApplet {
+ public void init() {
+ JColorChooser chooser = new JColorChooser();
+ chooser.setPreviewPanel(new JPanel());
+ getContentPane().add(chooser);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JColorChooser/Test4759934.html Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,14 @@
+<html>
+<body>
+1. Press button "Show Dialog" at the frame "Test" and
+ the dialog with button "Show ColorChooser" should appears.
+2. Press button "Show ColorChooser" at the dialog "Dialog" and
+ the colorchooser should appears.
+3. Press the button "Cancel" of colorchooser.
+ If the focus will come to the frame "Test" then test fails.
+ If the focus will come to the dialog "Dialog" then test passes.
+
+<applet width="500" height="400" code="Test4759934.class">
+</applet>
+</body>
+</html>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JColorChooser/Test4759934.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2003-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.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 4759934
+ * @summary Tests windows activation problem
+ * @author Andrey Pikalev
+ * @run applet/manual=yesno Test4759934.html
+ */
+
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Window;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import javax.swing.JApplet;
+import javax.swing.JButton;
+import javax.swing.JColorChooser;
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+
+public class Test4759934 extends JApplet implements ActionListener {
+ private static final String CMD_DIALOG = "Show Dialog"; // NON-NLS: first button
+ private static final String CMD_CHOOSER = "Show ColorChooser"; // NON-NLS: second button
+
+ private final JFrame frame = new JFrame("Test"); // NON-NLS: frame title
+
+ public void init() {
+ show(this.frame, CMD_DIALOG);
+ }
+
+ public void actionPerformed(ActionEvent event) {
+ String command = event.getActionCommand();
+ if (CMD_DIALOG.equals(command)) {
+ JDialog dialog = new JDialog(this.frame, "Dialog"); // NON-NLS: dialog title
+ dialog.setLocation(200, 0);
+ show(dialog, CMD_CHOOSER);
+ }
+ else if (CMD_CHOOSER.equals(command)) {
+ Object source = event.getSource();
+ Component component = (source instanceof Component)
+ ? (Component) source
+ : null;
+
+ JColorChooser.showDialog(component, "ColorChooser", Color.BLUE); // NON-NLS: title
+ }
+ }
+
+ private void show(Window window, String command) {
+ JButton button = new JButton(command);
+ button.setActionCommand(command);
+ button.addActionListener(this);
+ button.setFont(button.getFont().deriveFont(64.0f));
+
+ window.add(button);
+ window.pack();
+ window.setVisible(true);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JColorChooser/Test4887836.html Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,9 @@
+<html>
+<body>
+If you do not see white area under swatches,
+then test passed, otherwise it failed.
+
+<applet width="500" height="400" code="Test4887836.class">
+</applet>
+</body>
+</html>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JColorChooser/Test4887836.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2003-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.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 4887836
+ * @summary Checks if no tooltip modification when no KeyStroke modifier
+ * @author Konstantin Eremin
+ * @run applet/manual=yesno Test4887836.html
+ */
+
+import java.awt.Color;
+import java.awt.Font;
+import javax.swing.JApplet;
+import javax.swing.JColorChooser;
+import javax.swing.UIManager;
+
+public class Test4887836 extends JApplet {
+ public void init() {
+ UIManager.put("Label.font", new Font("Perpetua", 0, 36)); // NON-NLS: property and font names
+ add(new JColorChooser(Color.LIGHT_GRAY));
+ }
+}
--- a/jdk/test/javax/swing/JColorChooser/Test6524757.java Thu Aug 07 09:42:31 2008 -0700
+++ b/jdk/test/javax/swing/JColorChooser/Test6524757.java Tue Aug 12 17:59:58 2008 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright 2007 Sun Microsystems, Inc. All Rights Reserved.
+ * Copyright 2007-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
@@ -34,14 +34,13 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
-import javax.swing.JButton;
+import javax.swing.AbstractButton;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
-import javax.swing.JRadioButton;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.colorchooser.AbstractColorChooserPanel;
@@ -59,31 +58,41 @@
"ColorChooser.swatchesNameText", // NON-NLS: string key from DefaultSwatchChooserPanel
"ColorChooser.swatchesMnemonic", // NON-NLS: string key from DefaultSwatchChooserPanel:int
- "ColorChooser.swatchesDisplayedMnemonicIndex", // NON-NLS: int key from DefaultSwatchChooserPanel
"ColorChooser.swatchesSwatchSize", // NON-NLS: dimension key from DefaultSwatchChooserPanel
"ColorChooser.swatchesRecentText", // NON-NLS: string key from DefaultSwatchChooserPanel
"ColorChooser.swatchesRecentSwatchSize", // NON-NLS: dimension key from DefaultSwatchChooserPanel
//NotAvail: "ColorChooser.swatchesDefaultRecentColor", // NON-NLS: color key from DefaultSwatchChooserPanel
- "ColorChooser.hsbNameText", // NON-NLS: string key from DefaultHSBChooserPanel
- "ColorChooser.hsbMnemonic", // NON-NLS: int key from DefaultHSBChooserPanel
- "ColorChooser.hsbDisplayedMnemonicIndex", // NON-NLS: int key from DefaultHSBChooserPanel
- "ColorChooser.hsbHueText", // NON-NLS: string key from DefaultHSBChooserPanel
- "ColorChooser.hsbSaturationText", // NON-NLS: string key from DefaultHSBChooserPanel
- "ColorChooser.hsbBrightnessText", // NON-NLS: string key from DefaultHSBChooserPanel
- "ColorChooser.hsbRedText", // NON-NLS: string key from DefaultHSBChooserPanel
- "ColorChooser.hsbGreenText", // NON-NLS: string key from DefaultHSBChooserPanel
- "ColorChooser.hsbBlueText", // NON-NLS: string key from DefaultHSBChooserPanel
+ "ColorChooser.hsvNameText", // NON-NLS: string key from HSV ColorChooserPanel
+ "ColorChooser.hsvMnemonic", // NON-NLS: int key from HSV ColorChooserPanel
+ "ColorChooser.hsvHueText", // NON-NLS: string key from HSV ColorChooserPanel
+ "ColorChooser.hsvSaturationText", // NON-NLS: string key from HSV ColorChooserPanel
+ "ColorChooser.hsvValueText", // NON-NLS: string key from HSV ColorChooserPanel
+ "ColorChooser.hsvTransparencyText", // NON-NLS: string key from HSV ColorChooserPanel
+
+ "ColorChooser.hslNameText", // NON-NLS: string key from HSV ColorChooserPanel
+ "ColorChooser.hslMnemonic", // NON-NLS: int key from HSV ColorChooserPanel
+ "ColorChooser.hslHueText", // NON-NLS: string key from HSV ColorChooserPanel
+ "ColorChooser.hslSaturationText", // NON-NLS: string key from HSV ColorChooserPanel
+ "ColorChooser.hslLightnessText", // NON-NLS: string key from HSV ColorChooserPanel
+ "ColorChooser.hslTransparencyText", // NON-NLS: string key from HSV ColorChooserPanel
- "ColorChooser.rgbNameText", // NON-NLS: string key from DefaultRGBChooserPanel
- "ColorChooser.rgbMnemonic", // NON-NLS: int key from DefaultRGBChooserPanel
- "ColorChooser.rgbDisplayedMnemonicIndex", // NON-NLS: int key from DefaultRGBChooserPanel
- "ColorChooser.rgbRedText", // NON-NLS: string key from DefaultRGBChooserPanel
- "ColorChooser.rgbGreenText", // NON-NLS: string key from DefaultRGBChooserPanel
- "ColorChooser.rgbBlueText", // NON-NLS: string key from DefaultRGBChooserPanel
- "ColorChooser.rgbRedMnemonic", // NON-NLS: int key from DefaultRGBChooserPanel
- "ColorChooser.rgbGreenMnemonic", // NON-NLS: int key from DefaultRGBChooserPanel
- "ColorChooser.rgbBlueMnemonic", // NON-NLS: int key from DefaultRGBChooserPanel
+ "ColorChooser.rgbNameText", // NON-NLS: string key from HSV ColorChooserPanel
+ "ColorChooser.rgbMnemonic", // NON-NLS: int key from HSV ColorChooserPanel
+ "ColorChooser.rgbRedText", // NON-NLS: string key from HSV ColorChooserPanel
+ "ColorChooser.rgbGreenText", // NON-NLS: string key from HSV ColorChooserPanel
+ "ColorChooser.rgbBlueText", // NON-NLS: string key from HSV ColorChooserPanel
+ "ColorChooser.rgbAlphaText", // NON-NLS: string key from HSV ColorChooserPanel
+ "ColorChooser.rgbHexCodeText", // NON-NLS: string key from HSV ColorChooserPanel
+ "ColorChooser.rgbHexCodeMnemonic", // NON-NLS: int key from HSV ColorChooserPanel
+
+ "ColorChooser.cmykNameText", // NON-NLS: string key from HSV ColorChooserPanel
+ "ColorChooser.cmykMnemonic", // NON-NLS: int key from HSV ColorChooserPanel
+ "ColorChooser.cmykCyanText", // NON-NLS: string key from HSV ColorChooserPanel
+ "ColorChooser.cmykMagentaText", // NON-NLS: string key from HSV ColorChooserPanel
+ "ColorChooser.cmykYellowText", // NON-NLS: string key from HSV ColorChooserPanel
+ "ColorChooser.cmykBlackText", // NON-NLS: string key from HSV ColorChooserPanel
+ "ColorChooser.cmykAlphaText", // NON-NLS: string key from HSV ColorChooserPanel
};
private static final Object[] KOREAN = convert(Locale.KOREAN, KEYS);
private static final Object[] FRENCH = convert(Locale.FRENCH, KEYS);
@@ -91,19 +100,15 @@
public static void main(String[] args) {
// it affects Swing because it is not initialized
Locale.setDefault(Locale.KOREAN);
- Object[] korean = create();
+ validate(KOREAN, create());
// it does not affect Swing because it is initialized
Locale.setDefault(Locale.CANADA);
- Object[] canada = create();
+ validate(KOREAN, create());
// it definitely should affect Swing
JComponent.setDefaultLocale(Locale.FRENCH);
- Object[] french = create();
-
- validate(KOREAN, korean);
- validate(KOREAN, canada);
- validate(FRENCH, french);
+ validate(FRENCH, create());
}
private static void validate(Object[] expected, Object[] actual) {
@@ -153,10 +158,47 @@
// process all values
List<Object> list = new ArrayList<Object>(KEYS.length);
- addMain(list, dialog);
- addSwatch(list, chooser);
- addHSB(list, chooser);
- addRGB(list, chooser);
+
+ Component component = getC(getC(dialog.getLayeredPane(), 0), 1);
+ AbstractButton ok = (AbstractButton) getC(component, 0);
+ AbstractButton cancel = (AbstractButton) getC(component, 1);
+ AbstractButton reset = (AbstractButton) getC(component, 2);
+ list.add(ok.getText());
+ list.add(cancel.getText());
+ list.add(reset.getText());
+ list.add(Integer.valueOf(reset.getMnemonic()));
+
+ for (int i = 0; i < 5; i++) {
+ AbstractColorChooserPanel panel = (AbstractColorChooserPanel) getC(getC(getC(chooser, 0), i), 0);
+ list.add(panel.getDisplayName());
+ list.add(Integer.valueOf(panel.getMnemonic()));
+ if (i == 0) {
+ JLabel label = (JLabel) getC(getC(panel, 0), 1);
+ JPanel upper = (JPanel) getC(getC(getC(panel, 0), 0), 0);
+ JPanel lower = (JPanel) getC(getC(getC(panel, 0), 2), 0);
+ addSize(list, upper, 1, 1, 31, 9);
+ list.add(label.getText());
+ addSize(list, lower, 1, 1, 5, 7);
+ }
+ else {
+ Component container = getC(panel, 0);
+ for (int j = 0; j < 3; j++) {
+ AbstractButton button = (AbstractButton) getC(container, j);
+ list.add(button.getText());
+ }
+ JLabel label = (JLabel) getC(container, 3);
+ list.add(label.getText());
+ if (i == 4) {
+ label = (JLabel) getC(container, 4);
+ list.add(label.getText());
+ }
+ if (i == 3) {
+ label = (JLabel) getC(panel, 1);
+ list.add(label.getText());
+ list.add(Integer.valueOf(label.getDisplayedMnemonic()));
+ }
+ }
+ }
// close dialog
dialog.setVisible(false);
@@ -169,56 +211,6 @@
return list.toArray();
}
- private static void addMain(List<Object> list, JDialog dialog) {
- Component component = getC(getC(dialog.getLayeredPane(), 0), 1);
- JButton ok = (JButton) getC(component, 0);
- JButton cancel = (JButton) getC(component, 1);
- JButton reset = (JButton) getC(component, 2);
- list.add(ok.getText());
- list.add(cancel.getText());
- list.add(reset.getText());
- list.add(Integer.valueOf(reset.getMnemonic()));
- }
-
- private static void addSwatch(List<Object> list, JColorChooser chooser) {
- Component component = addPanel(list, chooser, 0);
- JLabel label = (JLabel) getC(getC(component, 0), 1);
- JPanel upper = (JPanel) getC(getC(getC(component, 0), 0), 0);
- JPanel lower = (JPanel) getC(getC(getC(component, 0), 2), 0);
- addSize(list, upper, 1, 1, 31, 9);
- list.add(label.getText());
- addSize(list, lower, 1, 1, 5, 7);
- }
-
- private static void addHSB(List<Object> list, JColorChooser chooser) {
- Component component = addPanel(list, chooser, 1);
- JRadioButton h = (JRadioButton) getC(getC(getC(component, 1), 0), 0);
- JRadioButton s = (JRadioButton) getC(getC(getC(component, 1), 0), 2);
- JRadioButton b = (JRadioButton) getC(getC(getC(component, 1), 0), 4);
- list.add(h.getText());
- list.add(s.getText());
- list.add(b.getText());
- JLabel red = (JLabel) getC(getC(getC(component, 1), 2), 0);
- JLabel green = (JLabel) getC(getC(getC(component, 1), 2), 2);
- JLabel blue = (JLabel) getC(getC(getC(component, 1), 2), 4);
- list.add(red.getText());
- list.add(green.getText());
- list.add(blue.getText());
- }
-
- private static void addRGB(List<Object> list, JColorChooser chooser) {
- Component component = addPanel(list, chooser, 2);
- JLabel red = (JLabel) getC(getC(component, 0), 0);
- JLabel green = (JLabel) getC(getC(component, 0), 3);
- JLabel blue = (JLabel) getC(getC(component, 0), 6);
- list.add(red.getText());
- list.add(green.getText());
- list.add(blue.getText());
- list.add(Integer.valueOf(red.getDisplayedMnemonic()));
- list.add(Integer.valueOf(green.getDisplayedMnemonic()));
- list.add(Integer.valueOf(blue.getDisplayedMnemonic()));
- }
-
private static void addSize(List<Object> list, Component component, int x, int y, int w, int h) {
Dimension size = component.getPreferredSize();
int width = (size.width + 1) / w - x;
@@ -226,14 +218,6 @@
list.add(new Dimension(width, height));
}
- private static Component addPanel(List<Object> list, JColorChooser chooser, int index) {
- AbstractColorChooserPanel panel = (AbstractColorChooserPanel) getC(getC(getC(chooser, 0), index), 0);
- list.add(panel.getDisplayName());
- list.add(Integer.valueOf(panel.getMnemonic()));
- list.add(Integer.valueOf(panel.getDisplayedMnemonicIndex()));
- return panel;
- }
-
private static Component getC(Component component, int index) {
Container container = (Container) component;
return container.getComponent(index);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JColorChooser/Test6559154.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,75 @@
+/*
+ * 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.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 6559154
+ * @summary Tests EDT hanging
+ * @author Sergey Malenkov
+ */
+
+import java.awt.Component;
+import java.awt.Container;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import javax.swing.JColorChooser;
+import javax.swing.JDialog;
+import javax.swing.SwingUtilities;
+import javax.swing.Timer;
+
+public class Test6559154 implements ActionListener, Runnable {
+
+ private JDialog dialog;
+
+ public void actionPerformed(ActionEvent event) {
+ if (this.dialog != null) {
+ this.dialog.dispose();
+ }
+ }
+
+ public void run() {
+ Timer timer = new Timer(1000, this);
+ timer.setRepeats(false);
+ timer.start();
+
+ JColorChooser chooser = new JColorChooser();
+ setEnabledRecursive(chooser, false);
+
+ this.dialog = new JDialog();
+ this.dialog.add(chooser);
+ this.dialog.setVisible(true);
+ }
+
+ private static void setEnabledRecursive(Container container, boolean enabled) {
+ for (Component component : container.getComponents()) {
+ component.setEnabled(enabled);
+ if (component instanceof Container) {
+ setEnabledRecursive((Container) component, enabled);
+ }
+ }
+ }
+
+ public static void main(String[] args) throws Exception {
+ SwingUtilities.invokeAndWait(new Test6559154());
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JColorChooser/Test6707406.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,63 @@
+/*
+ * 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.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 6707406
+ * @summary Tests color chooser with invalid UI
+ * @author Sergey Malenkov
+ */
+
+import java.awt.Color;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import javax.swing.JColorChooser;
+import javax.swing.UIManager;
+import javax.swing.UIManager.LookAndFeelInfo;
+import javax.swing.plaf.basic.BasicColorChooserUI;
+
+public class Test6707406 extends BasicColorChooserUI implements PropertyChangeListener {
+ public static void main(String[] args) throws Exception {
+ test();
+ for (LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
+ System.out.println(laf.getName());
+ UIManager.setLookAndFeel(laf.getClassName());
+ test();
+ }
+ }
+
+ private static void test() {
+ JColorChooser chooser = new JColorChooser();
+ chooser.getUI().uninstallUI(chooser);
+ new Test6707406().installUI(chooser);
+ chooser.getSelectionModel().setSelectedColor(Color.BLUE);
+ }
+
+ @Override
+ protected PropertyChangeListener createPropertyChangeListener() {
+ return this;
+ }
+
+ public void propertyChange(PropertyChangeEvent event) {
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JComboBox/6607130/bug6607130.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,149 @@
+/*
+ * 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.
+ *
+ * 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.
+ */
+
+/* @test
+ * @bug 6607130
+ * @summary Checks that JComboBox cell editor is hidden if the same
+ * item is selected with keyboard.
+ * Also checks that JComboBox cell editor is hidden if F2 and then
+ * ENTER were pressed.
+ * @author Mikhail Lapshin
+ */
+
+import sun.awt.SunToolkit;
+
+import javax.swing.*;
+import javax.swing.table.DefaultTableModel;
+import java.awt.*;
+import java.awt.event.KeyEvent;
+
+public class bug6607130 {
+ private JFrame frame;
+ private JComboBox cb;
+ private Robot robot;
+
+ public static void main(String[] args) throws Exception {
+ final bug6607130 test = new bug6607130();
+ try {
+ SwingUtilities.invokeAndWait(new Runnable() {
+ public void run() {
+ test.setupUI();
+ }
+ });
+ test.test();
+ } finally {
+ if (test.frame != null) {
+ test.frame.dispose();
+ }
+ }
+ }
+
+ public bug6607130() throws AWTException {
+ robot = new Robot();
+ }
+
+ private void setupUI() {
+ frame = new JFrame();
+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+
+ DefaultTableModel model = new DefaultTableModel(1, 1);
+ JTable table = new JTable(model);
+
+ cb = new JComboBox(new String[]{"one", "two", "three"});
+ table.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(cb));
+ frame.add(table);
+
+ frame.pack();
+ frame.setLocationRelativeTo(null);
+ frame.setVisible(true);
+ }
+
+ private void test() throws Exception {
+ realSync();
+ test1();
+ realSync();
+ checkResult("First test");
+ test2();
+ realSync();
+ checkResult("Second test");
+ }
+
+ private void test1() throws Exception {
+ // Select 'one'
+ hitKey(KeyEvent.VK_TAB);
+ realSync();
+ hitKey(KeyEvent.VK_F2);
+ realSync();
+ hitKey(KeyEvent.VK_DOWN);
+ realSync();
+ hitKey(KeyEvent.VK_DOWN);
+ realSync();
+ hitKey(KeyEvent.VK_ENTER);
+ realSync();
+
+ // Select 'one' again
+ hitKey(KeyEvent.VK_F2);
+ realSync();
+ hitKey(KeyEvent.VK_DOWN);
+ realSync();
+ hitKey(KeyEvent.VK_ENTER);
+ realSync();
+ }
+
+ private void test2() throws Exception {
+ // Press F2 and then press ENTER
+ // Editor should be shown and then closed
+ hitKey(KeyEvent.VK_F2);
+ realSync();
+ hitKey(KeyEvent.VK_ENTER);
+ realSync();
+ }
+
+ private void checkResult(String testName) {
+ if (!cb.isShowing()) {
+ System.out.println(testName + " passed");
+ } else {
+ System.out.println(testName + " failed");
+ throw new RuntimeException("JComboBox is showing " +
+ "after item selection.");
+ }
+ }
+
+ private static void realSync() {
+ ((SunToolkit) (Toolkit.getDefaultToolkit())).realSync();
+ }
+
+ public void hitKey(int keycode) {
+ robot.keyPress(keycode);
+ robot.keyRelease(keycode);
+ delay();
+ }
+
+ private void delay() {
+ try {
+ Thread.sleep(1000);
+ } catch(InterruptedException ie) {
+ ie.printStackTrace();
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JInternalFrame/6647340/bug6647340.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,146 @@
+/*
+ * 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.
+ *
+ * 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.
+ */
+
+/* @test
+ * @bug 6647340
+ * @summary Checks that iconified internal frame follows
+ * the main frame borders properly.
+ * @author Mikhail Lapshin
+ */
+
+import sun.awt.SunToolkit;
+
+import javax.swing.*;
+import java.awt.*;
+import java.beans.PropertyVetoException;
+
+public class bug6647340 {
+ private JFrame frame;
+ private Point location;
+ private JInternalFrame jif;
+
+ public static void main(String[] args) throws Exception {
+ final bug6647340 test = new bug6647340();
+ try {
+ SwingUtilities.invokeAndWait(new Runnable() {
+ public void run() {
+ test.setupUI();
+ }
+ });
+ test.test();
+ } finally {
+ if (test.frame != null) {
+ test.frame.dispose();
+ }
+ }
+ }
+
+ private void setupUI() {
+ frame = new JFrame();
+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+
+ JDesktopPane desktop = new JDesktopPane();
+ frame.add(desktop);
+
+ jif = new JInternalFrame("Internal Frame", true, true, true, true);
+ jif.setBounds(20, 20, 200, 100);
+ desktop.add(jif);
+ jif.setVisible(true);
+
+ Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
+ frame.setBounds((screen.width - 400) / 2, (screen.height - 400) / 2, 400, 400);
+ frame.setLocationRelativeTo(null);
+ frame.setVisible(true);
+ }
+
+ private void test() throws Exception {
+ realSync();
+ test1();
+ realSync();
+ check1();
+ realSync();
+ test2();
+ realSync();
+ check2();
+ }
+
+ private void test1() throws Exception {
+ SwingUtilities.invokeAndWait(new Runnable() {
+ public void run() {
+ setIcon(true);
+ location = jif.getDesktopIcon().getLocation();
+ Dimension size = frame.getSize();
+ frame.setSize(size.width + 100, size.height + 100);
+ }
+ });
+ }
+
+ private void test2() throws Exception {
+ SwingUtilities.invokeAndWait(new Runnable() {
+ public void run() {
+ setIcon(false);
+ }
+ });
+ realSync();
+ SwingUtilities.invokeAndWait(new Runnable() {
+ public void run() {
+ Dimension size = frame.getSize();
+ frame.setSize(size.width - 100, size.height - 100);
+ }
+ });
+ realSync();
+ SwingUtilities.invokeAndWait(new Runnable() {
+ public void run() {
+ setIcon(true);
+ }
+ });
+ }
+
+ private void check1() {
+ if (!jif.getDesktopIcon().getLocation().equals(location)) {
+ System.out.println("First test passed");
+ } else {
+ throw new RuntimeException("Icon isn't shifted with the frame bounds");
+ }
+ }
+
+ private void check2() {
+ if (jif.getDesktopIcon().getLocation().equals(location)) {
+ System.out.println("Second test passed");
+ } else {
+ throw new RuntimeException("Icon isn't located near the frame bottom");
+ }
+ }
+
+ private static void realSync() {
+ ((SunToolkit) (Toolkit.getDefaultToolkit())).realSync();
+ }
+
+ private void setIcon(boolean b) {
+ try {
+ jif.setIcon(b);
+ } catch (PropertyVetoException e) {
+ e.printStackTrace();
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JInternalFrame/6725409/bug6725409.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,162 @@
+/*
+ * 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.
+ *
+ * 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.
+ */
+
+/* @test
+ * @bug 6725409
+ * @summary Checks that JInternalFrame's system menu
+ * can be localized during run-time
+ * @author Mikhail Lapshin
+ */
+
+import javax.swing.*;
+import java.awt.*;
+
+public class bug6725409 {
+ private JFrame frame;
+ private JInternalFrame iFrame;
+ private TestTitlePane testTitlePane;
+ private boolean passed;
+
+ public static void main(String[] args) throws Exception {
+ try {
+ UIManager.setLookAndFeel(
+ new com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel());
+ } catch(UnsupportedLookAndFeelException e) {
+ System.out.println("The test is for Windows LaF only");
+ System.exit(0);
+ }
+
+ final bug6725409 bug6725409 = new bug6725409();
+ try {
+ SwingUtilities.invokeAndWait(new Runnable() {
+ public void run() {
+ bug6725409.setupUIStep1();
+ }
+ });
+ realSync();
+ SwingUtilities.invokeAndWait(new Runnable() {
+ public void run() {
+ bug6725409.setupUIStep2();
+ }
+ });
+ realSync();
+ SwingUtilities.invokeAndWait(new Runnable() {
+ public void run() {
+ bug6725409.test();
+ }
+ });
+ realSync();
+ bug6725409.checkResult();
+ } finally {
+ if (bug6725409.frame != null) {
+ bug6725409.frame.dispose();
+ }
+ }
+ }
+
+ private void setupUIStep1() {
+ frame = new JFrame();
+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+
+ JDesktopPane desktop = new JDesktopPane();
+ iFrame = new JInternalFrame("Internal Frame", true, true, true, true);
+ iFrame.setSize(200, 100);
+ desktop.add(iFrame);
+ frame.add(desktop);
+ iFrame.setVisible(true);
+
+ frame.setSize(500, 300);
+ frame.setLocationRelativeTo(null);
+ frame.setVisible(true);
+ }
+
+ private void setupUIStep2() {
+ UIManager.put("InternalFrameTitlePane.restoreButtonText",
+ "CUSTOM.restoreButtonText");
+ UIManager.put("InternalFrameTitlePane.moveButtonText",
+ "CUSTOM.moveButtonText");
+ UIManager.put("InternalFrameTitlePane.sizeButtonText",
+ "CUSTOM.sizeButtonText");
+ UIManager.put("InternalFrameTitlePane.minimizeButtonText",
+ "CUSTOM.minimizeButtonText");
+ UIManager.put("InternalFrameTitlePane.maximizeButtonText",
+ "CUSTOM.maximizeButtonText");
+ UIManager.put("InternalFrameTitlePane.closeButtonText",
+ "CUSTOM.closeButtonText");
+ SwingUtilities.updateComponentTreeUI(frame);
+ }
+
+ // The test depends on the order of the menu items in
+ // WindowsInternalFrameTitlePane.systemPopupMenu
+ private void test() {
+ testTitlePane = new TestTitlePane(iFrame);
+ passed = true;
+ checkMenuItemText(0, "CUSTOM.restoreButtonText");
+ checkMenuItemText(1, "CUSTOM.moveButtonText");
+ checkMenuItemText(2, "CUSTOM.sizeButtonText");
+ checkMenuItemText(3, "CUSTOM.minimizeButtonText");
+ checkMenuItemText(4, "CUSTOM.maximizeButtonText");
+ // Skip separator
+ checkMenuItemText(6, "CUSTOM.closeButtonText");
+ }
+
+ private void checkMenuItemText(int index, String text) {
+ JMenuItem menuItem = (JMenuItem)
+ testTitlePane.getSystemPopupMenu().getComponent(index);
+ if (!text.equals(menuItem.getText())) {
+ passed = false;
+ }
+ }
+
+ private void checkResult() {
+ if (passed) {
+ System.out.println("Test passed");
+ } else {
+ throw new RuntimeException("Unable to localize " +
+ "JInternalFrame's system menu during run-time");
+ }
+ }
+
+ private static void realSync() {
+ ((sun.awt.SunToolkit) (Toolkit.getDefaultToolkit())).realSync();
+ }
+
+ // Extend WindowsInternalFrameTitlePane to get access to systemPopupMenu
+ private class TestTitlePane extends
+ com.sun.java.swing.plaf.windows.WindowsInternalFrameTitlePane {
+ private JPopupMenu systemPopupMenu;
+
+ public TestTitlePane(JInternalFrame f) {
+ super(f);
+ }
+
+ public JPopupMenu getSystemPopupMenu() {
+ return systemPopupMenu;
+ }
+
+ protected void addSystemMenuItems(JPopupMenu menu) {
+ super.addSystemMenuItems(menu);
+ systemPopupMenu = menu;
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/RepaintManager/6608456/bug6608456.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,162 @@
+/*
+ * Copyright 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.
+ *
+ * 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.
+ */
+
+/* @test
+ *
+ * @bug 6608456
+ * @author Igor Kushnirskiy
+ * @summary tests if delegate RepaintManager gets invoked.
+ */
+
+import java.awt.*;
+import java.lang.reflect.Method;
+import java.util.concurrent.Callable;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.TimeUnit;
+
+import javax.swing.JComponent;
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.RepaintManager;
+import javax.swing.SwingUtilities;
+
+
+
+public class bug6608456 {
+ private static final TestFuture testFuture = new TestFuture();
+ public static void main(String[] args) throws Exception {
+ final JComponent component = invokeAndWait(
+ new Callable<JComponent>() {
+ public JComponent call() throws Exception {
+ RepaintManager.setCurrentManager(new TestRepaintManager());
+ JFrame frame = new JFrame("test");
+ frame.setLayout(new FlowLayout());
+ JButton button = new JButton("default");
+
+ frame.add(button);
+ button = new JButton("delegate");
+ if ( ! registerDelegate(
+ button, new TestRepaintManager())) {
+ return null;
+ }
+ frame.add(button);
+ frame.pack();
+ frame.setVisible(true);
+ return button;
+ }
+ });
+ if (component == null) {
+ throw new RuntimeException("failed. can not register delegate");
+ }
+ blockTillDisplayed(component);
+ // trigger repaint for delegate RepaintManager
+ invokeAndWait(
+ new Callable<Void>() {
+ public Void call() {
+ component.repaint();
+ return null;
+ }
+ });
+ try {
+ if (testFuture.get(10, TimeUnit.SECONDS)) {
+ // passed
+ }
+ } catch (Exception e) {
+ throw new RuntimeException("failed", e);
+ } finally {
+ JFrame frame = (JFrame) SwingUtilities
+ .getAncestorOfClass(JFrame.class, component);
+ if (frame != null) {
+ frame.dispose();
+ }
+ }
+ }
+ static class TestRepaintManager extends RepaintManager {
+ @Override
+ public void addDirtyRegion(JComponent c, int x, int y, int w, int h) {
+ if (RepaintManager.currentManager(c) == this) {
+ testFuture.defaultCalled();
+ } else {
+ testFuture.delegateCalled();
+ }
+ super.addDirtyRegion(c, x, y, w, h);
+ }
+ }
+ static class TestFuture extends FutureTask<Boolean> {
+ private volatile boolean defaultCalled = false;
+ private volatile boolean delegateCalled = false;
+ public TestFuture() {
+ super(new Callable<Boolean>() {
+ public Boolean call() {
+ return null;
+ }
+ });
+ }
+ public void defaultCalled() {
+ defaultCalled = true;
+ updateState();
+ }
+ public void delegateCalled() {
+ delegateCalled = true;
+ updateState();
+ }
+ private void updateState() {
+ if (defaultCalled && delegateCalled) {
+ set(Boolean.TRUE);
+ }
+ }
+ }
+
+ private static boolean registerDelegate(JComponent c,
+ RepaintManager repaintManager) {
+ boolean rv = false;
+ try {
+ Class<?> clazz = Class.forName("com.sun.java.swing.SwingUtilities3");
+ Method method = clazz.getMethod("setDelegateRepaintManager",
+ JComponent.class, RepaintManager.class);
+ method.invoke(clazz, c, repaintManager);
+ rv = true;
+ } catch (Exception ignore) {
+ }
+ return rv;
+ }
+ static <T> T invokeAndWait(Callable<T> callable) throws Exception {
+ FutureTask<T> future = new FutureTask<T>(callable);
+ SwingUtilities.invokeLater(future);
+ return future.get();
+ }
+
+ public static void blockTillDisplayed(Component comp) {
+ Point p = null;
+ while (p == null) {
+ try {
+ p = comp.getLocationOnScreen();
+ } catch (IllegalStateException e) {
+ try {
+ Thread.sleep(100);
+ } catch (InterruptedException ie) {
+ }
+ }
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/border/Test4120351.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,43 @@
+/*
+ * Copyright 1999-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.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 4120351
+ * @summary Tests that the methods createEtchedBorder(int type) and
+ * createEtchedBorder(int type, Color highlight, Color shadows) are added
+ * @author Andrey Pikalev
+ */
+
+import java.awt.Color;
+import javax.swing.BorderFactory;
+import javax.swing.border.EtchedBorder;
+
+public class Test4120351 {
+ public static void main(String[] args) {
+ BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
+ BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
+ BorderFactory.createEtchedBorder(EtchedBorder.RAISED, Color.BLACK, Color.WHITE);
+ BorderFactory.createEtchedBorder(EtchedBorder.LOWERED, Color.WHITE, Color.BLACK);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/border/Test4124729.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,38 @@
+/*
+ * Copyright 1999-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.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 4124729
+ * @summary Test that constrtructor LineBorder(?,?,?) is public
+ * @author Andrey Pikalev
+ */
+
+import java.awt.Color;
+import javax.swing.border.LineBorder;
+
+public class Test4124729 {
+ public static void main(String[] args) {
+ new LineBorder(Color.BLUE, 3, true);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/border/Test4243289.html Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,9 @@
+<html>
+<body>
+When applet starts, you'll see a panel with a TitledBorder with title "Panel Title".
+If this title is overstriken with the border line, test fails, otherwise it passes.
+
+<applet width="600" height="300" code="Test4243289.class">
+</applet>
+</body>
+</html>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/border/Test4243289.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,52 @@
+/*
+ * Copyright 1999-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.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 4243289
+ * @summary Tests that TitledBorder do not draw line through its caption
+ * @author Peter Zhelezniakov
+ * @run applet/manual=yesno Test4243289.html
+ */
+
+import java.awt.Font;
+import javax.swing.BorderFactory;
+import javax.swing.JApplet;
+import javax.swing.JPanel;
+import javax.swing.border.TitledBorder;
+
+public class Test4243289 extends JApplet {
+ public void init() {
+ Font font = new Font("Dialog", Font.PLAIN, 12); // NON-NLS: the font name
+ TitledBorder border = BorderFactory.createTitledBorder(
+ BorderFactory.createEtchedBorder(),
+ "Panel Title", // NON-NLS: the title of the border
+ TitledBorder.DEFAULT_JUSTIFICATION,
+ TitledBorder.DEFAULT_POSITION,
+ font);
+
+ JPanel panel = new JPanel();
+ panel.setBorder(border);
+ getContentPane().add(panel);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/border/Test4247606.html Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,10 @@
+<html>
+<body>
+If the button do not fit into the titled border bounds
+and cover the bottom border's line then test fails.
+Otherwise test passes.
+
+<applet width="200" height="200" code="Test4247606.class">
+</applet>
+</body>
+</html>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/border/Test4247606.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,62 @@
+/*
+ * Copyright 2001-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.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 4247606
+ * @summary BorderedPane appears wrong with Title Position Below Bottom
+ * @author Andrey Pikalev
+ * @run applet/manual=yesno Test4247606.html
+ */
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import javax.swing.BorderFactory;
+import javax.swing.JApplet;
+import javax.swing.JButton;
+import javax.swing.JComponent;
+import javax.swing.JPanel;
+import javax.swing.border.Border;
+import javax.swing.border.TitledBorder;
+
+public class Test4247606 extends JApplet {
+ public void init() {
+ JButton button = new JButton("Button"); // NON-NLS: the button text
+ button.setBorder(BorderFactory.createLineBorder(Color.red, 1));
+
+ TitledBorder border = new TitledBorder("Bordered Pane"); // NON-NLS: the panel title
+ border.setTitlePosition(TitledBorder.BELOW_BOTTOM);
+
+ JPanel panel = create(button, border);
+ panel.setBackground(Color.green);
+
+ getContentPane().add(create(panel, BorderFactory.createEmptyBorder(10, 10, 10, 10)));
+ }
+
+ private static JPanel create(JComponent component, Border border) {
+ JPanel panel = new JPanel(new BorderLayout());
+ panel.setBorder(border);
+ panel.add(component);
+ return panel;
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/border/Test4252164.html Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,10 @@
+<html>
+<body>
+Please, ensure that rounded border is filled completely.
+It should not contain white points inside.
+Use Mouse Wheel to change thickness of the border.
+
+<applet width="400" height="200" code="Test4252164.class">
+</applet>
+</body>
+</html>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/border/Test4252164.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2007-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.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 4252164
+ * @summary Tests rounded LineBorder for components
+ * @author Sergey Malenkov
+ * @run applet/manual=yesno Test4252164.html
+ */
+
+import java.awt.Color;
+import java.awt.event.MouseWheelEvent;
+import java.awt.event.MouseWheelListener;
+import javax.swing.JApplet;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.border.LineBorder;
+
+public class Test4252164 extends JApplet implements MouseWheelListener {
+ private int thickness;
+ private JLabel rounded;
+ private JLabel straight;
+
+ public void mouseWheelMoved(MouseWheelEvent event) {
+ update(event.getWheelRotation());
+ }
+
+ public void init() {
+ add(createUI());
+ addMouseWheelListener(this);
+ }
+
+ private JPanel createUI() {
+ this.rounded = new JLabel("ROUNDED"); // NON-NLS: the label for rounded border
+ this.straight = new JLabel("STRAIGHT"); // NON-NLS: the label for straight border
+
+ JPanel panel = new JPanel();
+ panel.add(this.rounded);
+ panel.add(this.straight);
+
+ update(10);
+
+ return panel;
+ }
+
+ private void update(int thickness) {
+ this.thickness += thickness;
+
+ this.rounded.setBorder(new LineBorder(Color.RED, this.thickness, true));
+ this.straight.setBorder(new LineBorder(Color.RED, this.thickness, false));
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/border/Test6461042.java Tue Aug 12 17:59:58 2008 -0700
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2006-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.
+ *
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 6461042
+ * @summary Tests that toString() doesn't cause StackOverflowException
+ * when a JComponent is its own border
+ * @author Shannon Hickey
+ */
+
+import java.awt.Component;
+import java.awt.Graphics;
+import java.awt.Insets;
+import javax.swing.JComponent;
+import javax.swing.border.Border;
+
+public class Test6461042 extends JComponent implements Border {
+ public static void main(String[] args) {
+ new Test6461042().toString();
+ }
+
+ public Test6461042() {
+ setBorder(this);
+ }
+
+ public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
+ }
+
+ public Insets getBorderInsets(Component c) {
+ return null;
+ }
+
+ public boolean isBorderOpaque() {
+ return false;
+ }
+}